Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/link: stop note links initiating the navigation on click

Adorian Doran73aa4f6ffd2c
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.ts
index c1fd3239c7..05c3356cdb 100644
--- a/apps/client/src/services/link.spec.ts
+++ b/apps/client/src/services/link.spec.ts
@@ -780,6 +780,39 @@ describe("goToLinkExt", () => {
openSpy.mockRestore();
});
+ it("leaves a plain left click on a note link in an editable text note to the link toolbar", () => {
+ const $editor = $("<div class='ck-content note-detail-editable-text-editor'>");
+ const $link = $("<a href='#root/aaaaaaaaaaaa'>");
+ const $embed = $("<div class='ck-content'>");
+ const $embeddedLink = $("<a href='#root/aaaaaaaaaaaa'>");
+ $editor.append($link, $embed.append($embeddedLink));
+
+ goToLinkExt(leftClick(), "#root/aaaaaaaaaaaa", $link);
+ goToLinkExt(leftClick(), "#root/aaaaaaaaaaaa?popup=1", $link);
+ expect(openInCurrentNoteContext).not.toHaveBeenCalled();
+ expect(triggerCommand).not.toHaveBeenCalled();
+
+ // The modifiers still open the note, and a link in an embed still navigates.
+ goToLinkExt(leftClick({ ctrlKey: true }), "#root/aaaaaaaaaaaa", $link);
+ expect(openTabWithNoteWithHoisting).toHaveBeenCalledOnce();
+ goToLinkExt(leftClick({ type: "dblclick" }), "#root/aaaaaaaaaaaa", $link);
+ expect(openTabWithNoteWithHoisting).toHaveBeenCalledTimes(2);
+ goToLinkExt(leftClick({ shiftKey: true }), "#root/aaaaaaaaaaaa", $link);
+ expect(triggerCommand).toHaveBeenCalledWith("openInWindow", expect.anything());
+ goToLinkExt(leftClick(), "#root/aaaaaaaaaaaa", $embeddedLink);
+ expect(openInCurrentNoteContext).toHaveBeenCalledOnce();
+ });
+
+ it("opens a note in place from the preview button of the link toolbar", () => {
+ const $preview = $("<a class='ck-link-toolbar__preview' target='_blank'>");
+ goToLinkExt(leftClick(), "#root/aaaaaaaaaaaa", $preview);
+ expect(openInCurrentNoteContext).toHaveBeenCalledOnce();
+ expect(openTabWithNoteWithHoisting).not.toHaveBeenCalled();
+
+ goToLinkExt(leftClick({ ctrlKey: true }), "#root/aaaaaaaaaaaa", $preview);
+ expect(openTabWithNoteWithHoisting).toHaveBeenCalledOnce();
+ });
+
it("does nothing when there is neither a note path nor an href", () => {
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
expect(goToLinkExt(leftClick(), undefined)).toBe(true);
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index f2e0af6c10..b7f93dad23 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -562,13 +562,21 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDo
const isLeftClick = !evt || ("which" in evt && evt.which === 1);
// Right click is handled separately.
const isMiddleClick = evt && "which" in evt && evt.which === 2;
- const targetIsBlank = ($link?.attr("target") === "_blank");
+ // The preview button of the text editor's link toolbar opens a note in place, as a link does.
+ const isLinkToolbarPreview = !!$link?.hasClass("ck-link-toolbar__preview");
+ const targetIsBlank = $link?.attr("target") === "_blank" && !isLinkToolbarPreview;
const isDoubleClick = isLeftClick && evt?.type === "dblclick";
const openInNewTab = (isLeftClick && (ctrlKey || targetIsBlank)) || isDoubleClick || isMiddleClick;
const activate = (isLeftClick && ctrlKey && shiftKey) || (isMiddleClick && shiftKey);
const openInNewWindow = isLeftClick && evt?.shiftKey && !ctrlKey;
+ const isPlainLeftClick = isLeftClick && !ctrlKey && !shiftKey && !isDoubleClick;
if (notePath) {
+ if (isPlainLeftClick && $link && isInEditableText($link)) {
+ // The text editor shows the link toolbar, whose preview button opens the note.
+ return true;
+ }
+
if (isLeftClick && openInPopup) {
appContext.triggerCommand("openInPopup", { noteIdOrPath: notePath, viewScope });
} else if (openInNewWindow) {
@@ -583,10 +591,9 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDo
openInCurrentNoteContext(evt, notePath, viewScope);
}
} else if (hrefLink) {
- const withinEditLink = $link?.hasClass("ck-link-actions__preview");
const outsideOfCKEditor = !$link || $link.closest("[contenteditable]").length === 0;
- if (openInNewTab || openInNewWindow || (isLeftClick && (withinEditLink || outsideOfCKEditor))) {
+ if (openInNewTab || openInNewWindow || (isLeftClick && (isLinkToolbarPreview || outsideOfCKEditor))) {
if (hrefLink.toLowerCase().startsWith("http") || hrefLink.startsWith("api/")) {
window.open(hrefLink, "_blank");
} else if (ALLOWED_PROTOCOLS.some((protocol) => hrefLink.toLowerCase().startsWith(`${protocol}:`))) {
@@ -618,6 +625,11 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDo
return true;
}
+/** Whether `$link` is in the content of an editable text note, rather than in an embed in it. */
+function isInEditableText($link: JQuery<HTMLElement>) {
+ return $link.closest(".ck-content").hasClass("note-detail-editable-text-editor");
+}
+
/**
* Scrolls to either the footnote (if clicking on a reference such as `[1]`), or to the reference of a footnote (if clicking on the footnote `^` arrow),
* or CKEditor bookmarks.
diff --git a/apps/client/src/services/note_tooltip.spec.ts b/apps/client/src/services/note_tooltip.spec.ts
index 2056e974bc..e337d17c1e 100644
--- a/apps/client/src/services/note_tooltip.spec.ts
+++ b/apps/client/src/services/note_tooltip.spec.ts
@@ -106,6 +106,7 @@ afterEach(() => {
// Clear any tracked tooltip elements while the .tooltip stub is still installed.
dismissAllTooltips();
document.body.classList.remove("context-menu-shown");
+ $(".ck-balloon-panel").remove();
$.fn.filter = origFilter;
$.fn.is = origIs;
delete ($.fn as any).tooltip;
@@ -351,18 +352,44 @@ describe("mouseEnterHandler", () => {
expect(parseNavigationStateFromUrl).not.toHaveBeenCalled();
});
- it("ignores links opted out via class, CK link actions, or inside a tooltip", async () => {
+ it("ignores links opted out via class, or inside a tooltip", async () => {
const $a = makeLink('<a class="no-tooltip-preview" href="#root/a">a</a>');
- const $b = makeLink('<div class="ck-link-actions"><a href="#root/b">b</a></div>').find("a");
const $c = makeLink('<div class="note-tooltip"><a href="#root/c">c</a></div>').find("a");
await mouseEnterHandler.call($a[0], eventFor($a));
- await mouseEnterHandler.call($b[0], eventFor($b));
await mouseEnterHandler.call($c[0], eventFor($c));
expect(parseNavigationStateFromUrl).not.toHaveBeenCalled();
});
+ it("stays off a link toolbar of the text editor, whether already shown or opened mid-flight", async () => {
+ vi.useFakeTimers();
+ const $link = makeLink('<a data-href="#root/abc">x</a>');
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "root/abc", noteId: "abc", viewScope: { viewMode: "default" } });
+ froca.getNote = vi.fn(async () => fakeNote({ noteId: "abc", bestPath: "root/abc" })) as unknown as typeof froca.getNote;
+ hoverActive = true;
+ const linkToolbar = makeLink(
+ '<div class="ck-balloon-panel ck-balloon-panel_visible"><div class="ck-toolbar ck-link-toolbar"></div></div>');
+ const referenceToolbar = makeLink(
+ '<div class="ck-balloon-panel ck-balloon-panel_visible reference-link-toolbar"></div>');
+
+ // Shown when the pointer arrives, as when it moves to the toolbar's "Open note" button.
+ await mouseEnterHandler.call($link[0], eventFor($link));
+ linkToolbar.remove();
+ await mouseEnterHandler.call($link[0], eventFor($link));
+ expect(parseNavigationStateFromUrl).not.toHaveBeenCalled();
+
+ // Opened while the delayed preview was in flight, as a click on the link opens it.
+ referenceToolbar.removeClass("ck-balloon-panel_visible");
+ const promise = mouseEnterHandler.call($link[0], eventFor($link));
+ referenceToolbar.addClass("ck-balloon-panel_visible");
+ await vi.advanceTimersByTimeAsync(600);
+ await promise;
+
+ expect(parseNavigationStateFromUrl).toHaveBeenCalled();
+ expect($.fn.tooltip as unknown as ReturnType<typeof vi.fn>).not.toHaveBeenCalled();
+ });
+
it("ignores footnote back-reference links (#fnref...)", async () => {
const $link = makeLink('<a href="#fnref1">^</a>');
parseNavigationStateFromUrl.mockReturnValue({ notePath: "p", noteId: "x", viewScope: { viewMode: "default" } });
@@ -403,6 +430,25 @@ describe("mouseEnterHandler", () => {
expect($.fn.tooltip as unknown as ReturnType<typeof vi.fn>).not.toHaveBeenCalled();
});
+ it("dismisses an open preview once a link toolbar opens without a click", async () => {
+ vi.useFakeTimers();
+ const $link = makeLink('<a href="#root/abc">x</a>');
+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "root/abc", noteId: "abc", viewScope: { viewMode: "default" } });
+ froca.getNote = vi.fn(async () => fakeNote({ noteId: "abc", bestPath: "root/abc" })) as unknown as typeof froca.getNote;
+ hoverActive = true;
+
+ const promise = mouseEnterHandler.call($link[0], eventFor($link));
+ await vi.advanceTimersByTimeAsync(600);
+ await promise;
+ const tooltip = $.fn.tooltip as unknown as ReturnType<typeof vi.fn>;
+ expect(tooltip).toHaveBeenCalledWith("show");
+
+ // A reference link selected with the keyboard shows its toolbar while the pointer stays.
+ makeLink('<div class="ck-balloon-panel ck-balloon-panel_visible reference-link-toolbar"></div>');
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(tooltip).toHaveBeenCalledWith("dispose");
+ });
+
it("shows nothing for a link that takes the opt-out while its preview is in flight", async () => {
vi.useFakeTimers();
const $link = makeLink('<a data-href="#root/abc">x</a>');
@@ -730,8 +776,6 @@ describe("setup helpers and dismissAllTooltips", () => {
const pointerSelectors = calls.filter((c) => c[0] === "pointerenter").map((c) => c[1]);
expect(pointerSelectors).toContain("a:not(.no-tooltip-preview)");
expect(pointerSelectors).toContain("[data-href]:not(.no-tooltip-preview)");
- // a global click handler is also registered (no delegation selector)
- expect(calls.some((c) => c[0] === "click")).toBe(true);
onSpy.mockRestore();
});
@@ -744,11 +788,15 @@ describe("setup helpers and dismissAllTooltips", () => {
// Click inside a .note-tooltip -> handler returns early, no dispose.
const $inside = $('<div class="note-tooltip"><span class="target">hi</span></div>');
$("body").append($inside);
- $(document).trigger($.Event("click", { target: $inside.find(".target")[0] }));
+ $inside.find(".target")[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
expect(($tracked as any).tooltip).not.toHaveBeenCalledWith("dispose");
- // Click outside -> dismissAllTooltips disposes the tracked element.
- $(document).trigger($.Event("click", { target: document.body }));
+ // A click on the link dismisses it, though its handler stops the propagation as
+ // `goToLink()` does, which is how a click opens the link toolbar of the text editor.
+ const stopAtLink = (e: JQuery.ClickEvent) => e.stopPropagation();
+ $(document).on("click", "a", stopAtLink);
+ $tracked[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ $(document).off("click", "a", stopAtLink);
expect(($tracked as any).tooltip).toHaveBeenCalledWith("dispose");
});
diff --git a/apps/client/src/services/note_tooltip.ts b/apps/client/src/services/note_tooltip.ts
index 87a25bc109..5d58c09238 100644
--- a/apps/client/src/services/note_tooltip.ts
+++ b/apps/client/src/services/note_tooltip.ts
@@ -19,15 +19,16 @@ function setupGlobalTooltip() {
$(document).on("pointerenter", "a:not(.no-tooltip-preview)", mouseEnterHandler);
$(document).on("pointerenter", "[data-href]:not(.no-tooltip-preview)", mouseEnterHandler);
- // close any note tooltip after click, this fixes the problem that sometimes tooltips remained on the screen
- $(document).on("click", (e) => {
- if ($(e.target).closest(".note-tooltip").length) {
+ // close any note tooltip after click, this fixes the problem that sometimes tooltips remained on the screen.
+ // Captured, as `goToLink()` stops the propagation of a click on a link.
+ document.addEventListener("click", (e) => {
+ if ($(e.target as Element).closest(".note-tooltip").length) {
// click within the tooltip shouldn't close it
return;
}
dismissAllTooltips();
- });
+ }, true);
}
function dismissAllTooltips() {
@@ -52,16 +53,23 @@ function isContextMenuShown() {
return document.body.classList.contains("context-menu-shown");
}
+/**
+ * Whether the text editor shows the toolbar of a link: the link toolbar of CKEditor, or the widget
+ * toolbar of a reference link. A preview opens below a link, which is where that toolbar sits.
+ */
+function isLinkToolbarShown() {
+ return document.querySelector(
+ ".ck-balloon-panel_visible .ck-link-toolbar, .ck-balloon-panel_visible.reference-link-toolbar"
+ ) !== null;
+}
+
export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.TriggeredEvent<T, undefined, T, T>) {
- if (e.pointerType !== "mouse" || isContextMenuShown()) return;
+ if (e.pointerType !== "mouse" || isContextMenuShown() || isLinkToolbarShown()) return;
const $link = $(this);
if ($link.hasClass("no-tooltip-preview") || $link.hasClass("disabled")) {
return;
- } else if ($link.closest(".ck-link-actions").length) {
- // this is to avoid showing tooltip from inside the CKEditor link editor dialog
- return;
} else if ($link.closest(".note-tooltip").length) {
// don't show tooltip for links within tooltip
return;
@@ -135,14 +143,16 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.Triggere
// we need to check if we're still hovering over the element
// since the operation to get tooltip content was async, it is possible that
// we now create tooltip which won't close because it won't receive mouseleave event
- // — or that a context menu was invoked in the meantime, which the preview must not cover.
+ // — or that a context menu or a link toolbar opened in the meantime, which the preview must
+ // not cover.
//
// The opt-out is re-read for the same reason: an element may take it on while its preview is
// being fetched, which is how a surface that opens over the pointer says the preview is no
// longer wanted — a calendar chip clicked gains it as the popover opens (see the class in
// CalendarView's eventClassNames), and the pointer is still on the chip, so the hover test
// alone would let the preview land on top of what the click just opened.
- if ($link.filter(":hover").length > 0 && !isContextMenuShown() && !$link.hasClass("no-tooltip-preview")) {
+ if ($link.filter(":hover").length > 0 && !isContextMenuShown() && !isLinkToolbarShown()
+ && !$link.hasClass("no-tooltip-preview")) {
$link.tooltip({
container: "body",
// https://github.com/zadam/trilium/issues/2794 https://github.com/zadam/trilium/issues/2988
@@ -181,8 +191,10 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.Triggere
// - once the user moves the cursor away from both link and the tooltip, hide the tooltip
const checkTooltip = () => {
- if (!$link.filter(":hover").length && !$(`.${linkId}:hover`).length) {
- // cursor is neither over the link nor over the tooltip, user likely is not interested
+ if (isLinkToolbarShown()
+ || (!$link.filter(":hover").length && !$(`.${linkId}:hover`).length)) {
+ // a link toolbar opened under the tooltip, or the cursor is neither over the link nor
+ // over the tooltip, user likely is not interested
dismissAllTooltips();
} else {
dismissTimer = setTimeout(checkTooltip, 1000);
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 3f2f42203b..a2fd6392ed 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4699,7 +4699,9 @@
"insert-a-code-block-that-is-edited-as-a-code-note": "Insert a code block that is edited as a code note.",
"new-child-note": "New child note",
"create-a-new-child-note": "Create a new child note",
- "create-a-new-child-note-and-insert-a-link-to-it": "Create a new child note and insert a link to it"
+ "create-a-new-child-note-and-insert-a-link-to-it": "Create a new child note and insert a link to it",
+ "open-note": "Open note",
+ "open-attachment": "Open attachment"
},
"task-state-dropped-title": "Invalid task states",
"task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
index fae7d2009e..d53d07513b 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
@@ -492,6 +492,15 @@ describe("getEditLinkOpts", () => {
.toHaveBeenCalledExactlyOnceWith("https://example.com", "card", "Example", "About");
});
+ it("edits a selected reference link with its title still mirroring the note's", () => {
+ const api = createApi({
+ href: "#root/abc", text: "Target", display: "plain", isReference: true
+ });
+ const opts = getEditLinkOpts(api, ready);
+ expect(opts).toMatchObject({ text: "Target", currentLink: { notePath: "root/abc" } });
+ expect(opts.currentTitle).toBeUndefined();
+ });
+
it("edits a selected link preview as a web link titled by its title, shown as it is", () => {
const api = createApi({
href: "https://example.com", text: "Example", description: "About", display: "card"
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 0394bd6191..d9c197bbbe 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -604,7 +604,7 @@ export function getEditLinkOpts(
return {
text: currentLink.text,
hasSelection: false,
- currentTitle: currentLink.text,
+ currentTitle: currentLink.isReference ? undefined : currentLink.text,
currentDescription: currentLink.description,
display: currentLink.display,
anchors,
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index 053c46afae..2a4375c830 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -141,7 +141,7 @@
"_help_UmgZAfcltxkS": "<p>Link previews turn a pasted URL into a rich, metadata-aware widget that can be displayed in three visual modes:</p><h2>Display modes</h2><p>A link preview can be displayed in one of three modes:</p><ul><li><strong>Inline</strong> — a link showing the site's favicon and page title (quite similar to&nbsp;<a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a>). Use this when you want the link to flow with the surrounding paragraph.</li><li><strong>Card</strong> — a block-level preview with thumbnail, title, description, and site name. Use this when the link is the focus of a paragraph.</li><li><strong>Embed</strong> — a block-level interactive embed.<ul><li>Currently supported for YouTube videos, which render interactively (via an <code>iframe</code>).</li><li>To prevent unwanted remote requests, the video is shown only after clicking on it first. Until then, the video's thumbnail is shown with a play button.</li></ul></li></ul><div class=\"trilium-multicolumn-layout\" data-trilium-column-ratios=\"1-1-1\"><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:251/42;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Link%20Previews_image.png\" width=\"251\" height=\"42\"><figcaption><em>Inline</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:1217/196;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Link%20Previews_image.png\" width=\"1217\" height=\"196\"><figcaption><em>Card</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:994/563;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Link%20Previews_image.png\" width=\"994\" height=\"563\"><figcaption><em>Embed</em> link preview</figcaption></figure></div></div><h2>Inserting a link preview</h2><p>There are three ways to create one:</p><h3>1. By pasting a URL</h3><p>A link preview is automatically created:</p><ul><li>By pasting the URL and pressing <kbd>Space</kbd>. This will create an <em>inline</em> link preview.</li><li>When at the start of a new paragraph, pressing <kbd>Enter</kbd> will create a <em>card</em> or an <em>embed</em> for YouTube URLs.</li></ul><p>To undo an automatic link preview, press <kbd>Ctrl</kbd>+<kbd>Z</kbd> immediately afterwards which keeps it as a plain link instead. Alternatively, once a link preview was created, click on the link and select <em>Plain link</em> from the link preview toolbar.</p><p>This automatic conversion can be disabled by going to&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>Text Notes</em> and unchecking <em>Autogenerate link previews</em> from the <em>Features</em> section.</p><p>If the link is not accessible to the Trilium server (or the network request fails for any other reason), it will not be converted to a link preview.</p><aside class=\"admonition note\"><p>A URL is only auto-converted when the pasted text <em>is</em> the URL. Links with a display name (e.g. <a href=\"https://triliumnotes.org\">Trilium Notes website</a>) are left as plain links.</p></aside><h3>2. From the link dialog</h3><p>Since v0.107.0, a link preview is created from the same <em>Add link</em> dialog as any other link (see <a class=\"reference-link\" href=\"#root/_help_3IDVtesTQ8ds\">External links</a>):</p><ul><li>Press <span class=\"tn-icon cke cke-link\"></span> in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, or press <kbd>Ctrl</kbd>+<kbd>K</kbd>, to open the dialog on <em>Web link</em>.</li><li>Type or paste the address, then pick the preview in <em>Display as</em>: <em>Inline</em>, <em>Card</em> or, for a YouTube video, <em>YouTube embed</em>. <em>Plain link</em> inserts an ordinary link. <em>Display as</em> is not shown when text is selected, since the link then keeps the selected text.</li><li>Optionally, type a <em>Link title</em> to show instead of the page's own title. A <em>Card</em> also offers a <em>Description</em> to show instead of the page's own description.</li><li>Press <kbd>Enter</kbd> or <em>Add link</em> to confirm. The link appears right away and turns into the preview once Trilium has read the page.</li></ul><p>Alternatively, use <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a> and look for <em>link preview</em> (it is also found by <em>embed</em>, <em>url</em> or <em>video</em>). It opens the same dialog with a preview already picked: a <em>YouTube embed</em> for a YouTube video, a <em>Card</em> for any other page.</p><p>To turn an existing link into a preview, open its <em>Edit link</em> dialog and change <em>Display as</em>. A link whose text differs from its address keeps that text as the title of the preview.</p><h3>3. By saving browser tabs from the Web Clipper</h3><p>When the&nbsp;<a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a>&nbsp;saves the tabs of a window, each tab becomes an <em>inline</em> link preview showing the title and favicon the browser displays for it. Because this data comes from the browser, pages behind a login keep their real title, and the Trilium server does not contact the saved pages.</p><p>When <em>Autogenerate link previews</em> is turned off, the tabs are saved as a list of plain links instead.</p><h2>Altering an existing link preview</h2><p>Click on an inserted link preview to select it, and a small toolbar will appear with the following options:</p><ul><li>The normal link operations (opening in a new tab, copying the link, unlinking).</li><li>The <span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> button, which opens the <em>Edit link</em> dialog on the link preview, as does pressing <kbd>Ctrl</kbd>+<kbd>K</kbd> while it is selected. The dialog changes its address, its <em>Link title</em> (especially useful if the title is hidden behind a login screen), the <em>Description</em> of a card and how it is displayed. A new address shows the title and description of the new page, unless you type your own.</li><li>A way to switch between the link preview modes (Inline, Card or Embed) as well as to convert it to a normal link instead.<ul><li>The Embed option is only enabled when the URL points to a supported service (YouTube today).</li></ul></li></ul><h2>Where the preview data comes from</h2><p>When you insert a link preview, Trilium fetches metadata once and stores it with the note:</p><ul><li><strong>YouTube URLs</strong>: the title and channel name are fetched via YouTube's public oEmbed endpoint, and the video's thumbnail is downloaded at up to 1280×720.</li><li><strong>All other URLs</strong>: Trilium fetches the page and reads OpenGraph tags (<code>og:title</code>, <code>og:description</code>, <code>og:image</code>, <code>og:site_name</code>), falling back to the page's <code>&lt;title&gt;</code> and <code>&lt;meta name=\"description\"&gt;</code>. The site's favicon and the page's image are downloaded as well.</li></ul><p>The text is kept in the note's HTML. The images are kept as system&nbsp;<a class=\"reference-link\" href=\"#root/_help_0vhv7lsOLy82\">Attachments</a> of the note, listed under <em>Generated by Trilium</em>.</p><p>Because the data is stored in the note itself, link previews continue to render correctly when you reopen the note, share/publish it, or export to HTML — without any further network requests.</p><p>The metadata is captured <strong>at insertion time</strong> and is not automatically refreshed. If the linked page later changes its title or thumbnail, you'll need to re-insert the link to pick up the new values. To refresh a link, simply create it again.</p><p>A YouTube embed inserted before v0.107.0 keeps its smaller thumbnail, shown blurred, until the link is inserted again.</p><p>When accessing a&nbsp;<a class=\"reference-link\" href=\"#root/_help_WOcw2SLH6tbX\">Server Installation</a>, the data is fetched from the remote URL by the server and not the client.</p><h2>Known limitations</h2><ul><li>The Embed display mode currently only supports YouTube. Other video and media platforms fall back to a Card preview.</li><li>Pages that block automated fetches may produce a minimal preview (hostname only).</li><li>Link previews require the Trilium server to reach the target URL, so they won't generate previews for pages on networks the server can't see.</li></ul>",
"_help_QEAPj01N5f7w": "<p>There are two types of links:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_3IDVtesTQ8ds\">External links</a>, for standard hyperlinks to websites or other resources.</li><li><a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a>&nbsp;for links to other notes within Trilium.<ul><li>The list of notes that refer to a particular note is called&nbsp;<a class=\"reference-link\" href=\"#root/_help_wfGXLmm7x27z\">Backlinks</a>.</li></ul></li></ul><h2>Note map</h2><p>Trilium provides a visualization of incoming and outgoing links for a particular note. See <a href=\"#root/_help_BCkXAVs63Ttv\">note map</a> for details.</p>",
"_help_3IDVtesTQ8ds": "<p>An external link is a standard web link targeting for example a website. For example, <a href=\"https://en.wikipedia.org/wiki/South_China_Sea\">https://en.wikipedia.org/wiki/South_China_Sea</a> is an external link to a Wikipedia page.</p><p>To create a link without a custom text:</p><ul><li>Press&nbsp;<span class=\"tn-icon cke cke-link\"></span> in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, or press <kbd>Ctrl</kbd>+<kbd>K</kbd>:<ul><li>Since v0.107.0, the <em>Add link</em> dialog opens on <em>Web link</em>, in a popup next to the cursor on desktop. Type or paste the address, and optionally a <em>Link title</em>; without one, the link shows its address.</li><li><em>Display as</em> inserts the address as a <em>Plain link</em>, or as one of the <a class=\"reference-link\" href=\"#root/_help_UmgZAfcltxkS\">Link Previews</a>: <em>Inline</em>, <em>Card</em> or, for a YouTube video, <em>YouTube embed</em>.</li><li>Press <kbd>Enter</kbd> or <em>Add link</em> to confirm.</li></ul></li><li>A simpler way is to paste the raw link and press space to turn it automatically into a link.</li><li>The&nbsp;<span class=\"tn-icon cke cke-trilium\"></span> button and <kbd>Ctrl</kbd>+<kbd>L</kbd> of&nbsp;<a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> open the same dialog on <em>Note</em>. Select <em>Web link</em> at the top of the dialog to create an external link from there.</li></ul><p>An address without a scheme, such as <code>example.com</code>, gets <code>https://</code>. A URL pasted into the <em>Note</em> field, or picked from its search, switches the dialog to <em>Web link</em>. The dialog also opens on <em>Web link</em> when the selected text is a URL.</p><p>To create a link with a custom text:</p><ul><li>First, type and select the text which will be turned into a link.</li><li>Open the <em>Add link</em> dialog as above (via the formatting toolbar, or <kbd>Ctrl</kbd>+<kbd>K</kbd>). The selected text becomes the text of the link, so the dialog does not offer <em>Display as</em>.</li><li>Alternatively, simply paste (<kbd>Ctrl</kbd>+<kbd>V</kbd>) over the selected text to turn it into a link.</li></ul><p>Once a link is inserted:</p><ul><li>The text inside the link can be changed if needed but the link itself will remain.</li><li>To modify the link, click on the link to display the popup and press the&nbsp;<span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> button. It opens the <em>Edit link</em> dialog, filled with the link's address and text, as do placing the cursor inside the link and pressing <kbd>Ctrl</kbd>+<kbd>K</kbd>, <kbd>Ctrl</kbd>+<kbd>L</kbd> or one of the link buttons. <em>Save link</em> changes the whole link, its text included, and the dialog can also turn it into a link to a note.</li><li>To remove a link, click on it and press the&nbsp;<span class=\"tn-icon cke cke-unlink\"></span> <em>Unlink</em> button.</li></ul><p>You can follow external link by either double clicking (will open new tab/window) it or right clicking on them and choosing \"Open in new tab\".</p>",
- "_help_hrZ1D00cLbal": "<p>Internal links are links to other notes within Trilium.</p><p>You can open an internal link by clicking it. You can also see a read-only preview of an internal link's contents by hovering over it.</p><h2>Inserting internal links</h2><p>Internal links can be created at the current position in a text note by:</p><ol><li>Pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the&nbsp;<span class=\"tn-icon cke cke-trilium\"></span> button underneath the&nbsp;<span class=\"tn-icon cke cke-plus\"></span> menu in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. On desktop, the <em>Add link</em> dialog opens in a popup next to the cursor.</li><li>Searching for the title of the desired note to link. It's also possible to create new notes from this dialog by typing a non-existing note title and selecting either <em>Create note</em>, which places it in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_S0Fos78ZfcY7\">Note Inbox</a>&nbsp;(today's day note, or the top level, when no inbox is set), or <em>Create child note</em>, which places it under the note being edited.</li></ol><p>There are two link types, chosen with the <em>Mirror the note's title</em> switch of the dialog, which is on by default:</p><ol><li>With the switch on, the link mirrors the note's title.<ol><li>This is sometimes also called \"reference link\".</li><li>The title of this link cannot be changed. Instead, it will always show the current title of the linked note.</li><li>The icon of the linked note will also be displayed.</li><li>If the linked note is deleted, the link keeps the last title it showed, in red and with a <span class=\"tn-icon bx bx-x\"></span> icon instead of the note icon. Clicking it while editing opens the <em>Fix link</em> dialog, which searches for that title; picking a note, or creating a new one, replaces the link with one to that note.</li></ol></li><li>With the switch off, the link has a title of its own, typed in the <em>Link title</em> field.<ol><li>This will create a traditional hyperlink, where the text of the link can be different from the note title.</li></ol></li></ol><p>Since v0.107.0, to change a link whose title does not mirror the note's, click it and press the <span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> button in its popup, or place the cursor inside it and press <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class=\"tn-icon cke cke-trilium\"></span> button. The <em>Edit link</em> dialog opens on the linked note, with its anchor and the link's text; <em>Save link</em> changes the whole link. Turning <em>Mirror the note's title</em> on there turns it into a link that mirrors the title.</p><h2>In-place linking</h2><p>You can also insert internal links “inline” by using the <code>@</code> symbol:</p><ol><li>Type <code>@</code> in a text note, which will open the note search menu.</li><li>Search for the desired note's title by typing a few characters. Use <kbd>Up</kbd> and <kbd>Down</kbd> to select the correct note, and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to create the link. It's also possible to create new notes with this method by typing a non-existing note title and selecting <em>Create note</em>, as described above, or <em>Create child note</em>. <em>Create child note</em> creates the note under the note being edited without asking for its type, inserts the link and opens the new note in <a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, which offers the note types to turn it into while it is still empty.</li></ol><p>To create an empty child note and link to it before naming it, use <em>New child note</em>, described in <a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</p><h2>Pasting internal links</h2><p>You can also insert internal links by copying a note from the note tree.</p><ol><li>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, select a note and press <kbd>Ctrl</kbd> + <kbd>C</kbd>.</li><li>In a text note, paste the link by pressing <kbd>Ctrl</kbd> + <kbd>V</kbd>.</li></ol>",
+ "_help_hrZ1D00cLbal": "<p>Internal links are links to other notes within Trilium.</p><p>You can open an internal link by clicking it. You can also see a read-only preview of an internal link's contents by hovering over it.</p><p>Since v0.107.0, clicking an internal link while editing a text note shows its popup instead, as clicking an external link does:</p><ul><li><em>Open note</em> opens the linked note, or <em>Open attachment</em> for a link to an attachment.</li><li><span class=\"tn-icon cke cke-trilium-copy\"></span> <em>Copy URL</em> copies the address of the link.</li><li><span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> changes the link, as described below.</li><li><span class=\"tn-icon cke cke-unlink\"></span> <em>Unlink</em> turns the link into plain text.</li></ul><p>To open the note in a new tab without the popup, <kbd>Ctrl</kbd>+click or double-click the link. The preview does not show while the popup is open.</p><h2>Inserting internal links</h2><p>Internal links can be created at the current position in a text note by:</p><ol><li>Pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the&nbsp;<span class=\"tn-icon cke cke-trilium\"></span> button underneath the&nbsp;<span class=\"tn-icon cke cke-plus\"></span> menu in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. On desktop, the <em>Add link</em> dialog opens in a popup next to the cursor.</li><li>Searching for the title of the desired note to link. It's also possible to create new notes from this dialog by typing a non-existing note title and selecting either <em>Create note</em>, which places it in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_S0Fos78ZfcY7\">Note Inbox</a>&nbsp;(today's day note, or the top level, when no inbox is set), or <em>Create child note</em>, which places it under the note being edited.</li></ol><p>There are two link types, chosen with the <em>Mirror the note's title</em> switch of the dialog, which is on by default:</p><ol><li>With the switch on, the link mirrors the note's title.<ol><li>This is sometimes also called \"reference link\".</li><li>The title of this link cannot be changed. Instead, it will always show the current title of the linked note.</li><li>The icon of the linked note will also be displayed.</li><li>If the linked note is deleted, the link keeps the last title it showed, in red and with a <span class=\"tn-icon bx bx-x\"></span> icon instead of the note icon. Clicking it while editing opens the <em>Fix link</em> dialog, which searches for that title; picking a note, or creating a new one, replaces the link with one to that note.</li></ol></li><li>With the switch off, the link has a title of its own, typed in the <em>Link title</em> field.<ol><li>This will create a traditional hyperlink, where the text of the link can be different from the note title.</li></ol></li></ol><p>Since v0.107.0, to change a link, click it and press the <span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> button in its popup. For a link whose title does not mirror the note's, placing the cursor inside it and pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class=\"tn-icon cke cke-trilium\"></span> button works too. The <em>Edit link</em> dialog opens on the linked note, with its anchor and, for a link with a title of its own, the link's text; <em>Save link</em> changes the whole link. Turning <em>Mirror the note's title</em> on or off there switches between the two link types.</p><h2>In-place linking</h2><p>You can also insert internal links “inline” by using the <code>@</code> symbol:</p><ol><li>Type <code>@</code> in a text note, which will open the note search menu.</li><li>Search for the desired note's title by typing a few characters. Use <kbd>Up</kbd> and <kbd>Down</kbd> to select the correct note, and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to create the link. It's also possible to create new notes with this method by typing a non-existing note title and selecting <em>Create note</em>, as described above, or <em>Create child note</em>. <em>Create child note</em> creates the note under the note being edited without asking for its type, inserts the link and opens the new note in <a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, which offers the note types to turn it into while it is still empty.</li></ol><p>To create an empty child note and link to it before naming it, use <em>New child note</em>, described in <a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</p><h2>Pasting internal links</h2><p>You can also insert internal links by copying a note from the note tree.</p><ol><li>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, select a note and press <kbd>Ctrl</kbd> + <kbd>C</kbd>.</li><li>In a text note, paste the link by pressing <kbd>Ctrl</kbd> + <kbd>V</kbd>.</li></ol>",
"_help_wfGXLmm7x27z": "<p>A link points from one note to another; a <em>backlink</em> is that same connection seen from the other end: the list of notes that refer to the current one.</p><p>Backlinks are maintained automatically and are read-only from this side. A backlink disappears when the note that created it removes the link; it cannot be deleted from the note being pointed at.</p><h2>What counts as a backlink</h2><p>Any&nbsp;<a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a>&nbsp;pointing at the current note, which covers two rather different cases:</p><ul><li>Relations that Trilium maintains on your behalf.<ul><li>The most common is <code>internalLink</code>, created whenever a note refers to another one through&nbsp;<a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a>&nbsp;in its text.</li><li>Embedded images (<code>imageLink</code>), relation map connections (<code>relationMapLink</code>) and note inclusions (<code>includeNoteLink</code>) work the same way.</li></ul></li><li>Relations you define yourself.<ul><li>If another note has <code>~author</code> pointing at the current note, that note is listed here as well.</li></ul></li></ul><p>Relations coming from a&nbsp;<a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;are excluded, since a search stores an <code>ancestor</code> relation that would otherwise list every one of its results as a backlink.</p><aside class=\"admonition note\"><p>Only some note types have their content scanned for links:&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>,&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>,&nbsp;<a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a>&nbsp;and&nbsp;<a class=\"reference-link\" href=\"#root/_help_GBBMSlVSOIGP\">AI</a>&nbsp;chats. A link written inside a&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note is not registered and will not appear as a backlink on the target note. A relation set manually on a code note does still count.</p></aside><h2>How entries are displayed</h2><p>Each entry names the note the reference comes from, followed by one of:</p><ul><li><strong>An excerpt</strong> of the surrounding content, with the link itself highlighted. This is available for&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes and for&nbsp;<a class=\"reference-link\" href=\"#root/_help_GBBMSlVSOIGP\">AI</a>&nbsp;chat notes. Roughly 200 characters of context are quoted around the link, trimmed with an ellipsis where the surrounding text is longer, and images are left out.</li><li><strong>The name of the relation</strong>, for every other note type where the source cannot be quoted. This is the case for&nbsp;<a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a>&nbsp;notes and for any note carrying a relation you defined yourself.</li></ul><p>A note is listed once per reference it makes, so a note that links to the current one three times occupies three rows.</p><p>Of note:</p><ul><li>For AI chat notes, only the assistant's own prose is quoted. A chat that reached the note purely through tool calls has nothing to quote and is listed by relation name instead.</li><li>Excerpts are only generated for roughly the first 50 sources. On a heavily referenced note, the remaining entries fall back to showing the relation name.</li></ul><h2>Where backlinks are shown</h2><ul><li>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_KRlZFoIH0j6p\">Connections tab</a>&nbsp;of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>, as a dedicated section.</li><li>As a badge in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>&nbsp;showing the number of backlinks. The badge only appears when the note is being read normally (not in a revision or attachment view) and when there is at least one backlink; pressing it opens the section above.</li><li>In&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, as a button with a link icon in the header of the popup, under the same conditions; its tooltip gives the number of backlinks. Pressing a backlink opens that note in the popup.</li><li>Incoming links are also drawn on the link map, see&nbsp;<a class=\"reference-link\" href=\"#root/_help_BCkXAVs63Ttv\">Note Map (Link map, Tree map)</a>.</li></ul>",
"_help_S6Xx8QIWTV66": "<p>There are three types of lists supported by text notes:</p><ul><li><span class=\"tn-icon cke cke-bulleted-list\"></span>&nbsp;Bulleted lists (also known as unordered lists).</li><li><span class=\"tn-icon cke cke-numbered-list\"></span>&nbsp;Numbered lists (or ordered lists).</li><li><span class=\"tn-icon cke cke-todo-list\"></span>&nbsp;To-do lists</li></ul><p>For bulleted and numbered lists, it's possible to configure an alternative marker such as squares or Roman numbering by pressing the&nbsp;<span class=\"tn-icon cke cke-dropdown-arrow\"></span> icon. For numbered lists, it's also possible to specify the number to start at or whether to count in reverse order. On the <a class=\"reference-link\" href=\"#root/_help_RDslemsQ6gCp\">Mobile Frontend</a>, these are in the row of the <em>List ›</em> button, which shows while the cursor is in a list; its <em>List type</em> button also turns the list into another kind, to-do lists included.</p><h2>Keyboard interaction</h2><ul><li>To create a new list:<ul><li>Bulleted list: Start a line with <code>*</code> or <code>-</code> followed by a space;</li><li>Numbered list: Start a line with <code>1.</code> or <code>1)</code> followed by a space;</li><li>To-do list: Start a line with <code>- [ ]</code> for an unchecked item or <code>[x]</code> for a checked item.</li></ul></li><li>To create a new item in the list, press <kbd>Enter</kbd>.</li><li>To create a blank line within a list item, press <kbd>Shift</kbd>+<kbd>Enter</kbd>.</li><li>To exit out of the list, press <kbd>Enter</kbd> twice.</li><li>To merge two lists, simply delete the gap between them.</li><li>To create nested lists, simply use the&nbsp;<span class=\"tn-icon cke cke-indent\"></span> button (see <em>Indentation</em> in&nbsp;<a class=\"reference-link\" href=\"#root/_help_dEHYtoWWi8ct\">Other features</a>) or the <kbd>Tab</kbd> key. To decrease the nesting level for the current element, press <kbd>Shift</kbd>+<kbd>Tab</kbd>.</li></ul><h2>Headings, code blocks within lists</h2><p>It possible to add content-level blocks such as headings, code blocks, tables within lists, as follows:</p><figure class=\"table\"><table><tbody><tr><td>1</td><td><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Lists_image.jpg\"></td><td>First, create a list.</td></tr><tr><td>2</td><td><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/4_Lists_image.jpg\"></td><td>Press Enter to create a new list item.</td></tr><tr><td>3</td><td><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Lists_image.jpg\"></td><td>Press Backspace to get rid of the bullet point. Notice the cursor position.</td></tr><tr><td>4</td><td><img class=\"image_resized\" style=\"aspect-ratio:676/112;width:98.29%;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/5_Lists_image.jpg\" width=\"676\" height=\"112\"></td><td>At this point, insert any desired block-level item such as a code block.</td></tr><tr><td>5</td><td><img class=\"image_resized\" style=\"aspect-ratio:675/129;width:94.22%;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Lists_image.jpg\" width=\"675\" height=\"129\"></td><td>To continue with a new bullet point, press Enter until the cursor moves to a new blank position.</td></tr><tr><td>6</td><td><img class=\"image_resized\" style=\"aspect-ratio:675/129;width:100%;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Lists_image.jpg\" width=\"675\" height=\"129\"></td><td>Press Enter once more to create the new bullet.</td></tr></tbody></table></figure><p>The same principle applies to all three list types (bullet, numbered and to-do).</p><h2>Sorting</h2><p>The items of a list can be sorted, nested items moving with the item they belong to. This is experimental, see&nbsp;<a class=\"reference-link\" href=\"#root/_help_0vgWgxQAWj4a\">Sorting</a>.</p><h2>Alignment</h2><p>A list item can be centered or aligned to the right, either with the text alignment button in the formatting toolbar or by aligning the <a class=\"reference-link\" href=\"#root/_help_NdowYOC1GFKS\">Tables</a> cell that contains the list. The bullet, number or checkbox then moves together with the text of the item.</p><h2>To-do lists</h2><p>See&nbsp;<a class=\"reference-link\" href=\"#root/_help_fASfBrYnquKU\">To-do Lists</a>.</p><h2>Collapsible lists</h2><p>Starting with Trilium v0.104.0, it is possible to collapse nested list items. This applies to bullet lists, numbered lists as well as to-do lists.</p><p>To collapse or expand a list item that has nested sub-items:</p><ul><li>Using the mouse, move the cursor over the list item and an arrow will appear to its left. Clicking it will toggle between collapsed and expanded.</li><li>For bullet lists and numbered lists, it's also possible to click directly on the marker (e.g. the bullet or the number) instead of on the arrow to collapse or expand it. This won't work for to-do lists since this would toggle the to-do instead.</li><li>Press <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Enter</kbd> which will toggle the collapse/expand state for the item at the cursor position.</li></ul><p>Of note:</p><ul><li>Collapsed items always show the arrow to indicate its state.</li><li>The collapsed state is saved at note level and synced across instances, which means that it will restore after a refresh or reopening of the application.</li><li>The collapsed state is also persisted in&nbsp;<a class=\"reference-link\" href=\"#root/_help_mHbBMPDPkVV5\">Import &amp; Export</a>, but only for the HTML format. Markdown exports will not preserve the collapse state.</li><li>Collapsible bullets only exist in the context of editable text notes. Read-only lists will always be fully expanded.</li><li>The list items will auto-expand on edit to avoid typing in a hidden area.</li></ul>",
"_help_QrtTYPmdd1qq": "<p>Markdown-like formatting allows inserting some basic formatting by typing the Markdown equivalent. Note that this does not mean that&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes supports Markdown, these are just some convenience shortcuts.</p><p>To import more complex formatting into text notes, consider using the <a href=\"#root/_help_dEHYtoWWi8ct\"><em>Import from Markdown</em></a> function. For fully-fleged Markdown notes imports, consider using the dedicated <a href=\"#root/_help_Oau6X9rCuegd\">import</a> function.</p><ul><li>For <a href=\"#root/_help_Gr6xFaF6ioJ5\">headings:</a><ul><li><code>##</code> for Heading 2 (the first-level heading is reserved for the note title).</li><li><code>###</code> for Heading 3</li><li><code>####</code> for Heading 4</li><li><code>#####</code> for Heading 5</li><li><code>######</code> for Heading 6</li></ul></li><li>For&nbsp;<a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a>:<ul><li><strong>Bold</strong>: Type <code>**text**</code> or <code>__text__</code></li><li><em>Italic</em>: Type <code>*text*</code> or <code>_text_</code></li><li><del>Strikethrough</del>: Type <code>~~text~~</code></li></ul></li><li>For&nbsp;<a class=\"reference-link\" href=\"#root/_help_S6Xx8QIWTV66\">Lists</a>:<ul><li>Bulleted list: Start a line with <code>*</code> or <code>-</code> followed by a space;</li><li>Numbered list: Start a line with <code>1.</code> or <code>1)</code> followed by a space;</li><li>To-do list: Start a line with <code>[ ]</code> for an unchecked item or <code>[x]</code> for a checked item.</li></ul></li><li>For <a href=\"#root/_help_NwBbFdNZ9h7O\">block quotes</a>, press <code>&gt;</code>, followed by a space.</li><li>For&nbsp;<a class=\"reference-link\" href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a>, type <code>```</code>.</li><li>For a <a href=\"#root/_help_dEHYtoWWi8ct\">horizontal line</a>, type <code>---</code>.</li><li>For <a href=\"#root/_help_NwBbFdNZ9h7O\">admonitions</a>:<ul><li><code>!!! note</code></li><li><code>!!! tip</code></li><li><code>!!! important</code></li><li><code>!!! caution</code></li><li><code>!!! warning</code></li><li>Starting any other text with <code>!!!</code> will insert a note admonition with the text inside of it.</li></ul></li><li>For <a href=\"#root/_help_CohkqWQC1iBv\">emojis</a>, type <code>:</code> followed by an emoji name to trigger an auto-completion.</li></ul><p>If auto-formatting is not desirable, press <kbd>Ctrl</kbd> + <kbd>Z</kbd> to revert the text to its original form.</p>",
diff --git a/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md b/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md
index 57052c8822..7f49dd7886 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md
@@ -3,6 +3,15 @@ Internal links are links to other notes within Trilium.
You can open an internal link by clicking it. You can also see a read-only preview of an internal link's contents by hovering over it.
+Since v0.107.0, clicking an internal link while editing a text note shows its popup instead, as clicking an external link does:
+
+* _Open note_ opens the linked note, or _Open attachment_ for a link to an attachment.
+* <span class="tn-icon cke cke-trilium-copy"></span> _Copy URL_ copies the address of the link.
+* <span class="tn-icon cke cke-pencil"></span> _Edit link_ changes the link, as described below.
+* <span class="tn-icon cke cke-unlink"></span> _Unlink_ turns the link into plain text.
+
+To open the note in a new tab without the popup, <kbd>Ctrl</kbd>+click or double-click the link. The preview does not show while the popup is open.
+
## Inserting internal links
Internal links can be created at the current position in a text note by:
@@ -20,7 +29,7 @@ There are two link types, chosen with the _Mirror the note's title_ switch of th
2. With the switch off, the link has a title of its own, typed in the _Link title_ field.
1. This will create a traditional hyperlink, where the text of the link can be different from the note title.
-Since v0.107.0, to change a link whose title does not mirror the note's, click it and press the <span class="tn-icon cke cke-pencil"></span> _Edit link_ button in its popup, or place the cursor inside it and press <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class="tn-icon cke cke-trilium"></span> button. The _Edit link_ dialog opens on the linked note, with its anchor and the link's text; _Save link_ changes the whole link. Turning _Mirror the note's title_ on there turns it into a link that mirrors the title.
+Since v0.107.0, to change a link, click it and press the <span class="tn-icon cke cke-pencil"></span> _Edit link_ button in its popup. For a link whose title does not mirror the note's, placing the cursor inside it and pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class="tn-icon cke cke-trilium"></span> button works too. The _Edit link_ dialog opens on the linked note, with its anchor and, for a link with a title of its own, the link's text; _Save link_ changes the whole link. Turning _Mirror the note's title_ on or off there switches between the two link types.
## In-place linking
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index 29e81bdc8b..3346738323 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -67,6 +67,7 @@ import ContentEmbedToolbar from "./plugins/content_embed/content_embed_toolbar.j
import ContentEmbedCaret from "./plugins/content_embed/content_embed_caret.js";
import ExtendedCodeBlock from "./plugins/content_embed/extended_code_block.js";
import LinkEmbedToolbar from "./plugins/link_embed/link_embed_toolbar.js";
+import NoteLinkToolbar from "./plugins/note_link_toolbar.js";
import TodoListMultistate from "./plugins/todo_list_multistate/todo_list_multistate.js";
import TodoListUncheckOnEnter from "./plugins/todo_list_uncheck_on_enter.js";
import CollapsibleListItems from "./plugins/collapsible_list_items.js";
@@ -127,6 +128,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
ContentEmbedCaret,
ExtendedCodeBlock,
LinkEmbedToolbar,
+ NoteLinkToolbar,
TodoListMultistate,
CollapsibleListItems,
ListItemAlignment,
diff --git a/packages/ckeditor5/src/plugins/internallink.spec.ts b/packages/ckeditor5/src/plugins/internallink.spec.ts
index 8529e1dab9..ba953db94a 100644
--- a/packages/ckeditor5/src/plugins/internallink.spec.ts
+++ b/packages/ckeditor5/src/plugins/internallink.spec.ts
@@ -211,6 +211,27 @@ describe("the link at the selection", () => {
.toStrictEqual({ href: "https://a.example", text: "abc", display: "plain" });
});
+ it("reads a selected reference link, and replaces it with a link or a reference", async () => {
+ const data = () => getModelData(editor.model, { withoutSelection: true });
+ const SELECTED = "<paragraph>a [<reference href=\"#root/abc\"></reference>] b</paragraph>";
+ setModelData(editor.model, SELECTED);
+ expect(getLinkAtSelection(editor)).toStrictEqual(
+ { href: "#root/abc", text: "Target", display: "plain", isReference: true }
+ );
+
+ await replaceLinkAtSelection(editor, "#root/def", "See there");
+ expect(data()).toBe(
+ "<paragraph>a <$text linkHref=\"#root/def\">See there</$text> b</paragraph>"
+ );
+
+ setModelData(editor.model, SELECTED);
+ await replaceLinkAtSelection(editor, "#root/def", null);
+ expect(data()).toBe(
+ "<paragraph>a <reference href=\"#root/def\" storedTitle=\"Target\"></reference> b"
+ + "</paragraph>"
+ );
+ });
+
it("reads a selected link preview as a link titled by its title, shown as it is", () => {
setModelData(editor.model, "<paragraph>a [<linkMention url=\"https://a.example\""
+ " title=\"A\" description=\"About A\"></linkMention>]</paragraph>");
diff --git a/packages/ckeditor5/src/plugins/internallink.ts b/packages/ckeditor5/src/plugins/internallink.ts
index 7b2c222b17..17c376f35d 100644
--- a/packages/ckeditor5/src/plugins/internallink.ts
+++ b/packages/ckeditor5/src/plugins/internallink.ts
@@ -8,7 +8,9 @@ import internalLinkIcon from '../icons/trilium.svg?raw';
import {
getLinkWidgetMode, getSelectedLinkWidget, type LinkDisplayMode
} from './link_embed/link_embed_commands.js';
-import ReferenceLink, { getReferenceTitle, referenceAttributes } from './referencelink';
+import ReferenceLink, {
+ getReferenceTitle, getReferenceTitleSync, getSelectedReference, referenceAttributes
+} from './referencelink';
export const COMMAND_NAME = 'insertInternalLink';
@@ -176,18 +178,35 @@ class InsertInternalLinkCommand extends Command {
}
}
-/** A link in the text, or a link preview, as the link dialog edits it. */
+/** A link in the text, a reference link or a link preview, as the link dialog edits it. */
export interface LinkAtSelection {
href: string;
- /** The whole text of a link, or the title of a preview. */
+ /** The whole text of a link, or the title of a reference link or a preview. */
text: string;
/** The description of a preview. A link has none. */
description?: string;
display: LinkDisplayMode;
+ /** Whether the link is a reference link, whose text follows the title of its note. */
+ isReference?: boolean;
}
-/** The link around the selection or the selected link preview, or `null` outside one. */
+/**
+ * The link around the selection, or the selected reference link or link preview, or `null`
+ * outside one.
+ */
export function getLinkAtSelection(editor: Editor): LinkAtSelection | null {
+ const reference = getSelectedReference(editor);
+ if (reference) {
+ const href = reference.getAttribute('href') as string;
+ const storedTitle = reference.getAttribute('storedTitle') as string | undefined;
+ return {
+ href,
+ text: getReferenceTitleSync(editor, href, storedTitle),
+ display: 'plain',
+ isReference: true
+ };
+ }
+
const preview = getSelectedLinkWidget(editor);
if (preview) {
return {
@@ -213,9 +232,9 @@ export function getLinkAtSelection(editor: Editor): LinkAtSelection | null {
}
/**
- * Replaces the link around the selection or the selected link preview with `text` linking to
- * `href`, keeping the formatting of the link's start, or with a reference to the note at `href`
- * when `text` is `null`. A reference replaces
+ * Replaces the link around the selection, or the selected reference link or link preview, with
+ * `text` linking to `href`, keeping the formatting of the link's start, or with a reference to the
+ * note at `href` when `text` is `null`. A reference replaces
* the link once `getReferenceTitle()` resolves, in one undo step with the removal, and
* takes the caret along only if the user has not moved it in the meantime.
*/
@@ -277,6 +296,11 @@ export function getAnchorNames(editor: Editor): string[] {
function findLinkAtSelection(editor: Editor): { href: string; range: ModelRange } | null {
const model = editor.model;
+ const reference = getSelectedReference(editor);
+ if (reference) {
+ return { href: reference.getAttribute('href') as string, range: model.createRangeOn(reference) };
+ }
+
const preview = getSelectedLinkWidget(editor);
if (preview) {
return { href: preview.getAttribute('url') as string, range: model.createRangeOn(preview) };
diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts
index f8284b806a..9c210f216b 100644
--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts
+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts
@@ -277,7 +277,7 @@ class LinkEmbedEditLinkButton extends Plugin {
* URL in a new tab. Reuses CKEditor's `ck-link-toolbar__preview` styling for
* visual parity with the built-in link toolbar.
*/
-class LinkEmbedPreviewButtonView extends ButtonView {
+export class LinkEmbedPreviewButtonView extends ButtonView {
declare href: string | undefined;
constructor(locale: Locale) {
diff --git a/packages/ckeditor5/src/plugins/note_link_toolbar.spec.ts b/packages/ckeditor5/src/plugins/note_link_toolbar.spec.ts
new file mode 100644
index 0000000000..e1248afb15
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/note_link_toolbar.spec.ts
@@ -0,0 +1,149 @@
+import {
+ _getModelData as getModelData, _setModelData as setModelData, ButtonView, type ClassicEditor,
+ ContextualBalloon, Essentials, Link, LinkUI, Paragraph, type ToolbarView,
+ WidgetToolbarRepository
+} from "ckeditor5";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import { LinkEmbedPreviewButtonView } from "./link_embed/link_embed_toolbar.js";
+import NoteLinkToolbar, { UNLINK_REFERENCE_COMMAND } from "./note_link_toolbar.js";
+
+const NOTE = "#root/abc";
+/** A link to an attachment, escaped for the model data of `_setModelData()`. */
+const ATTACHMENT = "#root/abc?viewMode=attachments&amp;attachmentId=def";
+const REFERENCE = `<paragraph>a [<reference href="${NOTE}"></reference>] b</paragraph>`;
+
+describe("NoteLinkToolbar", () => {
+ let editor: ClassicEditor;
+ let showDialog: ReturnType<typeof vi.fn>;
+ let copy: ReturnType<typeof vi.fn>;
+
+ beforeEach(async () => {
+ showDialog = vi.fn(() => null);
+ copy = vi.fn();
+ // The host passes `clipboard` with a cast too, as the editor config does not declare it.
+ editor = await createTestEditor([ Essentials, Paragraph, Link, NoteLinkToolbar ], {
+ internalLink: { showDialog },
+ referenceLink: { getTitle: async () => "Target", getTitleSync: () => "Target" },
+ clipboard: { copy }
+ } as unknown as Parameters<typeof createTestEditor>[1]);
+ });
+
+ function create<T>(name: string) {
+ return editor.ui.componentFactory.create(name) as unknown as T;
+ }
+
+ it("reads Open note in the link toolbar of a link to a note, and the address otherwise", () => {
+ const preview = create<ButtonView>("linkPreview");
+ const linkTo = (href: string) => setModelData(editor.model,
+ `<paragraph><$text linkHref="${href}">fo[]o</$text></paragraph>`);
+
+ linkTo(NOTE);
+ expect(preview.label).toBe("Open note");
+ expect(preview.tooltip).toBe(false);
+ linkTo(ATTACHMENT);
+ expect(preview.label).toBe("Open attachment");
+
+ for (const href of [ "https://a.example", "#rootless", "#anchor" ]) {
+ linkTo(href);
+ expect(preview.label).toBe(href);
+ }
+ });
+
+ describe("on a reference link", () => {
+ function getToolbar() {
+ const repository = editor.plugins.get(WidgetToolbarRepository) as unknown as {
+ _toolbarDefinitions: Map<string, { view: ToolbarView }>;
+ };
+ return repository._toolbarDefinitions.get("referenceLink")?.view;
+ }
+
+ it("shows the buttons of the link toolbar while the reference is selected", () => {
+ editor.ui.focusTracker.isFocused = true;
+ const balloon = editor.plugins.get(ContextualBalloon);
+
+ setModelData(editor.model, REFERENCE);
+ const toolbar = getToolbar();
+ expect(toolbar).toBeDefined();
+ expect(balloon.visibleView).toBe(toolbar);
+ const labels = [ ...toolbar?.items ?? [] ]
+ .filter((item) => item instanceof ButtonView)
+ .map((item) => item.label);
+ expect(labels).toStrictEqual([ "Open note", "Copy URL", "Edit link", "Unlink" ]);
+
+ setModelData(editor.model, `<paragraph>a[] <reference href="${NOTE}"></reference></paragraph>`);
+ expect(balloon.visibleView).toBeNull();
+ });
+
+ it("opens the note from an anchor to it, styled as the link toolbar's", () => {
+ const preview = create<LinkEmbedPreviewButtonView>("referenceLinkPreview");
+ preview.render();
+ expect(preview.element?.tagName).toBe("A");
+ expect(preview.element?.classList.contains("ck-link-toolbar__preview")).toBe(true);
+
+ setModelData(editor.model, REFERENCE);
+ expect(preview.label).toBe("Open note");
+ expect(preview.element?.getAttribute("href")).toBe(NOTE);
+
+ setModelData(editor.model, `<paragraph>[<reference href="${ATTACHMENT}"></reference>]</paragraph>`);
+ expect(preview.label).toBe("Open attachment");
+
+ setModelData(editor.model, "<paragraph>a[]</paragraph>");
+ expect(preview.label).toBeUndefined();
+ expect(preview.href).toBeUndefined();
+ });
+
+ it("copies the address of the reference", () => {
+ const button = create<ButtonView>("referenceLinkCopyUrl");
+ button.fire("execute");
+ expect(copy).not.toHaveBeenCalled();
+
+ setModelData(editor.model, REFERENCE);
+ button.fire("execute");
+ expect(copy).toHaveBeenCalledExactlyOnceWith(NOTE);
+ });
+
+ it("opens the link dialog on the reference", () => {
+ setModelData(editor.model, REFERENCE);
+ create<ButtonView>("editLink").fire("execute");
+ expect(showDialog).toHaveBeenCalledOnce();
+ });
+
+ it("unlinks the reference to its title, in one undo step", () => {
+ const button = create<ButtonView>("referenceLinkUnlink");
+ setModelData(editor.model, "<paragraph>a[]</paragraph>");
+ expect(button.isEnabled).toBe(false);
+
+ setModelData(editor.model, REFERENCE);
+ expect(button.isEnabled).toBe(true);
+ button.fire("execute");
+ expect(getModelData(editor.model)).toBe("<paragraph>a Target[] b</paragraph>");
+
+ editor.execute("undo");
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe(`<paragraph>a <reference href="${NOTE}"></reference> b</paragraph>`);
+ expect(editor.commands.get(UNLINK_REFERENCE_COMMAND)?.isEnabled).toBe(true);
+ });
+ });
+});
+
+describe("the provider of note links", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("offers no list of links in the link form", async () => {
+ const register = vi.spyOn(LinkUI.prototype, "registerLinksListProvider");
+ await createTestEditor([ Essentials, Paragraph, Link, NoteLinkToolbar ]);
+
+ expect(register).toHaveBeenCalledOnce();
+ expect(register.mock.calls[0]?.[0].getListItems()).toStrictEqual([]);
+ });
+
+ it("leaves out the provider in an editor without the link toolbar", async () => {
+ const editor = await createTestEditor([ Essentials, Paragraph, NoteLinkToolbar ]);
+ expect(editor.plugins.has(LinkUI)).toBe(false);
+ expect(editor.plugins.has(NoteLinkToolbar)).toBe(true);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/note_link_toolbar.ts b/packages/ckeditor5/src/plugins/note_link_toolbar.ts
new file mode 100644
index 0000000000..e018a5ff9a
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/note_link_toolbar.ts
@@ -0,0 +1,132 @@
+import {
+ ButtonView, Command, type Editor, IconUnlink, LinkUI, type ModelElement, Plugin,
+ WidgetToolbarRepository
+} from 'ckeditor5';
+
+import { createCopyUrlButton } from './copy_link_url.js';
+import InternalLinkPlugin from './internallink.js';
+import { LinkEmbedPreviewButtonView } from './link_embed/link_embed_toolbar.js';
+import { getAttachmentId, getReferenceTitleSync, getSelectedReference } from './referencelink.js';
+
+export const UNLINK_REFERENCE_COMMAND = 'unlinkReference';
+
+/**
+ * The toolbar of a link to a note. A link in the text shows the link toolbar of `LinkUI`, and a
+ * reference link shows a widget toolbar with the same buttons. In both, the first button reads
+ * "Open note" instead of the address.
+ */
+export default class NoteLinkToolbar extends Plugin {
+
+ /** The `href` of the selected reference link, or `null` when the selection holds none. */
+ declare referenceHref: string | null;
+
+ static get requires() {
+ return [ WidgetToolbarRepository, InternalLinkPlugin ] as const;
+ }
+
+ static get pluginName() {
+ return 'NoteLinkToolbar' as const;
+ }
+
+ init() {
+ const editor = this.editor;
+ const factory = editor.ui.componentFactory;
+ const unlinkCommand = new UnlinkReferenceCommand(editor);
+ editor.commands.add(UNLINK_REFERENCE_COMMAND, unlinkCommand);
+
+ this.set('referenceHref', null);
+ this.listenTo(editor.model.document, 'change', () => {
+ const href = getSelectedReference(editor)?.getAttribute('href');
+ this.referenceHref = typeof href === 'string' ? href : null;
+ });
+
+ factory.add('referenceLinkPreview', locale => {
+ const button = new LinkEmbedPreviewButtonView(locale);
+ button.bind('href').to(this, 'referenceHref', href => href ?? undefined);
+ button.bind('label').to(this, 'referenceHref',
+ href => href ? getOpenLinkLabel(editor, href) : undefined);
+ return button;
+ });
+
+ factory.add('referenceLinkCopyUrl', locale =>
+ createCopyUrlButton(editor, locale, () => this.referenceHref)
+ );
+
+ factory.add('referenceLinkUnlink', locale => {
+ const button = new ButtonView(locale);
+ button.set({
+ label: editor.t('Unlink'),
+ icon: IconUnlink,
+ tooltip: true
+ });
+ button.bind('isEnabled').to(unlinkCommand);
+ button.on('execute', () => {
+ editor.execute(UNLINK_REFERENCE_COMMAND);
+ editor.editing.view.focus();
+ });
+ return button;
+ });
+ }
+
+ afterInit() {
+ const editor = this.editor;
+
+ if (editor.plugins.has(LinkUI)) {
+ editor.plugins.get(LinkUI).registerLinksListProvider({
+ label: editor.t('Internal link'),
+ getListItems: () => [],
+ getItem: href => NOTE_LINK.test(href)
+ ? { href, label: getOpenLinkLabel(editor, href) }
+ : null
+ });
+ }
+
+ editor.plugins.get(WidgetToolbarRepository).register('referenceLink', {
+ items: [
+ 'referenceLinkPreview', 'referenceLinkCopyUrl', '|', 'editLink', 'referenceLinkUnlink'
+ ],
+ balloonClassName: 'ck-toolbar-container reference-link-toolbar',
+ getRelatedElement(selection) {
+ const element = selection.getSelectedElement();
+ return element?.hasClass('reference-link') ? element : null;
+ }
+ });
+ }
+}
+
+/** Replaces the selected reference link with its title as plain text. */
+class UnlinkReferenceCommand extends Command {
+
+ override refresh() {
+ this.isEnabled = !!getSelectedReference(this.editor);
+ }
+
+ override execute() {
+ const editor = this.editor;
+ // `refresh()` disables the command without a selected reference.
+ const reference = getSelectedReference(editor) as ModelElement;
+ const href = reference.getAttribute('href') as string;
+ const storedTitle = reference.getAttribute('storedTitle') as string | undefined;
+ const title = getReferenceTitleSync(editor, href, storedTitle);
+ const model = editor.model;
+ model.change(writer => {
+ const range = model.createRangeOn(reference);
+ const inserted = model.insertContent(writer.createText(title), range);
+ writer.setSelection(inserted.end);
+ });
+ }
+}
+
+/** A link to a note or to an attachment of one, as opposed to a web address or an anchor. */
+const NOTE_LINK = /^#root(?:[/?]|$)/;
+
+/** The text of the button that opens the note or attachment `href` points to. */
+function getOpenLinkLabel(editor: Editor, href: string) {
+ return getAttachmentId(href) ? editor.t('Open attachment') : editor.t('Open note');
+}
+
+declare module 'ckeditor5' {
+ interface PluginsMap {
+ [NoteLinkToolbar.pluginName]: NoteLinkToolbar;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.ts
index eaa6d19671..b10a0346a2 100644
--- a/packages/ckeditor5/src/plugins/referencelink.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.ts
@@ -372,6 +372,12 @@ export function getReferenceTitleSync( editor: Editor, href: string, storedTitle
return getTitleSync ? getTitleSync( href, storedTitle ) : storedTitle ?? href;
}
+/** The selected reference link, or `null` when the selection holds none. */
+export function getSelectedReference( editor: Editor ): ModelElement | null {
+ const element = editor.model.document.selection.getSelectedElement();
+ return element?.is( 'element', 'reference' ) ? element : null;
+}
+
/** The attributes of a `reference` to `href`, with `storedTitle` when there is one to keep. */
export function referenceAttributes( href: string | undefined, storedTitle: string | undefined ) {
return storedTitle ? { href, storedTitle } : { href };