Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/block references: prevent links referencing the same note to include the note name in their name

Adorian Doran2d6fe2beb72e
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.ts
index f728006b14..65031b1f0e 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -317,6 +317,20 @@ describe("Text content renderer", () => {
expect(refLink?.textContent).toContain("Referenced Title");
});
+ it("labels a reference to a block of the rendered note by the text of the block", async () => {
+ const contentEl = document.createElement("div");
+ const note = buildNote({
+ id: "selfRef1",
+ title: "Self",
+ content: "<p data-trilium-block-id=\"b1\">Opening words</p>"
+ + "<p><a class=\"reference-link\" href=\"#root/selfRef1?block=b1\">stale</a></p>"
+ });
+ await renderText(note, $(contentEl));
+ const refLink = contentEl.querySelector("a.reference-link");
+ expect(refLink).not.toBeNull();
+ expect(refLink?.textContent).toBe("Opening words");
+ });
+
it("tolerates reference links without an href", async () => {
const contentEl = document.createElement("div");
const note = buildNote({
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index 72b3f2580a..8f2a7bc5a9 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -81,9 +81,10 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendere
const noteIdsToPrefetch = referenceLinks.map((i, el) => getNoteIdFromLink(el));
await froca.getNotes(noteIdsToPrefetch);
+ const hostNoteId = note instanceof FNote ? note.noteId : undefined;
await Promise.all(referenceLinks.toArray().map(async (el) => {
const innerSpan = document.createElement("span");
- await link.loadReferenceLinkTitle($(innerSpan), el.getAttribute("href"));
+ await link.loadReferenceLinkTitle($(innerSpan), el.getAttribute("href"), hostNoteId);
el.replaceChildren(innerSpan);
}));
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.ts
index c5c46033a1..91014477f6 100644
--- a/apps/client/src/services/link.spec.ts
+++ b/apps/client/src/services/link.spec.ts
@@ -1202,6 +1202,28 @@ describe("block references", () => {
expect(linkService.getReferenceLinkTitleSync(brokenHref)).toBe("Source");
});
+ it("labels a reference to the blocks of the note it is in by their text alone", async () => {
+ const note = buildNote({ title: "Source", content });
+ const $own = $("<span>");
+ const $broken = $("<span>");
+ const $elsewhere = $("<span>");
+
+ const href = `#root/${note.noteId}?block=b1`;
+ const brokenHref = `#root/${note.noteId}?block=gone`;
+ await linkService.loadReferenceLinkTitle($own, href, note.noteId);
+ await linkService.loadReferenceLinkTitle($broken, brokenHref, note.noteId);
+ await linkService.loadReferenceLinkTitle($elsewhere, href, "otherNote");
+
+ expect($own.text()).toBe("First block");
+ expect($own.children("span.tn-icon.bx.bx-paragraph")).toHaveLength(1);
+ expect($own.find("small")).toHaveLength(0);
+ expect($own.hasClass("block-reference-broken")).toBe(false);
+ expect($broken.text()).toBe("block_reference.broken");
+ expect($broken.hasClass("block-reference-broken")).toBe(true);
+ expect($elsewhere.text()).toBe("SourceFirst block");
+ expect($elsewhere.find("small").text()).toBe("First block");
+ });
+
it("adds no label to a reference to the blocks of a note that cannot be read", async () => {
const note = buildNote({ title: "Code", type: "code", content });
const $el = $("<span>");
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index 9cada5a644..58abe84d85 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -670,7 +670,15 @@ function linkContextMenu(e: PointerEvent) {
linkContextMenuService.openContextMenu(notePath, e, viewScope, null);
}
-async function loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | null | undefined = null) {
+/**
+ * Fills `$el` with the label of the reference link to `href`. A link to blocks of `hostNoteId`, the
+ * note the link is in, shows only the text of the blocks.
+ */
+async function loadReferenceLinkTitle(
+ $el: JQuery<HTMLElement>,
+ href: string | null | undefined = null,
+ hostNoteId?: string
+) {
const $link = $el[0].tagName === "A" ? $el : $el.find("a");
href = href || $link.attr("href");
@@ -695,6 +703,16 @@ async function loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | n
const subjectId = viewScope?.card || noteId;
const note = subjectId ? await froca.getNote(subjectId, true) : null;
+ if (viewScope?.block && note && noteId === hostNoteId) {
+ const label = await loadBlockReferenceLabel(note, viewScope.block);
+ if (label) {
+ $el.text(label.text)
+ .toggleClass("block-reference-broken", label.isBroken)
+ .prepend($("<span>").addClass("tn-icon bx bx-paragraph"));
+ return;
+ }
+ }
+
if (note) {
$el.addClass(note.getColorClass());
}
diff --git a/apps/client/src/widgets/dialogs/revisions.spec.tsx b/apps/client/src/widgets/dialogs/revisions.spec.tsx
index 03e76e1b1d..bd3b2c6d89 100644
--- a/apps/client/src/widgets/dialogs/revisions.spec.tsx
+++ b/apps/client/src/widgets/dialogs/revisions.spec.tsx
@@ -20,8 +20,8 @@ vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));
*/
/** Renders revision HTML and lets the reference-link lookups (froca, then the icon) settle. */
-async function renderRevision(content: string) {
- const container = renderInto(<RevisionContentText content={content} />);
+async function renderRevision(content: string, noteId = "revisedNote") {
+ const container = renderInto(<RevisionContentText content={content} noteId={noteId} />);
await vi.waitFor(() => expect(container.querySelector(".ck-content")).toBeTruthy());
return container;
}
@@ -67,6 +67,22 @@ describe("RevisionContentText", () => {
});
});
+ it("labels a reference to a block of the revised note by the text of the block", async () => {
+ const note = buildNote({
+ title: "Revised note",
+ content: "<p data-trilium-block-id=\"b1\">Opening words</p>"
+ });
+ const href = `#root/${note.noteId}?block=b1`;
+ const container = await renderRevision(
+ `<p>before</p><p><a class="reference-link" href="${href}">x</a></p>`,
+ note.noteId
+ );
+
+ const link = container.querySelector("a.reference-link");
+ expect(link).not.toBeNull();
+ await vi.waitFor(() => expect(link?.textContent).toBe("Opening words"));
+ });
+
it("leaves a preview without a URL alone rather than rendering an empty card", async () => {
const container = await renderRevision('<p>before</p><p><span class="link-mention" data-title="No URL"></span></p>');
diff --git a/apps/client/src/widgets/dialogs/revisions.tsx b/apps/client/src/widgets/dialogs/revisions.tsx
index 7afa15f2e5..25a6ace10f 100644
--- a/apps/client/src/widgets/dialogs/revisions.tsx
+++ b/apps/client/src/widgets/dialogs/revisions.tsx
@@ -633,7 +633,7 @@ function RevisionContent({ noteContent, revisionItem, fullRevision, showDiff }:
}
switch (revisionItem.type) {
case "text":
- return <RevisionContentText content={content} />;
+ return <RevisionContentText content={content} noteId={revisionItem.noteId} />;
case "code":
return <div className="revision-diff-code">{content}</div>;
case "image":
@@ -669,7 +669,10 @@ function RevisionContent({ noteContent, revisionItem, fullRevision, showDiff }:
}
}
-export function RevisionContentText({ content }: { content: string | Uint8Array | undefined }) {
+export function RevisionContentText({ content, noteId }: {
+ content: string | Uint8Array | undefined;
+ noteId: string;
+}) {
const contentRef = useRef<HTMLDivElement>(null);
// A revision stores what CKEditor's data downcast produced, and two of those constructs carry
@@ -682,8 +685,8 @@ export function RevisionContentText({ content }: { content: string | Uint8Array
if (!container) return;
applyLinkEmbeds(container);
- void applyReferenceLinks(container);
- }, [content]);
+ void applyReferenceLinks(container, noteId);
+ }, [content, noteId]);
useEffect(() => {
if (contentRef.current?.querySelector("span.math-tex")) {
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx
index 950ca83ba1..ccb9b0f108 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx
@@ -4,12 +4,15 @@ import { useRef } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import link from "../../../services/link";
import CKEditorWithWatchdog, { type CKEditorApi } from "./CKEditorWithWatchdog";
const mocks = vi.hoisted(() => ({
options: {} as Record<string, string | boolean>,
create: vi.fn(async () => {}),
- destroy: vi.fn(async () => {})
+ destroy: vi.fn(async () => {}),
+ note: undefined as { noteId: string; title: string } | undefined,
+ handlers: {} as Record<string, (...args: unknown[]) => unknown>
}));
vi.mock("@triliumnext/ckeditor5", () => {
@@ -34,11 +37,13 @@ vi.mock("@triliumnext/ckeditor5", () => {
vi.mock("../../react/hooks", () => ({
useKeyboardShortcuts: () => {},
- useLegacyImperativeHandlers: () => {},
+ useLegacyImperativeHandlers: (handlers: typeof mocks.handlers) => {
+ mocks.handlers = handlers;
+ },
useNoteContext: () => ({
parentComponent: undefined,
ntxId: undefined,
- note: undefined,
+ note: mocks.note,
notePath: undefined
}),
useSyncedRef: (_externalRef: unknown, initialValue: unknown) => useRef(initialValue),
@@ -57,6 +62,7 @@ let host: HTMLElement;
beforeEach(() => {
mocks.options = { locale: "en", mathFieldEnabled: true };
+ mocks.note = undefined;
mocks.create.mockClear();
mocks.destroy.mockClear();
host = document.body.appendChild(document.createElement("div"));
@@ -110,4 +116,26 @@ describe("CKEditorWithWatchdog", () => {
await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalledOnce());
expect(props.watchdogRef.current).toBeNull();
});
+
+ it("labels its reference links as links in the note it edits", async () => {
+ mocks.note = { noteId: "host1", title: "Host" };
+ const loadReferenceLinkTitle = vi.spyOn(link, "loadReferenceLinkTitle")
+ .mockResolvedValue(undefined);
+ const props = {
+ contentLanguage: null,
+ watchdogRef: createRef<EditorWatchdog>(),
+ onChange: vi.fn(),
+ editorApi: createRef<CKEditorApi>(),
+ templates: []
+ };
+ await act(async () => {
+ render(<CKEditorWithWatchdog {...props} />, host);
+ });
+
+ const $el = $("<span>");
+ await mocks.handlers.loadReferenceLinkTitle($el, "#root/host1?block=b1");
+
+ expect(loadReferenceLinkTitle).toHaveBeenCalledWith($el, "#root/host1?block=b1", "host1");
+ loadReferenceLinkTitle.mockRestore();
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index f7e6b7f5b2..7d8b711c00 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@ -224,7 +224,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe
useLegacyImperativeHandlers({
async loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | null = null) {
- await link.loadReferenceLinkTitle($el, href);
+ await link.loadReferenceLinkTitle($el, href, note?.noteId);
},
async fetchLinkMetadata(url: string) {
// The preview's pictures are stored as attachments of the note being edited, so there
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
index 02e12f0593..20e81829e9 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
@@ -330,6 +330,20 @@ describe("ReadOnlyText ?block= handling", () => {
.toBe(container.querySelector("[data-trilium-block-id='b1']"));
});
+ it("labels a link to a block of its note by the text of the block", async () => {
+ const harness = setupHarness({ isVisible: true });
+ cleanupContainer = harness.container;
+ const content = "<p data-trilium-block-id=\"b1\">Opening words</p>"
+ + `<p><a class="reference-link" href="#root/${harness.note.noteId}?block=b1">x</a></p>`;
+ harness.note.getBlob = async () => ({ content }) as never;
+
+ await harness.mount();
+
+ const link = harness.container.querySelector("a.reference-link");
+ expect(link).not.toBeNull();
+ await vi.waitFor(() => expect(link?.textContent).toBe("Opening words"));
+ });
+
it("leaves a link to a block of its note to the editor while hidden", async () => {
const { parent, noteContext, container, scrollIntoView } = await mountWithBlock(
undefined,
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 7e07b2de4b..6a811d384d 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -78,6 +78,7 @@ export default function ReadOnlyText({ note, noteContext, ntxId, parentComponent
<>
<ReadOnlyTextContent
html={blob?.content ?? ""}
+ noteId={note.noteId}
ntxId={ntxId}
dir={isRtl ? "rtl" : "ltr"}
contentRef={readOnlyContentRef}
@@ -89,6 +90,8 @@ export default function ReadOnlyText({ note, noteContext, ntxId, parentComponent
interface ReadOnlyTextContentProps {
/** CKEditor-compatible HTML to render. */
html: string;
+ /** The note `html` belongs to. Reference links to its own blocks show only their text. */
+ noteId?: string;
/** Note context id — enables `contentElRefreshed` / `executeWithContentElement` integrations when provided. */
ntxId?: string | null;
dir?: "ltr" | "rtl";
@@ -104,7 +107,9 @@ interface ReadOnlyTextContentProps {
* titles, code-block syntax highlighting, and image click handling. Transforms re-run
* whenever `html` changes.
*/
-export function ReadOnlyTextContent({ html, ntxId, dir, className, contentRef: externalContentRef }: ReadOnlyTextContentProps) {
+export function ReadOnlyTextContent({
+ html, noteId, ntxId, dir, className, contentRef: externalContentRef
+}: ReadOnlyTextContentProps) {
const contentRef = useSyncedRef(externalContentRef);
const [ codeBlockWordWrap ] = useTriliumOptionBool("codeBlockWordWrap");
const [ codeBlockTabWidth ] = useTriliumOption("codeBlockTabWidth");
@@ -134,13 +139,13 @@ export function ReadOnlyTextContent({ html, ntxId, dir, className, contentRef: e
applyInlineMermaid(container),
applyContentEmbeds(container),
applyLinkEmbeds(container),
- applyReferenceLinks(container),
+ applyReferenceLinks(container, noteId),
formatCodeBlocks($(container))
]));
applyMath(container);
setupImageOpening(container, true);
- }, [ html, ntxId, contentRef ]);
+ }, [ html, noteId, ntxId, contentRef ]);
useEffect(() => {
if (!contentRef.current) return;
diff --git a/apps/client/src/widgets/type_widgets/text/read_only_helper.ts b/apps/client/src/widgets/type_widgets/text/read_only_helper.ts
index 0f43544b6d..b83f261021 100644
--- a/apps/client/src/widgets/type_widgets/text/read_only_helper.ts
+++ b/apps/client/src/widgets/type_widgets/text/read_only_helper.ts
@@ -1,9 +1,13 @@
import link from "../../../services/link";
-export async function applyReferenceLinks(container: HTMLDivElement | HTMLElement) {
+/** Fills the reference links in `container`, which shows content of `hostNoteId` if given. */
+export async function applyReferenceLinks(
+ container: HTMLDivElement | HTMLElement,
+ hostNoteId?: string
+) {
const referenceLinks = container.querySelectorAll<HTMLDivElement>("a.reference-link");
for (const referenceLink of referenceLinks) {
- await link.loadReferenceLinkTitle($(referenceLink));
+ await link.loadReferenceLinkTitle($(referenceLink), null, hostNoteId);
// Wrap in a <span> to match the design while in CKEditor.
const spanEl = document.createElement("span");
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html
index b30f331aa5..2fffe2269f 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Block references.html
@@ -14,7 +14,8 @@
<li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li>
</ol>
<p>The link shows the title of the note, followed by the beginning of the
- referenced text.</p>
+ referenced text. A link to blocks of the same note shows only the beginning
+ of the referenced text.</p>
<h2>Following a reference</h2>
<p>Clicking a block reference opens the note, scrolls to the referenced blocks
and flashes them. If a referenced block was deleted, an error message is
diff --git a/docs/User Guide/User Guide/Note Types/Text/Block references.md b/docs/User Guide/User Guide/Note Types/Text/Block references.md
index c590092165..3c31ea667c 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Block references.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Block references.md
@@ -8,7 +8,7 @@ Block references are [links](Links.md) to a block of a text note, such as a para
3. Select _Copy reference to this block_, or _Copy reference to these blocks_ for a selection. The referenced blocks flash briefly.
4. Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.
-The link shows the title of the note, followed by the beginning of the referenced text.
+The link shows the title of the note, followed by the beginning of the referenced text. A link to blocks of the same note shows only the beginning of the referenced text.
## Following a reference