Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/links: show the link editor as a popover on desktop, keep as a dialog for mobile

Adorian Dorandc83d69efb6a
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.ts
index a77e0ce210..852ff9ba71 100644
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@ -383,7 +383,7 @@ export type CommandMappings = {
showCheatsheet: CommandData;
showShortcutHints: CommandData;
showHelp: CommandData;
- addLinkToText: CommandData & Pick<AddLinkOpts, "target">;
+ addLinkToText: CommandData;
followLinkUnderCursor: CommandData;
insertDateTimeToText: CommandData;
pasteMarkdownIntoText: CommandData;
diff --git a/apps/client/src/widgets/dialogs/add_link.css b/apps/client/src/widgets/dialogs/add_link.css
index 1aabe029cd..142a9cfbd3 100644
--- a/apps/client/src/widgets/dialogs/add_link.css
+++ b/apps/client/src/widgets/dialogs/add_link.css
@@ -1,4 +1,21 @@
-.modal.add-link-dialog {
+.add-link-balloon {
+ padding: 8px;
+ /* Keeps the card wider than the 500px at which Card.css stacks its rows. */
+ width: 34rem;
+ max-width: calc(100vw - 2rem);
+ /* Overrides the text styles inherited from CKEditor's `ck-reset_all`. */
+ font-size: var(--main-font-size);
+ line-height: var(--bs-body-line-height);
+ white-space: normal;
+ text-align: start;
+
+ .add-link-actions {
+ display: flex;
+ justify-content: flex-end;
+ }
+}
+
+:is(.modal.add-link-dialog, .add-link-balloon) {
.tn-card {
margin-bottom: 1rem;
}
diff --git a/apps/client/src/widgets/dialogs/add_link.spec.tsx b/apps/client/src/widgets/dialogs/add_link.spec.tsx
index dc61116a0b..a84b219420 100644
--- a/apps/client/src/widgets/dialogs/add_link.spec.tsx
+++ b/apps/client/src/widgets/dialogs/add_link.spec.tsx
@@ -6,8 +6,9 @@ import Component from "../../components/component";
import type { Suggestion } from "../../services/note_autocomplete";
import { buildNote } from "../../test/easy-froca";
import { renderInto } from "../../test/render";
+import Modal from "../react/Modal";
import { ParentComponent } from "../react/react_utils";
-import AddLinkDialog, { type AddLinkOpts, normalizeWebLink } from "./add_link";
+import AddLinkDialog, { AddLinkBalloon, type AddLinkOpts, normalizeWebLink } from "./add_link";
const autocomplete = vi.hoisted(() => ({
onChange: undefined as ((suggestion: Suggestion | null) => void) | undefined
@@ -92,14 +93,6 @@ describe("AddLinkDialog", () => {
return container.querySelector<HTMLInputElement>(`.add-link-${name} input`);
}
- async function type(input: HTMLInputElement | null, value: string) {
- if (!input) throw new Error("The field is not shown.");
- await act(async () => {
- input.value = value;
- input.dispatchEvent(new Event("input", { bubbles: true }));
- });
- }
-
async function submit() {
const form = container.querySelector("form");
const modal = container.querySelector(".modal");
@@ -192,7 +185,8 @@ describe("AddLinkDialog", () => {
expect(addLink)
.toHaveBeenLastCalledWith("https://example.com", "https://example.com", true);
- await open({ target: "url", currentLink: { notePath: "root/abc" } });
+ const note = buildNote({ title: "Target" });
+ await open({ target: "url", currentLink: { notePath: `root/${note.noteId}` } });
expect(current()).toBe("add_link.note");
});
@@ -277,3 +271,83 @@ describe("AddLinkDialog", () => {
expect(container.querySelector(".note-autocomplete")).not.toBeNull();
});
});
+
+describe("AddLinkBalloon", () => {
+ const addLink = vi.fn<AddLinkOpts["addLink"]>(async () => {});
+ const onClose = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ async function show(opts: Partial<AddLinkOpts> = {}) {
+ const rendered: { container?: HTMLElement } = {};
+ await act(async () => {
+ rendered.container = renderInto(
+ <AddLinkBalloon
+ opts={{ text: "", hasSelection: false, addLink, ...opts }}
+ onClose={onClose}
+ />
+ );
+ });
+ const form = rendered.container?.querySelector("form");
+ if (!form) throw new Error("The balloon has no form.");
+ return form;
+ }
+
+ async function submit(form: HTMLFormElement) {
+ await act(async () => {
+ form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ });
+ }
+
+ it("focuses the field of the side it opens on, and closes once a link is applied", async () => {
+ const noteForm = await show();
+ expect(document.activeElement).toBe(noteForm.querySelector(".note-autocomplete"));
+
+ const form = await show({ target: "url" });
+ const url = form.querySelector<HTMLInputElement>(".add-link-url input");
+ expect(url).not.toBeNull();
+ expect(document.activeElement).toBe(url);
+
+ await submit(form);
+ expect(onClose).not.toHaveBeenCalled();
+
+ await type(url, "example.com");
+ await submit(form);
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(addLink)
+ .toHaveBeenCalledExactlyOnceWith("https://example.com", "https://example.com", true);
+ });
+
+ it("takes the focus from a modal around the editor", async () => {
+ renderInto(
+ <Modal className="host-modal" size="md" show onHidden={() => {}}><input /></Modal>
+ );
+ await vi.waitFor(() => expect(document.querySelector(".host-modal.show")).not.toBeNull());
+
+ const form = await show({ target: "url" });
+ expect(document.activeElement).toBe(form.querySelector(".add-link-url input"));
+ });
+
+ it("opens on an edited link with its address selected, and applies it left alone", async () => {
+ const form = await show({
+ currentLink: { externalLink: "https://example.com/page" }, currentTitle: "Page"
+ });
+ const url = form.querySelector<HTMLInputElement>(".add-link-url input");
+ expect(url?.value).toBe("https://example.com/page");
+ expect([ url?.selectionStart, url?.selectionEnd ]).toStrictEqual([ 0, url?.value.length ]);
+
+ await submit(form);
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(addLink).toHaveBeenCalledExactlyOnceWith("https://example.com/page", "Page", true);
+ });
+});
+
+async function type(input: HTMLInputElement | null, value: string) {
+ if (!input) throw new Error("The field is not shown.");
+ await act(async () => {
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
diff --git a/apps/client/src/widgets/dialogs/add_link.tsx b/apps/client/src/widgets/dialogs/add_link.tsx
index 9a707e1fa0..b183928bd3 100644
--- a/apps/client/src/widgets/dialogs/add_link.tsx
+++ b/apps/client/src/widgets/dialogs/add_link.tsx
@@ -16,6 +16,7 @@ import FormTextBox from "../react/FormTextBox";
import FormToggle from "../react/FormToggle";
import { useTriliumEvent } from "../react/hooks";
import Modal from "../react/Modal";
+import { suspendModalFocusTraps } from "../react/modal_focustrap";
import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutocomplete";
import { refToJQuerySelector } from "../react/react_utils";
import SegmentedChoice from "../react/SegmentedChoice";
@@ -87,16 +88,94 @@ export interface AddLinkOpts {
export default function AddLinkDialog() {
const [ opts, setOpts ] = useState<AddLinkOpts>();
+ const [ shown, setShown ] = useState(false);
+ const hasSubmittedRef = useRef(false);
+ const form = useAddLinkForm(opts);
+
+ useTriliumEvent("showAddLinkDialog", opts => {
+ setOpts(opts);
+ setShown(true);
+ });
+
+ function onSubmit() {
+ if (!form.hasLink) {
+ logError("No link to add.");
+ return;
+ }
+
+ hasSubmittedRef.current = true;
+ // Insertion logic in onHidden because it needs focus.
+ setShown(false);
+ }
+
+ return (
+ <Modal
+ className="add-link-dialog"
+ size="lg"
+ title={form.title}
+ helpPageId="QEAPj01N5f7w"
+ footer={<Button text={form.buttonText} keyboardShortcut="Enter" />}
+ onSubmit={onSubmit}
+ onShown={form.onShown}
+ onHidden={() => {
+ if (hasSubmittedRef.current) {
+ hasSubmittedRef.current = false;
+ form.applyLink();
+ }
+
+ form.reset();
+ setShown(false);
+ }}
+ show={shown}
+ >
+ {form.body}
+ </Modal>
+ );
+}
+
+/**
+ * The form of the link dialog in the balloon that the text editor places at the caret. `onClose`
+ * closes the balloon.
+ */
+export function AddLinkBalloon({ opts, onClose }: { opts: AddLinkOpts; onClose(): void }) {
+ // Lets the fields take focus inside a modal, such as the quick edit popup. Runs before the
+ // effects of `useAddLinkForm()`, which focus the fields.
+ useEffect(() => suspendModalFocusTraps(), []);
+ const form = useAddLinkForm(opts);
+
+ useEffect(() => {
+ form.onShown();
+ }, []);
+
+ return (
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (!form.hasLink) return;
+
+ onClose();
+ form.applyLink();
+ }}
+ >
+ {form.body}
+ <div className="add-link-actions">
+ <Button text={form.buttonText} keyboardShortcut="Enter" />
+ </div>
+ </form>
+ );
+}
+
+/** The state and the fields of the link dialog for `opts`, shared by the modal and the balloon. */
+function useAddLinkForm(opts: AddLinkOpts | undefined) {
const [ linkTitle, setLinkTitle ] = useState("");
const [ linkType, setLinkType ] = useState<LinkType>();
const [ suggestion, setSuggestion ] = useState<Suggestion | null>(null);
const [ bookmarks, setBookmarks ] = useState<string[]>([]);
const [ selectedBookmark, setSelectedBookmark ] = useState("");
const [ noteTitle, setNoteTitle ] = useState("");
- const [ shown, setShown ] = useState(false);
const [ target, setTarget ] = useState<LinkTarget>("note");
const [ webLink, setWebLink ] = useState("");
- const hasSubmittedRef = useRef(false);
+ const [ isShowPending, setIsShowPending ] = useState(false);
const webLinkRef = useRef<HTMLInputElement>(null);
// The text of the link being edited, while it stands in for the picked note's title.
const keptTitleRef = useRef<string | null>(null);
@@ -104,11 +183,6 @@ export default function AddLinkDialog() {
// On mobile, focusing a field opens the keyboard, so a field waits for a tap.
const autoFocus = !isMobile();
- useTriliumEvent("showAddLinkDialog", opts => {
- setOpts(opts);
- setShown(true);
- });
-
useEffect(() => {
if (opts?.hasSelection || opts?.currentTitle !== undefined) {
setLinkType("hyper-link");
@@ -240,7 +314,14 @@ export default function AddLinkDialog() {
}
}, [selectedBookmark, noteTitle]);
- async function onShown() {
+ // Runs one render after `onShown`, so `fillAndFocus()` reads the state set from `opts`.
+ useEffect(() => {
+ if (!isShowPending) return;
+ setIsShowPending(false);
+ void fillAndFocus();
+ }, [ isShowPending ]);
+
+ async function fillAndFocus() {
if (target === "url") {
if (autoFocus) {
webLinkRef.current?.focus();
@@ -275,17 +356,30 @@ export default function AddLinkDialog() {
}
}
- function onSubmit() {
- hasSubmittedRef.current = true;
+ /** Applies the link picked, through `opts.addLink`. */
+ function applyLink() {
+ if (!opts || !suggestion) return;
- if (suggestion) {
- // Insertion logic in onHidden because it needs focus.
- setShown(false);
- } else {
- logError("No link to add.");
+ if (suggestion.notePath) {
+ // Handle note link, optionally with a bookmark anchor
+ const path = selectedBookmark
+ ? `${suggestion.notePath}?bookmark=${encodeURIComponent(selectedBookmark)}`
+ : suggestion.notePath;
+ opts.addLink(path, linkType === "reference-link" ? null : linkTitle);
+ } else if (suggestion.externalLink) {
+ // An external link without a text of its own reads as its address.
+ const text = linkTitle.trim() || suggestion.externalLink;
+ opts.addLink(suggestion.externalLink, text, true);
}
}
+ function reset() {
+ setSuggestion(null);
+ setBookmarks([]);
+ setSelectedBookmark("");
+ setNoteTitle("");
+ }
+
const autocompleteRef = useRef<HTMLInputElement>(null);
const handleRef = useRef<NoteAutocompleteHandle>(null);
const title = opts?.fixLink ? t("add_link.fix_link")
@@ -306,41 +400,15 @@ export default function AddLinkDialog() {
</OptionCardSection>
);
- return (
- <Modal
- className="add-link-dialog"
- size="lg"
- title={title}
- helpPageId="QEAPj01N5f7w"
- footer={<Button text={buttonText} keyboardShortcut="Enter" />}
- onSubmit={onSubmit}
- onShown={onShown}
- onHidden={() => {
- // Insert the link.
- if (hasSubmittedRef.current && suggestion && opts) {
- hasSubmittedRef.current = false;
-
- if (suggestion.notePath) {
- // Handle note link, optionally with a bookmark anchor
- const path = selectedBookmark
- ? `${suggestion.notePath}?bookmark=${encodeURIComponent(selectedBookmark)}`
- : suggestion.notePath;
- opts.addLink(path, linkType === "reference-link" ? null : linkTitle);
- } else if (suggestion.externalLink) {
- // An external link without a text of its own reads as its address.
- const text = linkTitle.trim() || suggestion.externalLink;
- opts.addLink(suggestion.externalLink, text, true);
- }
- }
-
- setSuggestion(null);
- setBookmarks([]);
- setSelectedBookmark("");
- setNoteTitle("");
- setShown(false);
- }}
- show={shown}
- >
+ return {
+ title,
+ buttonText,
+ hasLink: !!suggestion,
+ /** Fills and focuses the fields, once the form is on screen. */
+ onShown: () => setIsShowPending(true),
+ applyLink,
+ reset,
+ body: (
<Card>
{!opts?.fixLink && (
<CardSection>
@@ -440,8 +508,8 @@ export default function AddLinkDialog() {
</>
)}
</Card>
- </Modal>
- );
+ )
+ };
}
/**
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx
index fb82b90232..8c782be30e 100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx
@@ -1,6 +1,7 @@
import {
type CKEditorError, CKTextEditor, ClassicEditor, getLinkAtSelection, type IconPickerRequest,
- onTextEditorError, PopupEditor, replaceLinkAtSelection, SnippetDefinition
+ type LinkDialogRequest, onTextEditorError, PopupEditor, replaceLinkAtSelection,
+ SnippetDefinition
} from "@triliumnext/ckeditor5";
import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";
import { createPortal, HTMLAttributes, RefObject } from "preact";
@@ -67,9 +68,16 @@ interface CKEditorProps extends Pick<HTMLAttributes<HTMLDivElement>, "className"
containerRef?: RefObject<HTMLDivElement | null>;
/** What renders the embeds of the editor and acts on them. Editors without embeds leave it out. */
contentEmbedHandlers?: ContentEmbedHandlers;
+ /** Shows the link dialog, as `internalLink.showDialog` does. */
+ showLinkDialog?: (request: LinkDialogRequest) => (() => void) | null;
}
-export default function CKEditor({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, editorRef: externalEditorRef, onNotificationWarning, onNotificationInfo, onEditorError, onChange, onEditorInitialized, editorApi, templates, rebuildKey, contentEmbedHandlers }: CKEditorProps) {
+export default function CKEditor({
+ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor,
+ editorRef: externalEditorRef, onNotificationWarning, onNotificationInfo, onEditorError,
+ onChange, onEditorInitialized, editorApi, templates, rebuildKey, contentEmbedHandlers,
+ showLinkDialog
+}: CKEditorProps) {
const containerRef = useSyncedRef<HTMLDivElement>(externalContainerRef, null);
const editorRef = useRef<CKTextEditor>(null);
const stopReportingErrorsRef = useRef<() => void>(undefined);
@@ -139,6 +147,8 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa
noteRef.current = note;
const contentEmbedHandlersRef = useRef(contentEmbedHandlers);
contentEmbedHandlersRef.current = contentEmbedHandlers;
+ const showLinkDialogRef = useRef(showLinkDialog);
+ showLinkDialogRef.current = showLinkDialog;
/** The open icon picker request and its balloon container, or `null` when none is open. */
const [ iconPickerRequest, setIconPickerRequest ] = useState<IconPickerRequest | null>(null);
@@ -312,7 +322,8 @@ export default function CKEditor({ containerRef: externalContainerRef, contentLa
getNotePath: () => noteLocationRef.current?.notePath,
save: () => parentComponent?.triggerCommand("saveNoteDetailNow")
},
- getContentEmbedHandlers: () => contentEmbedHandlersRef.current
+ getContentEmbedHandlers: () => contentEmbedHandlersRef.current,
+ showLinkDialog: (request) => showLinkDialogRef.current?.(request) ?? null
});
if (isStale) {
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 6c7cf94f2e..a70d4f3d20 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -7,12 +7,14 @@ import {
CKTextEditor,
type FileUploadData,
type FileUploadEvent,
+ type LinkDialogRequest,
SnippetDefinition
} from "@triliumnext/ckeditor5";
import { deferred, formatBlockRange, parseBlockRange } from "@triliumnext/commons";
+import { createPortal } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
-import appContext, { type CommandListenerData } from "../../../components/app_context";
+import appContext from "../../../components/app_context";
import { consumeBlockReference } from "../../../services/block_reference";
import { consumeBookmark } from "../../../services/bookmark_jump";
import dialog from "../../../services/dialog";
@@ -24,7 +26,7 @@ import note_create from "../../../services/note_create";
import { consumeSearchTerms } from "../../../services/search_jump";
import toast from "../../../services/toast";
import utils, { isMobile } from "../../../services/utils";
-import type { AddLinkOpts } from "../../dialogs/add_link";
+import { AddLinkBalloon, type AddLinkOpts } from "../../dialogs/add_link";
import {
useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useSameNoteSwitch,
useSearchTermsConsumer, useTriliumEvent, useTriliumOption, useTriliumOptionBool
@@ -247,11 +249,31 @@ export default function EditableText({
enter: enterContentEmbed
};
- useLegacyImperativeHandlers({
- addLinkToTextCommand({ target }: CommandListenerData<"addLinkToText"> = {}) {
- if (!editorApiRef.current) return;
- const opts = getAddLinkOpts(editorApiRef.current, waitForEditor, target);
+ const [ linkDialog, setLinkDialog ] = useState<{
+ opts: AddLinkOpts;
+ request: LinkDialogRequest;
+ } | null>(null);
+
+ // CKEditor places the balloon at the caret; `AddLinkBalloon` renders into its container.
+ // On mobile, `showAddLinkDialog` opens the form in a modal instead.
+ function showLinkDialog(request: LinkDialogRequest) {
+ if (!editorApiRef.current) return null;
+
+ const opts = getAddLinkOpts(editorApiRef.current, waitForEditor, request.target);
+ if (isMobile()) {
parentComponent?.triggerCommand("showAddLinkDialog", opts);
+ return null;
+ }
+
+ setLinkDialog({ opts, request });
+ return () => setLinkDialog(null);
+ }
+
+ useLegacyImperativeHandlers({
+ // Keyboard shortcut
+ async addLinkToTextCommand() {
+ const editor = await waitForEditor();
+ editor?.execute("insertInternalLink");
},
pasteMarkdownIntoTextCommand() {
if (!editorApiRef.current) return;
@@ -509,6 +531,7 @@ export default function EditableText({
onEditorError={(error) => reportEditorError(error, reloadEditor)}
rebuildKey={editorRebuildKey}
contentEmbedHandlers={contentEmbedHandlers}
+ showLinkDialog={showLinkDialog}
onChange={() => {
// `getData()` serializes the whole note, so saves wait for typing to pause.
spacedUpdate.resetUpdateTimer();
@@ -550,6 +573,10 @@ export default function EditableText({
}}
/>}
+ {linkDialog && createPortal(
+ <AddLinkBalloon opts={linkDialog.opts} onClose={linkDialog.request.close} />,
+ linkDialog.request.container
+ )}
</>
);
}
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index 6e6760459d..fc352a09c6 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -410,8 +410,6 @@ describe("CK config - tables", () => {
it("hands the dialogs and cut to note of the editor to the app commands that do them", async () => {
const triggerHostCommand = vi.fn(async () => undefined);
const config = await buildConfig(baseOpts({ triggerHostCommand }));
- await config.internalLink?.openDialog({ target: "url" });
- expect(triggerHostCommand).toHaveBeenLastCalledWith("addLinkToText", { target: "url" });
const callbacks = [
[ config.markdownImport?.open, "pasteMarkdownIntoText" ],
@@ -424,7 +422,7 @@ describe("CK config - tables", () => {
await callback?.();
expect(triggerHostCommand).toHaveBeenLastCalledWith(command);
}
- expect(triggerHostCommand).toHaveBeenCalledTimes(callbacks.length + 1);
+ expect(triggerHostCommand).toHaveBeenCalledTimes(callbacks.length);
});
it("shows the icon picker the editor asks for, and none without a host for it", async () => {
@@ -437,6 +435,19 @@ describe("CK config - tables", () => {
expect((await buildConfig(baseOpts())).inlineIcon?.showPicker(request)).toBeNull();
});
+ it("shows the link dialog the editor asks for, and none without a host for it", async () => {
+ const release = vi.fn();
+ const showLinkDialog = vi.fn(() => release);
+ const request = {
+ container: document.createElement("div"), target: "url" as const, close: vi.fn()
+ };
+
+ expect((await buildConfig(baseOpts({ showLinkDialog }))).internalLink?.showDialog(request))
+ .toBe(release);
+ expect(showLinkDialog).toHaveBeenCalledWith(request);
+ expect((await buildConfig(baseOpts())).internalLink?.showDialog(request)).toBeNull();
+ });
+
it("copies block and tab references from the reference source, and none without one", async () => {
const getEditor = vi.fn(() => null);
const referenceSource = {
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 1717030078..ac9be2fa0c 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -1,4 +1,8 @@
-import { type AttachmentUploadHost, type ContentEmbedHost, type EditorConfig, getCkLocale, type IconPickerRequest, type LinkEmbedHost, SnippetDefinition, type TextTransformationConfig } from "@triliumnext/ckeditor5";
+import {
+ type AttachmentUploadHost, type ContentEmbedHost, type EditorConfig, getCkLocale,
+ type IconPickerRequest, type LinkDialogRequest, type LinkEmbedHost, SnippetDefinition,
+ type TextTransformationConfig
+} from "@triliumnext/ckeditor5";
import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";
import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD_SUBTYPES, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
import i18next from "i18next";
@@ -69,6 +73,8 @@ export interface BuildEditorOptions {
) => Promise<unknown> | undefined | null;
/** Shows the icon picker the editor asks for, as `inlineIcon.showPicker` does. */
showIconPicker?: (request: IconPickerRequest) => (() => void) | null;
+ /** Shows the link dialog, as `internalLink.showDialog` does. */
+ showLinkDialog?: (request: LinkDialogRequest) => (() => void) | null;
/** The note that the block and tab references the editor copies point to. */
referenceSource?: ReferenceSource;
/**
@@ -258,11 +264,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
linkEmbed: buildLinkEmbedHost(opts.getNoteId),
getNoteId: opts.getNoteId,
attachmentUpload: buildAttachmentUploadHost(opts.getComponentId),
- internalLink: {
- openDialog: async (options) => {
- await opts.triggerHostCommand?.("addLinkToText", options);
- }
- },
+ internalLink: { showDialog: (request) => opts.showLinkDialog?.(request) ?? null },
childNote: buildChildNoteHost(() => opts.getChildNoteParent?.()),
markdownImport: { open: bindHostCommand(opts, "pasteMarkdownIntoText") },
inlineIcon: { showPicker: (request) => opts.showIconPicker?.(request) ?? null },
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index 17c0ed7dde..55c697d2b0 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -140,8 +140,8 @@
"_help_oiVPnW8QfnvS": "<h2>Trilium-specific shortcuts</h2><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Bring up inline formatting toolbar (arrow keys ←,→ to navigate, Enter to apply)</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Bring up block formatting toolbar</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">external link</a></td><td>Ctrl+K</td><td>⌘+K</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">internal (note) link</a></td><td>Ctrl+L</td><td>⌘+L</td></tr><tr><td>Inserts current date and time at caret position</td><td>Alt+T</td><td>⌥+T</td></tr><tr><td>Increase paragraph indentation</td><td>Tab</td><td>⇥</td></tr><tr><td>Decrease paragraph indentation</td><td>Shift + Tab</td><td>⇧ + ⇥</td></tr><tr><td>Mark selected text as <a href=\"#root/_help_UYuUB1ZekNQU\">keyboard shortcut</a></td><td>Ctrl + Alt + K</td><td>⌘+ ⌥+ K</td></tr><tr><td>Insert&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a></td><td>Ctrl + M</td><td>⌘+ M</td></tr><tr><td>Move blocks (lists, paragraphs, etc.) up, or in a <a href=\"#root/_help_NdowYOC1GFKS\">table</a> the rows</td><td>Alt+↑</td><td>⌥+↑</td></tr><tr><td>Move blocks (lists, paragraphs, etc.) down, or in a <a href=\"#root/_help_NdowYOC1GFKS\">table</a> the rows</td><td>Alt+↓</td><td>⌥+↓</td></tr><tr><td>Move the selected content to another column of a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current column of a multicolumn layout</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a column after or before the current one in a multicolumn layout</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr><tr><td>Move the selected content to another tab in <a class=\"reference-link\" href=\"#root/_help_EK2ckIZ74tbT\">Content tabs</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current tab of a tabs block</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a tab after or before the current one in a tabs block</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr></tbody></table></figure><h2>Common shortcuts</h2><aside class=\"admonition tip\"><p>This section of keyboard shortcuts presents a subset of the keyboard shortcuts as supported by the editor technology we are using,&nbsp;<a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>. The shortcuts were taken from the <a href=\"https://ckeditor.com/docs/ckeditor5/latest/features/accessibility.html#keyboard-shortcuts\">official documentation</a>. Note that not all the shortcuts in the original documentation are applicable (due to using a different configuration).</p></aside><h3>Content editing</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a hard break (a new paragraph)</td><td>Enter</td><td></td></tr><tr><td>Insert a soft break (a <code>&lt;br&gt;</code> element)</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Copy selected content</td><td>Ctrl+C</td><td>⌘C</td></tr><tr><td>Paste content</td><td>Ctrl+V</td><td>⌘V</td></tr><tr><td>Paste content as plain text</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Undo</td><td>Ctrl+Z</td><td>⌘Z</td></tr><tr><td>Redo</td><td>Ctrl+Y, Ctrl+Shift+Z</td><td>⌘Y, ⌘⇧Z</td></tr><tr><td>Bold text</td><td>Ctrl+B</td><td>⌘B</td></tr><tr><td>Change text case</td><td>Shift+F3</td><td>⇧F3 (may require Fn)</td></tr><tr><td>Create link</td><td>Ctrl+K</td><td>⌘K</td></tr><tr><td>Move out of a link</td><td>←←, →→</td><td></td></tr><tr><td>Move out of an inline code style</td><td>←←, →→</td><td></td></tr><tr><td>Select all</td><td>Ctrl+A</td><td>⌘A</td></tr><tr><td>Find in the document</td><td>Ctrl+F</td><td>⌘F</td></tr><tr><td>Copy text formatting</td><td>Ctrl+Shift+C</td><td>⌘⇧C</td></tr><tr><td>Paste text formatting</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Italic text</td><td>Ctrl+I</td><td>⌘I</td></tr><tr><td>Strikethrough text</td><td>Ctrl+Shift+X</td><td>⌘⇧X</td></tr><tr><td>Underline text</td><td>Ctrl+U</td><td>⌘U</td></tr><tr><td>Revert autoformatting action</td><td>Backspace</td><td></td></tr></tbody></table></figure><h3>Interacting with blocks</h3><p>Blocks are images, tables, blockquotes, annotations.</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a new paragraph directly after a widget</td><td>Enter</td><td></td></tr><tr><td>Insert a new paragraph directly before a widget</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Move the caret to allow typing directly before a widget</td><td>↑, ←</td><td></td></tr><tr><td>Move the caret to allow typing directly after a widget</td><td>↓, →</td><td></td></tr><tr><td>After entering a nested editable, move the selection to the closest ancestor widget. For example: move from an image caption to the whole image widget.</td><td>Tab then Esc</td><td></td></tr></tbody></table></figure><p>Specifically for lists:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Increase list item indent</td><td>⇥</td><td></td></tr><tr><td>Decrease list item indent</td><td>Shift+⇥</td><td>⇧⇥</td></tr></tbody></table></figure><p>In tables:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Move the selection to the next cell</td><td>⇥</td><td></td></tr><tr><td>Move the selection to the previous cell</td><td>Shift+⇥</td><td>⇧⇥</td></tr><tr><td>Insert a new table row (when in the last cell of a table)</td><td>⇥</td><td></td></tr><tr><td>Navigate through the table</td><td>↑, →, ↓, ←</td><td></td></tr></tbody></table></figure><h3>General UI shortcuts</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Close contextual balloons, dropdowns, and dialogs</td><td>Esc</td><td></td></tr><tr><td>Open the accessibility help dialog</td><td>Alt+0</td><td>⌥0</td></tr><tr><td>Move focus between form fields (inputs, buttons, etc.)</td><td>⇥, Shift+⇥</td><td>⇥, ⇧⇥</td></tr><tr><td>Move focus to the toolbar, navigate between toolbars</td><td>Alt+F10</td><td>⌥F10 (may require Fn)</td></tr><tr><td>Navigate through the toolbar or menu bar</td><td>↑, →, ↓, ←</td><td></td></tr><tr><td>Navigate to the next focusable field or an element outside the editor</td><td>Tab, Shift+Tab</td><td></td></tr><tr><td>Execute the currently focused button. Executing buttons that interact with the editor content moves the focus back to the content.</td><td>Enter, Space</td><td></td></tr><tr><td>Move focus in and out of an active dialog window</td><td>Ctrl+F6</td><td>⌘F6 (may require Fn)</td></tr></tbody></table></figure>",
"_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. By using the \"Link preview\" toolbar button or slash command</h3><p>Click <em>Link preview</em> (<span class=\"tn-icon cke cke-trilium-link-preview\"></span>) in the formatting toolbar to open the <em>Link preview</em> popup. Paste the URL and choose the type of preview.</p><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>), which opens the same popup at the cursor.</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>A button to edit the title of the link preview. This is especially useful if the title is hidden behind a login screen.</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>. Type or paste the address, and optionally a <em>Link title</em>; without one, the link shows its address.</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.</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>.</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_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>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.</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_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/External links.md b/docs/User Guide/User Guide/Note Types/Text/Links/External links.md
index d7686dceee..24062cbd0a 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Links/External links.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Links/External links.md
@@ -4,7 +4,7 @@ An external link is a standard web link targeting for example a website. For exa
To create a link without a custom text:
* Press <span class="tn-icon cke cke-link"></span> in the <a class="reference-link" href="../Formatting%20toolbar.md">Formatting toolbar</a>, or press <kbd>Ctrl</kbd>+<kbd>K</kbd>:
- * Since v0.107.0, the _Add link_ dialog opens on _Web link_. Type or paste the address, and optionally a _Link title_; without one, the link shows its address.
+ * Since v0.107.0, the _Add link_ dialog opens on _Web link_, in a popup next to the cursor on desktop. Type or paste the address, and optionally a _Link title_; without one, the link shows its address.
* Press <kbd>Enter</kbd> or _Add link_ to confirm.
* A simpler way is to paste the raw link and press space to turn it automatically into a link.
* The <span class="tn-icon cke cke-trilium"></span> button and <kbd>Ctrl</kbd>+<kbd>L</kbd> of <a class="reference-link" href="Internal%20(reference)%20links.md">Internal (reference) links</a> open the same dialog on _Note_. Select _Web link_ at the top of the dialog to create an external link from there.
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 e0e455d57b..57052c8822 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
@@ -7,7 +7,7 @@ You can open an internal link by clicking it. You can also see a read-only previ
Internal links can be created at the current position in a text note by:
-1. Pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class="tn-icon cke cke-trilium"></span> button underneath the <span class="tn-icon cke cke-plus"></span> menu in the <a class="reference-link" href="../Formatting%20toolbar.md">Formatting toolbar</a>.
+1. Pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class="tn-icon cke cke-trilium"></span> button underneath the <span class="tn-icon cke cke-plus"></span> menu in the <a class="reference-link" href="../Formatting%20toolbar.md">Formatting toolbar</a>. On desktop, the _Add link_ dialog opens in a popup next to the cursor.
2. 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 _Create note_, which places it in the <a class="reference-link" href="../../../Basic%20Concepts%20and%20Features/Notes/Note%20Inbox.md">Note Inbox</a> (today's day note, or the top level, when no inbox is set), or _Create child note_, which places it under the note being edited.
There are two link types, chosen with the _Mirror the note's title_ switch of the dialog, which is on by default:
diff --git a/packages/ckeditor5/src/hosted_balloon.ts b/packages/ckeditor5/src/hosted_balloon.ts
new file mode 100644
index 0000000000..cd7e7f562e
--- /dev/null
+++ b/packages/ckeditor5/src/hosted_balloon.ts
@@ -0,0 +1,181 @@
+import {
+ clickOutsideHandler, ContextualBalloon, type Editor, KeystrokeHandler, type Locale, View,
+ type ViewRange
+} from "ckeditor5";
+
+/**
+ * A balloon at the caret with content rendered by the host application. The editor places the
+ * balloon and takes it down; the host renders its own component into the balloon's element.
+ *
+ * The plugin that creates it must require `ContextualBalloon`.
+ */
+export default class HostedBalloon {
+
+ private readonly editor: Editor;
+ private readonly className: string;
+ private readonly balloon: ContextualBalloon;
+ private view: HostedBalloonView | null = null;
+ private release: (() => void) | null = null;
+ private resizeObserver: ResizeObserver | null = null;
+ private repositionFrame = 0;
+
+ /** `className` is set on the element the host renders into. */
+ constructor(editor: Editor, className: string) {
+ this.editor = editor;
+ this.className = className;
+ this.balloon = editor.plugins.get(ContextualBalloon);
+
+ // Esc reaches the editor only while the caret has focus, and the host's content takes
+ // focus away, so `HostedBalloonView` registers a handler of its own.
+ editor.keystrokes.set("Esc", (_data, cancel) => {
+ if (this.view) {
+ this.hide();
+ cancel();
+ }
+ });
+ }
+
+ /**
+ * Opens the balloon at the caret and calls `render` with the element to render into. `render`
+ * returns the function that removes the rendered content, or `null` when the host shows the
+ * content somewhere else, which closes the balloon again. Does nothing while it is open.
+ */
+ show(render: (container: HTMLElement) => (() => void) | null) {
+ const editor = this.editor;
+ const editorEl = editor.editing.view.getDomRoot();
+ const shownAt = editor.editing.view.document.selection.getFirstRange();
+
+ if (this.view || !editorEl || !shownAt) {
+ return;
+ }
+
+ const view = new HostedBalloonView(editor.locale, this.className);
+ view.keystrokes.set("Esc", (_data, cancel) => {
+ this.hide();
+ editor.editing.view.focus();
+ cancel();
+ });
+
+ // Wired per view rather than once: the handler listens through the view, so destroying
+ // the view on the way out stops it.
+ clickOutsideHandler({
+ emitter: view,
+ activator: () => this.view === view,
+ /* v8 ignore next -- the balloon renders its panel as the editor starts up */
+ contextElements: this.balloon.view.element ? [ this.balloon.view.element ] : [],
+ callback: () => this.hide()
+ });
+
+ this.balloon.add({ view, position: getBalloonPosition(editor, shownAt) });
+ this.view = view;
+
+ const container = view.element;
+ /* v8 ignore next 4 -- the balloon renders the view as it adds it, so it has an element */
+ if (!container) {
+ this.hide();
+ return;
+ }
+
+ const release = render(container);
+ if (!release) {
+ this.hide();
+ return;
+ }
+
+ this.release = release;
+
+ // The host renders into the container only after `render` returns, and a balloon placed
+ // around an empty container puts its arrow half the content's width from the caret.
+ // Reposition on every size change, not just the first render. The reposition waits for
+ // the next frame because it can change the container's width, which Chrome reports as an
+ // observer loop.
+ this.resizeObserver = new ResizeObserver(() => {
+ cancelAnimationFrame(this.repositionFrame);
+
+ this.repositionFrame = requestAnimationFrame(() => {
+ /* v8 ignore next -- disconnecting the observer cancels the pending frames */
+ if (this.view) {
+ this.balloon.updatePosition();
+ }
+ });
+ });
+ this.resizeObserver.observe(container);
+ }
+
+ /** Removes the host's content and closes the balloon. Does nothing while it is closed. */
+ hide() {
+ const view = this.view;
+
+ this.view = null;
+ this.resizeObserver?.disconnect();
+ this.resizeObserver = null;
+ cancelAnimationFrame(this.repositionFrame);
+ this.release?.();
+ this.release = null;
+
+ if (!view) {
+ return;
+ }
+
+ /* v8 ignore next -- a view this balloon still references is one the balloon still has */
+ if (this.balloon.hasView(view)) {
+ this.balloon.remove(view);
+ }
+
+ view.destroy();
+ }
+
+}
+
+/**
+ * The view inside the balloon: an element for the host to render into, and nothing else.
+ *
+ * It has `ck-reset_all-excluded` because everything a balloon shows sits inside the body
+ * collection's `ck-reset_all`, which would strip the application's own styling from the content.
+ */
+class HostedBalloonView extends View {
+
+ public readonly keystrokes = new KeystrokeHandler();
+
+ constructor(locale: Locale, className: string) {
+ super(locale);
+
+ this.setTemplate({
+ tag: "div",
+ attributes: {
+ class: [ "ck-reset_all-excluded", className ]
+ }
+ });
+ }
+
+ public override render() {
+ super.render();
+
+ /* v8 ignore next 3 -- `render()` is what builds the element, so it is never absent here */
+ if (!this.element) {
+ return;
+ }
+
+ this.keystrokes.listenTo(this.element);
+ }
+
+ public override destroy() {
+ super.destroy();
+ this.keystrokes.destroy();
+ }
+
+}
+
+/** Where the balloon points: the caret, read again on every placement, as the emoji picker does. */
+function getBalloonPosition(editor: Editor, shownAt: ViewRange) {
+ const view = editor.editing.view;
+
+ return {
+ target: () => {
+ /* v8 ignore next -- a rendered document always has a range for the caret */
+ const range = view.document.selection.getFirstRange() ?? shownAt;
+
+ return view.domConverter.viewRangeToDom(range);
+ }
+ };
+}
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 5f1bbe2e9b..56518bdc21 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -31,6 +31,7 @@ export type { ContentEmbedHost } from "./plugins/content_embed/content_embed.js"
export type { AttachmentLinkChange } from "./plugins/referencelink.js";
export type { ChildNoteHost } from "./plugins/child_note.js";
export { getLinkAtSelection, replaceLinkAtSelection } from "./plugins/internallink.js";
+export type { LinkDialogRequest } from "./plugins/internallink.js";
export type { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.js";
export type { default as TriliumSlashCommands, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem } from "./plugins/mention/slash_commands.js";
export type { MentionHostedFeed, MentionHostedList, MentionHostedListState } from "./plugins/mention/types.js";
diff --git a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts
index 5a02ac4105..0fbe5bd348 100644
--- a/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts
+++ b/packages/ckeditor5/src/plugins/inline_icon/inline_icon_ui.ts
@@ -1,9 +1,7 @@
import bxSticker from "boxicons/svg/regular/bx-sticker.svg?raw";
-import {
- ButtonView, clickOutsideHandler, type Command, ContextualBalloon, type Editor,
- KeystrokeHandler, type Locale, Plugin, View, type ViewRange
-} from "ckeditor5";
+import { ButtonView, type Command, ContextualBalloon, Plugin } from "ckeditor5";
+import HostedBalloon from "../../hosted_balloon.js";
import { INSERT_ICON_COMMAND } from "./inline_icon_editing.js";
/**
@@ -29,11 +27,7 @@ export default class InlineIconUI extends Plugin {
return [ ContextualBalloon ] as const;
}
- private _balloon: ContextualBalloon = this.editor.plugins.get(ContextualBalloon);
- private _pickerView: IconPickerView | null = null;
- private _releasePicker: (() => void) | null = null;
- private _pickerResize: ResizeObserver | null = null;
- private _replacePicker = 0;
+ private picker = new HostedBalloon(this.editor, "icon-picker-balloon");
init() {
const editor = this.editor;
@@ -41,92 +35,26 @@ export default class InlineIconUI extends Plugin {
this.addPickerButton(INSERT_ICON_COMMAND, t("Icon"));
this.addPickerButton(CHANGE_ICON, t("Change icon"));
-
- // Esc reaches the editor only while the caret has focus, and the picker takes focus away,
- // so {@link IconPickerView} registers a handler of its own.
- editor.keystrokes.set("Esc", (_data, cancel) => {
- if (this._pickerView) {
- this._hide();
- cancel();
- }
- });
}
public override destroy() {
// Before the base class stops the listeners the balloon is taken down through.
- this._hide();
+ this.picker.hide();
super.destroy();
}
/** Opens the picker; the `/` palette calls this as well as the toolbar buttons. */
public showPicker() {
const editor = this.editor;
- const editorEl = editor.editing.view.getDomRoot();
- const shownAt = editor.editing.view.document.selection.getFirstRange();
-
- if (this._pickerView || !editorEl || !shownAt) {
- return;
- }
-
- const view = new IconPickerView(editor.locale);
- view.keystrokes.set("Esc", (_data, cancel) => {
- this._hide();
- editor.editing.view.focus();
- cancel();
- });
-
- // Wired per picker rather than once: the handler listens through the view, so destroying
- // the view on the way out stops it.
- clickOutsideHandler({
- emitter: view,
- activator: () => this._pickerView === view,
- /* v8 ignore next -- the balloon renders its panel as the editor starts up */
- contextElements: this._balloon.view.element ? [ this._balloon.view.element ] : [],
- callback: () => this._hide()
- });
-
- this._balloon.add({ view, position: getBalloonPosition(editor, shownAt) });
- this._pickerView = view;
-
- const container = view.element;
- /* v8 ignore next 4 -- the balloon renders the view as it adds it, so it has an element */
- if (!container) {
- this._hide();
- return;
- }
- const release = editor.config.get("inlineIcon")?.showPicker({
+ this.picker.show((container) => editor.config.get("inlineIcon")?.showPicker({
container,
onSelect: (iconClass) => {
- this._hide();
+ this.picker.hide();
editor.execute(INSERT_ICON_COMMAND, { iconClass });
editor.editing.view.focus();
}
- }) ?? null;
-
- if (!release) {
- this._hide();
- return;
- }
-
- this._releasePicker = release;
-
- // The host renders into the container only after the call above returns, and a balloon
- // placed around an empty container puts its arrow half the picker's width from the caret.
- // Reposition on every size change, not just the first render. The reposition waits for the
- // next frame because it can change the container's width, which Chrome reports as an
- // observer loop.
- this._pickerResize = new ResizeObserver(() => {
- cancelAnimationFrame(this._replacePicker);
-
- this._replacePicker = requestAnimationFrame(() => {
- /* v8 ignore next -- disconnecting the observer cancels the pending frames */
- if (this._pickerView) {
- this._balloon.updatePosition();
- }
- });
- });
- this._pickerResize.observe(container);
+ }) ?? null);
}
/**
@@ -155,81 +83,6 @@ export default class InlineIconUI extends Plugin {
});
}
- private _hide() {
- const view = this._pickerView;
-
- this._pickerView = null;
- this._pickerResize?.disconnect();
- this._pickerResize = null;
- cancelAnimationFrame(this._replacePicker);
- this._releasePicker?.();
- this._releasePicker = null;
-
- if (!view) {
- return;
- }
-
- /* v8 ignore next -- a picker this plugin still references is one the balloon still has */
- if (this._balloon.hasView(view)) {
- this._balloon.remove(view);
- }
-
- view.destroy();
- }
-
-}
-
-/**
- * The view inside the balloon: an element for the host to render into, and nothing else.
- *
- * It has `ck-reset_all-excluded` because everything a balloon shows sits inside the body
- * collection's `ck-reset_all`, which would strip the application's own styling from the picker.
- */
-class IconPickerView extends View {
-
- public readonly keystrokes = new KeystrokeHandler();
-
- constructor(locale: Locale) {
- super(locale);
-
- this.setTemplate({
- tag: "div",
- attributes: {
- class: [ "ck-reset_all-excluded", "icon-picker-balloon" ]
- }
- });
- }
-
- public override render() {
- super.render();
-
- /* v8 ignore next 3 -- `render()` is what builds the element, so it is never absent here */
- if (!this.element) {
- return;
- }
-
- this.keystrokes.listenTo(this.element);
- }
-
- public override destroy() {
- super.destroy();
- this.keystrokes.destroy();
- }
-
-}
-
-/** Where the balloon points: the caret, read again on every placement, as the emoji picker does. */
-function getBalloonPosition(editor: Editor, shownAt: ViewRange) {
- const view = editor.editing.view;
-
- return {
- target: () => {
- /* v8 ignore next -- a rendered document always has a range for the caret */
- const range = view.document.selection.getFirstRange() ?? shownAt;
-
- return view.domConverter.viewRangeToDom(range);
- }
- };
}
/** What the editor asks the host's icon picker for. */
diff --git a/packages/ckeditor5/src/plugins/internallink.spec.ts b/packages/ckeditor5/src/plugins/internallink.spec.ts
index 310d93cd4a..6b22bd3f14 100644
--- a/packages/ckeditor5/src/plugins/internallink.spec.ts
+++ b/packages/ckeditor5/src/plugins/internallink.spec.ts
@@ -7,29 +7,75 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
import InternalLinkPlugin, {
- COMMAND_NAME, getLinkAtSelection, replaceLinkAtSelection
+ COMMAND_NAME, getLinkAtSelection, type LinkDialogRequest, replaceLinkAtSelection
} from "./internallink.js";
describe("InternalLinkPlugin", () => {
let editor: ClassicEditor;
- let openDialog: ReturnType<typeof vi.fn>;
+ let showDialog: ReturnType<typeof vi.fn>;
beforeEach(async () => {
- openDialog = vi.fn();
+ showDialog = vi.fn();
editor = await createTestEditor([Essentials, Paragraph, CodeBlock, InternalLinkPlugin], {
- internalLink: { openDialog }
+ internalLink: { showDialog }
});
});
+ /** Has the host render into the balloon, answering with the request and the release. */
+ function renderIntoBalloon() {
+ const shown: { request?: LinkDialogRequest } = {};
+ const release = vi.fn();
+ showDialog.mockImplementation((request: LinkDialogRequest) => {
+ shown.request = request;
+ return release;
+ });
+ return { shown, release };
+ }
+
it("loads the plugin and registers the command and toolbar button", () => {
expect(editor.plugins.get(InternalLinkPlugin)).toBeInstanceOf(InternalLinkPlugin);
expect(editor.commands.get(COMMAND_NAME)).toBeDefined();
expect(editor.ui.componentFactory.has("internalLink")).toBe(true);
});
- it("has the host open the Add link dialog when executed", () => {
+ it("opens the host's dialog in a balloon at the caret, until the host closes it", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ const { shown, release } = renderIntoBalloon();
+ const balloon = editor.plugins.get(ContextualBalloon);
+
+ editor.execute(COMMAND_NAME, { target: "url" });
+ const container = shown.request?.container;
+ expect(shown.request?.target).toBe("url");
+ expect(container?.classList.contains("add-link-balloon")).toBe(true);
+ expect(container && balloon.view.element?.contains(container)).toBe(true);
+
+ shown.request?.close();
+ expect(release).toHaveBeenCalledOnce();
+ expect(balloon.visibleView).toBeNull();
+ });
+
+ it("closes the balloon for a host that shows the dialog its own way, or has none", async () => {
+ const plainEditor = await createTestEditor([ Essentials, Paragraph, InternalLinkPlugin ]);
+
+ for (const testEditor of [ editor, plainEditor ]) {
+ setModelData(testEditor.model, "<paragraph>foo[]</paragraph>");
+ const balloon = testEditor.plugins.get(ContextualBalloon);
+ const add = vi.spyOn(balloon, "add");
+
+ testEditor.execute(COMMAND_NAME);
+ expect(add).toHaveBeenCalledOnce();
+ expect(balloon.visibleView).toBeNull();
+ }
+ expect(showDialog).toHaveBeenCalledOnce();
+ });
+
+ it("lets go of the dialog when the editor is torn down under it", async () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ const { release } = renderIntoBalloon();
editor.execute(COMMAND_NAME);
- expect(openDialog).toHaveBeenCalledOnce();
+
+ await editor.destroy();
+ expect(release).toHaveBeenCalledOnce();
});
it("labels the button without the shortcut, leaving that to the keystroke", () => {
@@ -167,12 +213,12 @@ describe("the link at the selection", () => {
describe("the edit button of the link toolbar", () => {
let editor: ClassicEditor;
- let openDialog: ReturnType<typeof vi.fn>;
+ let showDialog: ReturnType<typeof vi.fn>;
beforeEach(async () => {
- openDialog = vi.fn();
+ showDialog = vi.fn();
editor = await createTestEditor([Essentials, Paragraph, Link, InternalLinkPlugin], {
- internalLink: { openDialog }
+ internalLink: { showDialog }
});
});
@@ -189,7 +235,7 @@ describe("the edit button of the link toolbar", () => {
expect(edit).toBeInstanceOf(ButtonView);
edit?.fire("execute");
- expect(openDialog).toHaveBeenCalledOnce();
+ expect(showDialog).toHaveBeenCalledOnce();
expect(toolbarView && balloon.hasView(toolbarView)).toBe(false);
expect(linkUI.formView && balloon.hasView(linkUI.formView)).toBe(false);
});
@@ -197,12 +243,12 @@ describe("the edit button of the link toolbar", () => {
describe("the link button and Ctrl+K", () => {
let editor: ClassicEditor;
- let openDialog: ReturnType<typeof vi.fn>;
+ let showDialog: ReturnType<typeof vi.fn>;
beforeEach(async () => {
- openDialog = vi.fn();
+ showDialog = vi.fn();
editor = await createTestEditor([Essentials, Paragraph, Link, InternalLinkPlugin], {
- internalLink: { openDialog }
+ internalLink: { showDialog }
});
});
@@ -231,7 +277,8 @@ describe("the link button and Ctrl+K", () => {
expect(button.isOn).toBe(false);
button.fire("execute");
- expect(openDialog).toHaveBeenCalledExactlyOnceWith({ target: "url" });
+ expect(showDialog)
+ .toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ target: "url" }));
expect(isLinkFormShown()).toBe(false);
// The button shows as on in a link, and off where no link can be made.
@@ -244,7 +291,8 @@ describe("the link button and Ctrl+K", () => {
it("opens the link dialog on Ctrl+K in the text", () => {
setModelData(editor.model, "<paragraph>foo[]</paragraph>");
expect(pressCtrlK(editor.keystrokes)).toBe(true);
- expect(openDialog).toHaveBeenCalledExactlyOnceWith({ target: "url" });
+ expect(showDialog)
+ .toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ target: "url" }));
expect(isLinkFormShown()).toBe(false);
});
@@ -267,7 +315,7 @@ describe("the link button and Ctrl+K", () => {
});
element.dispatchEvent(keydown);
expect(keydown.defaultPrevented).toBe(true);
- expect(openDialog).toHaveBeenCalledTimes(shown);
+ expect(showDialog).toHaveBeenCalledTimes(shown);
expect(balloon.hasView(linkUI.toolbarView)).toBe(false);
}
expect(linkUI.formView).not.toBeNull();
diff --git a/packages/ckeditor5/src/plugins/internallink.ts b/packages/ckeditor5/src/plugins/internallink.ts
index eb173903b0..361b8c2f20 100644
--- a/packages/ckeditor5/src/plugins/internallink.ts
+++ b/packages/ckeditor5/src/plugins/internallink.ts
@@ -3,6 +3,7 @@ import {
ModelLiveRange, Plugin
} from 'ckeditor5';
import type { Editor, LinkCommand, ModelRange, View } from 'ckeditor5';
+import HostedBalloon from '../hosted_balloon.js';
import internalLinkIcon from '../icons/trilium.svg?raw';
import ReferenceLink, { getReferenceTitle, referenceAttributes } from './referencelink';
@@ -16,12 +17,22 @@ export interface InternalLinkDialogOptions {
target?: 'note' | 'url';
}
+/** The request that the editor passes to the host's link dialog. */
+export interface LinkDialogRequest extends InternalLinkDialogOptions {
+ /** The element to render the dialog into, which the editor owns and places at the caret. */
+ container: HTMLElement;
+ /** Closes the balloon. The host calls it once the link is applied. */
+ close(): void;
+}
+
export default class InternalLinkPlugin extends Plugin {
static get requires() {
- return [ ReferenceLink ];
+ return [ ReferenceLink, ContextualBalloon ];
}
+ private dialog = new HostedBalloon(this.editor, 'add-link-balloon');
+
init() {
const editor = this.editor;
const t = editor.t;
@@ -121,6 +132,25 @@ export default class InternalLinkPlugin extends Plugin {
isToolbarKeystrokeSet = true;
});
}
+
+ override destroy() {
+ this.dialog.hide();
+ super.destroy();
+ }
+
+ /**
+ * Opens the link dialog in a balloon at the caret. A host that shows the dialog its own way
+ * leaves the balloon empty, which closes it again.
+ */
+ showDialog(options: InternalLinkDialogOptions = {}) {
+ const editor = this.editor;
+
+ this.dialog.show(container => editor.config.get('internalLink')?.showDialog({
+ ...options,
+ container,
+ close: () => this.dialog.hide()
+ }) ?? null);
+ }
}
class InsertInternalLinkCommand extends Command {
@@ -134,7 +164,7 @@ class InsertInternalLinkCommand extends Command {
}
execute(options?: InternalLinkDialogOptions) {
- this.editor.config.get('internalLink')?.openDialog(options);
+ this.editor.plugins.get(InternalLinkPlugin).showDialog(options);
}
}
@@ -223,8 +253,13 @@ function findLinkAtSelection(editor: Editor): { href: string; range: ModelRange
declare module 'ckeditor5' {
interface EditorConfig {
internalLink?: {
- /** Opens the dialog that adds a link at the selection, or edits the link there. */
- openDialog(options?: InternalLinkDialogOptions): void;
+ /**
+ * Renders the dialog that adds a link at the selection, or edits the link there, into
+ * `request.container`, and returns the function that removes it. A host that shows the
+ * dialog somewhere else (a phone, which has no room for a balloon) leaves the container
+ * alone and returns `null`.
+ */
+ showDialog(request: LinkDialogRequest): (() => void) | null;
};
}
}
diff --git a/packages/ckeditor5/src/plugins/mobile_toolbar_items.spec.ts b/packages/ckeditor5/src/plugins/mobile_toolbar_items.spec.ts
index d71c29aa03..845ec25e77 100644
--- a/packages/ckeditor5/src/plugins/mobile_toolbar_items.spec.ts
+++ b/packages/ckeditor5/src/plugins/mobile_toolbar_items.spec.ts
@@ -301,10 +301,10 @@ describe("MobileToolbarItems", () => {
describe("addLink", () => {
it("opens the link dialog of the internal link button, under the link icon", async () => {
- const openDialog = vi.fn();
+ const showDialog = vi.fn();
const editor = await createTestEditor([Essentials, Paragraph, InternalLinkPlugin, MobileToolbarItems], {
toolbar: ["addLink"],
- internalLink: { openDialog }
+ internalLink: { showDialog }
});
setModelData(editor.model, "<paragraph>foo[]</paragraph>");
@@ -313,7 +313,7 @@ describe("addLink", () => {
};
expect([button.label, button.icon, button.isEnabled]).toStrictEqual(["Link", IconLink, true]);
button.fire("execute");
- expect(openDialog).toHaveBeenCalledOnce();
+ expect(showDialog).toHaveBeenCalledOnce();
editor.enableReadOnlyMode("spec");
expect(button.isEnabled).toBe(false);