Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor/link editor: handle link previews, remove the old UI
Adorian Doran73a34fcd1ed0
diff --git a/.claude/skills/ckeditor5-plugin-development/harness/kit.ts b/.claude/skills/ckeditor5-plugin-development/harness/kit.tsindex 63e92ee612..52c52da0a2 100644--- a/.claude/skills/ckeditor5-plugin-development/harness/kit.ts+++ b/.claude/skills/ckeditor5-plugin-development/harness/kit.ts@@ -22,7 +22,6 @@ import blockquote from "./theme/blockquote.css?inline";import ckContentRaw from "./theme/ck-content.css?raw";import codeBlockToolbar from "./theme/code_block_toolbar.css?inline";import contentColors from "./theme/content_colors.css?inline";-import linkEmbedForm from "./theme/link_embed_form.css?inline";import todoLists from "./theme/todo_lists.css?inline";import oldFull from "./zz_ckcss_old.css?inline";import oldContent from "./zz_ckcss_old_content.css?inline";@@ -30,7 +29,7 @@ import oldContent from "./zz_ckcss_old_content.css?inline";export type Side = "old" | "new";/** What `src/index.ts` imports after `ckeditor5/ckeditor5.css`. Keep in step with it. */-const PACKAGE_LAYER = [ blockquote, contentColors, codeBlockToolbar, linkEmbedForm ];+const PACKAGE_LAYER = [ blockquote, contentColors, codeBlockToolbar ];/** `ck-content.css` without its `@import`s, which the share and export contexts load explicitly. */const CK_CONTENT_REST = ckContentRaw.replace(/@import[^;]*;/g, "");diff --git a/apps/client/src/stylesheets/theme-next/forms.css b/apps/client/src/stylesheets/theme-next/forms.cssindex 3a9c2cb4df..18f5eef1fa 100644--- a/apps/client/src/stylesheets/theme-next/forms.css+++ b/apps/client/src/stylesheets/theme-next/forms.css@@ -270,8 +270,7 @@ select.form-select,select.form-control,.select-button.dropdown-toggle.btn,:root .ck.ck-labeled-field-view__input-wrapper > .ck.ck-dropdown > button.ck.ck-dropdown__button,-:root .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button,-:root .ck.ck-link-embed-form__actions > .ck.ck-dropdown > button.ck.ck-dropdown__button {+:root .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button {--dropdown-arrow: var(--select-arrow-svg) right 0.75rem center/15px 20px no-repeat;outline: 3px solid transparent;@@ -289,9 +288,7 @@ body[dir=rtl] select.form-control,body[dir=rtl] .select-button.dropdown-toggle.btn,:root body[dir=rtl] .ck.ck-labeled-field-view__input-wrapper > .ck.ck-dropdown> button.ck.ck-dropdown__button,-:root body[dir=rtl] .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button,-:root body[dir=rtl] .ck.ck-link-embed-form__actions > .ck.ck-dropdown- > button.ck.ck-dropdown__button {+:root body[dir=rtl] .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button {background-position: left 0.75rem center;}@@ -301,8 +298,7 @@ select.form-control:hover,.select-button.dropdown-toggle.btn:hover,:root .ck.ck-labeled-field-view__input-wrapper > .ck.ck-dropdown> button.ck.ck-dropdown__button:hover,-:root .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button:hover,-:root .ck.ck-link-embed-form__actions > .ck.ck-dropdown > button.ck.ck-dropdown__button:hover {+:root .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button:hover {background: var(--input-hover-background) var(--dropdown-arrow,);color: var(--input-hover-color);}@@ -310,8 +306,7 @@ select.form-control:hover,button.select-button.dropdown-toggle.btn:active,:root .ck.ck-labeled-field-view__input-wrapper > .ck.ck-dropdown> button.ck.ck-dropdown__button:active,-:root .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button:active,-:root .ck.ck-link-embed-form__actions > .ck.ck-dropdown > button.ck.ck-dropdown__button:active {+:root .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button:active {background-color: transparent;color: var(--select-focus-text-color);}@@ -324,8 +319,6 @@ select.form-control:focus,:root .ck.ck-labeled-field-view__input-wrapper > .ck.ck-dropdown> button.ck.ck-dropdown__button:is(:focus, .ck-on),:root .ck.ck-emoji__skin-tone > .ck.ck-dropdown- > button.ck.ck-dropdown__button:is(:focus, .ck-on),-:root .ck.ck-link-embed-form__actions > .ck.ck-dropdown> button.ck.ck-dropdown__button:is(:focus, .ck-on) {box-shadow: unset;outline: 3px solid var(--input-focus-outline-color);@@ -342,9 +335,7 @@ select.form-select:disabled,select.form-control:disabled,:root .ck.ck-labeled-field-view__input-wrapper > .ck.ck-dropdown> button.ck.ck-dropdown__button.ck-disabled,-:root .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button.ck-disabled,-:root .ck.ck-link-embed-form__actions > .ck.ck-dropdown- > button.ck.ck-dropdown__button.ck-disabled {+:root .ck.ck-emoji__skin-tone > .ck.ck-dropdown > button.ck.ck-dropdown__button.ck-disabled {background: var(--input-background-color) var(--dropdown-arrow);color: var(--input-text-color);opacity: 0.65;diff --git a/apps/client/src/stylesheets/theme-next/notes/text.css b/apps/client/src/stylesheets/theme-next/notes/text.cssindex 1476b33b84..3c69557e56 100644--- a/apps/client/src/stylesheets/theme-next/notes/text.css+++ b/apps/client/src/stylesheets/theme-next/notes/text.css@@ -880,22 +880,15 @@ button.ck.ck-button:is(.ck-button-action, .ck-button-save, .ck-button-cancel, .c/* forms.css draws the arrow as a background and dims the whole box when disabled. */:root .ck-labeled-field-view__input-wrapper > .ck-dropdown .ck-dropdown__arrow,-:root .ck-emoji__skin-tone > .ck-dropdown .ck-dropdown__arrow,-:root .ck-link-embed-form__actions > .ck-dropdown .ck-dropdown__arrow {+:root .ck-emoji__skin-tone > .ck-dropdown .ck-dropdown__arrow {display: none;}:root .ck-labeled-field-view__input-wrapper > .ck.ck-dropdown- > .ck-button.ck-dropdown__button.ck-disabled .ck-button__label,-:root .ck-link-embed-form__actions > .ck.ck-dropdown> .ck-button.ck-dropdown__button.ck-disabled .ck-button__label {opacity: 1;}-:root .ck.ck-link-embed-form__actions > .ck.ck-dropdown > button.ck.ck-dropdown__button {- padding-inline-start: var(--ck-spacing-padding);-}-/** Color inputs*/diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex fe7d59bfac..92eb16de54 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -69,7 +69,13 @@"web_link": "Web link","url": "URL","mirror_title": "Mirror the note's title",- "mirror_title_description": "The link shows the note's current title, and changes when the note is renamed."+ "mirror_title_description": "The link shows the note's current title, and changes when the note is renamed.",+ "display_as": "Display as",+ "display_plain": "Plain link",+ "display_inline": "Inline",+ "display_card": "Card",+ "display_embed": "YouTube embed",+ "page_title": "Title of the web page"},"branch_prefix": {"edit_branch_prefix": "Edit branch prefix",@@ -4490,7 +4496,6 @@"drag-to-reposition-the-collapsible-block": "Drag to reposition the collapsible block","edit-anchor": "Edit anchor","edit-task-states": "Edit task states",- "edit-title": "Edit title","embed": "Embed","enter-caption": "Enter caption","enter-the-anchor-name-without-spaces": "Enter the anchor name without spaces.",@@ -4569,7 +4574,6 @@"the-file-is-too-large-to-be-uploaded-http-413-if-trilium-is-behind-a-reverse-proxy-raise-its-request-body-size-limit": "The file is too large to be uploaded (HTTP 413). If Trilium is behind a reverse proxy, raise its request body size limit.","the-server-responded-with-http-0": "The server responded with HTTP %0.","tip": "Tip",- "title": "Title","to-do-list": "To-do list","toggle-collapsible-block": "Toggle collapsible block","tokens": "tokens",@@ -4579,7 +4583,6 @@"type-the-content-here": "Type the content here...","undefined-custom-task-state": "Undefined custom task state","unknown-embed-widget": "unknown embed widget",- "url": "URL","upload-an-image-from-your-device": "Upload an image from your device.","upload-files-as-attachments-and-insert-embeds": "Upload files as attachments and insert embeds.","upload-files-as-attachments-and-insert-links": "Upload files as attachments and insert links.",diff --git a/apps/client/src/widgets/dialogs/add_link.spec.tsx b/apps/client/src/widgets/dialogs/add_link.spec.tsxindex 30be856993..01b418c212 100644--- a/apps/client/src/widgets/dialogs/add_link.spec.tsx+++ b/apps/client/src/widgets/dialogs/add_link.spec.tsx@@ -8,7 +8,9 @@ import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";import Modal from "../react/Modal";import { ParentComponent } from "../react/react_utils";-import AddLinkDialog, { AddLinkBalloon, type AddLinkOpts, normalizeWebLink } from "./add_link";+import AddLinkDialog, {+ AddLinkBalloon, type AddLinkOpts, getShownDisplay, normalizeWebLink+} from "./add_link";const autocomplete = vi.hoisted(() => ({onChange: undefined as ((suggestion: Suggestion | null) => void) | undefined@@ -39,10 +41,23 @@ describe("normalizeWebLink", () => {});});+describe("getShownDisplay", () => {+ it("shows the display picked, a card for a player the address lacks, a plain link off the web", () => {+ const video = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";+ expect(getShownDisplay("inline", "https://example.com")).toBe("inline");+ expect(getShownDisplay("embed", video)).toBe("embed");+ expect(getShownDisplay("card", video)).toBe("card");+ expect(getShownDisplay("embed", "https://example.com")).toBe("card");+ expect(getShownDisplay("embed", undefined)).toBe("card");+ expect(getShownDisplay("card", "mailto:[email protected]")).toBe("plain");+ });+});+describe("AddLinkDialog", () => {let host: Component;let container: HTMLElement;const addLink = vi.fn<AddLinkOpts["addLink"]>(async () => {});+ const addLinkPreview = vi.fn<NonNullable<AddLinkOpts["addLinkPreview"]>>(async () => {});beforeEach(() => {vi.clearAllMocks();@@ -93,6 +108,23 @@ describe("AddLinkDialog", () => {return container.querySelector<HTMLInputElement>(`.add-link-${name} input`);}+ function displaySelect() {+ return container.querySelector<HTMLSelectElement>(".add-link-display select");+ }++ function displays() {+ return [ ...displaySelect()?.options ?? [] ].map((option) => option.textContent);+ }++ async function pickDisplay(value: string) {+ const select = displaySelect();+ if (!select) throw new Error("The dialog offers no display.");+ await act(async () => {+ select.value = value;+ select.dispatchEvent(new Event("change", { bubbles: true }));+ });+ }+async function submit() {const form = container.querySelector("form");const modal = container.querySelector(".modal");@@ -268,6 +300,90 @@ describe("AddLinkDialog", () => {}});+ it("offers how a web link is displayed to a caller that shows previews, and applies a preview", async () => {+ await open({ target: "url" });+ expect(displaySelect()).toBeNull();++ await open({ target: "url", addLinkPreview });+ expect(headings()).toStrictEqual([]);+ expect(displays()).toStrictEqual(+ [ "add_link.display_plain", "add_link.display_inline", "add_link.display_card" ]+ );+ const video = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";+ await type(field("url"), video);+ expect(displays()).toContain("add_link.display_embed");+ await pickDisplay("card");+ await type(field("text"), "Never gonna");+ await submit();+ expect(addLinkPreview).toHaveBeenLastCalledWith(video, "card", "Never gonna");+ expect(addLink).not.toHaveBeenCalled();++ // A player shows no title.+ await open({ target: "url", display: "embed", addLinkPreview });+ await type(field("url"), video);+ expect(field("text")).toBeNull();+ await submit();+ expect(addLinkPreview).toHaveBeenLastCalledWith(video, "embed", null);++ // A plain link, and any address that is not a web page, stays a link.+ await open({ target: "url", addLinkPreview });+ await type(field("url"), "example.com");+ await submit();+ expect(addLink).toHaveBeenLastCalledWith("https://example.com", "https://example.com", true);+ await open({ target: "url", display: "card", addLinkPreview });+ await type(field("url"), "mailto:[email protected]");+ expect(displaySelect()?.disabled).toBe(true);+ await submit();+ expect(addLink).toHaveBeenLastCalledWith(+ "mailto:[email protected]", "mailto:[email protected]", true+ );+ expect(addLinkPreview).toHaveBeenCalledTimes(2);+ });++ it("turns an edited link into a preview with the page's own title unless it has a text", async () => {+ const url = "https://example.com/page";+ await open({ currentLink: { externalLink: url }, currentTitle: url, addLinkPreview });+ await pickDisplay("inline");+ await submit();+ expect(addLinkPreview).toHaveBeenLastCalledWith(url, "inline", null);++ await open({ currentLink: { externalLink: url }, currentTitle: "Page", addLinkPreview });+ await pickDisplay("card");+ await submit();+ expect(addLinkPreview).toHaveBeenLastCalledWith(url, "card", "Page");+ expect(addLink).not.toHaveBeenCalled();+ });++ it("edits a link preview, giving another address the title of its own page", async () => {+ const url = "https://example.com/page";+ await open({+ currentLink: { externalLink: url }, currentTitle: "Page", display: "card", addLinkPreview+ });+ expect(field("url")?.value).toBe(url);+ expect(field("text")?.value).toBe("Page");+ expect(displays()).toStrictEqual(+ [ "add_link.display_plain", "add_link.display_inline", "add_link.display_card" ]+ );+ await submit();+ expect(addLinkPreview).toHaveBeenLastCalledWith(url, "card", "Page");++ await open({+ currentLink: { externalLink: url }, currentTitle: "Page", display: "card", addLinkPreview+ });+ await type(field("url"), "https://example.com/other");+ expect(field("text")?.value).toBe("");+ await type(field("text"), "Mine");+ await type(field("url"), "https://example.com/third");+ expect(field("text")?.value).toBe("Mine");+ await submit();+ expect(addLinkPreview).toHaveBeenLastCalledWith("https://example.com/third", "card", "Mine");++ // A plain link keeps its text for another address.+ await open({ currentLink: { externalLink: url }, currentTitle: "Page", addLinkPreview });+ await type(field("url"), "https://example.com/other");+ expect(field("text")?.value).toBe("Page");+ });+it("offers no web link when fixing a link to a missing note", async () => {await open({ text: "Gone", fixLink: true });expect(choice()).toStrictEqual([]);diff --git a/apps/client/src/widgets/dialogs/add_link.tsx b/apps/client/src/widgets/dialogs/add_link.tsxindex 7e79956882..4a9655b9a8 100644--- a/apps/client/src/widgets/dialogs/add_link.tsx+++ b/apps/client/src/widgets/dialogs/add_link.tsx@@ -1,10 +1,12 @@import "./add_link.css";-import { ALLOWED_PROTOCOLS } from "@triliumnext/commons";+import type { LinkDisplayMode } from "@triliumnext/ckeditor5";+import { ALLOWED_PROTOCOLS, isHttpUrl } from "@triliumnext/commons";import { useEffect, useRef, useState } from "preact/hooks";import froca from "../../services/froca";import { t } from "../../services/i18n";+import { detectEmbedType } from "../../services/link_embed";import type { Suggestion } from "../../services/note_autocomplete";import tree from "../../services/tree";import { isMobile } from "../../services/utils";@@ -83,7 +85,18 @@ export interface AddLinkOpts {* `text`, and offers only notes, always as a reference link.*/fixLink?: boolean;+ /**+ * How the web link is displayed: a plain link by default, or as the link preview being edited.+ * `embed` falls back to a card for an address without a player.+ */+ display?: LinkDisplayMode;addLink(notePath: string, linkTitle: string | null, externalLink?: boolean): Promise<void>;+ /**+ * Puts a preview of the web link in place of the link. A caller that can show previews passes+ * it, and the dialog then offers the choice of how a web link is displayed. `title` replaces+ * the page's own title.+ */+ addLinkPreview?(url: string, display: LinkDisplayMode, title: string | null): Promise<void>;}export default function AddLinkDialog() {@@ -175,11 +188,14 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {const [ noteTitle, setNoteTitle ] = useState("");const [ target, setTarget ] = useState<LinkTarget>("note");const [ webLink, setWebLink ] = useState("");+ const [ display, setDisplay ] = useState<LinkDisplayMode>("plain");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);const initialBookmarkRef = useRef("");+ // The title of the link preview being edited, while the title field still shows it.+ const previewTitleRef = useRef<string | null>(null);// On mobile, focusing a field opens the keyboard, so a field waits for a tap.const autoFocus = !isMobile();@@ -193,7 +209,10 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {const initialWebLink = opts ? getInitialWebLink(opts) : null;setTarget(initialWebLink !== null ? "url" : "note");setWebLink(initialWebLink ?? "");+ setDisplay(opts?.display ?? "plain");keptTitleRef.current = opts?.currentTitle ?? null;+ previewTitleRef.current = opts?.currentLink && opts.display && opts.display !== "plain"+ ? opts.currentTitle ?? null : null;initialBookmarkRef.current = opts?.currentBookmark ?? "";setLinkTitle(opts?.currentTitle ?? "");@@ -208,6 +227,11 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {setWebLink(text);const link = normalizeWebLink(text);setSuggestion(link ? { externalLink: link } : null);+ // A preview's title is its page's, so another address takes the title of its own page.+ if (previewTitleRef.current !== null && linkTitle === previewTitleRef.current) {+ setLinkTitle("");+ }+ previewTitleRef.current = null;}function changeTarget(next: LinkTarget, text = "") {@@ -356,7 +380,14 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {}}- /** Applies the link picked, through `opts.addLink`. */+ const showsDisplay = target === "url" && !!opts?.addLinkPreview;+ const shownDisplay = getShownDisplay(display, suggestion?.externalLink);+ const isPreview = showsDisplay && shownDisplay !== "plain";+ const showsTitle = !opts?.hasSelection && !opts?.targetOnly && !opts?.fixLink;+ // A video player shows no title.+ const showsWebLinkTitle = showsTitle && !(showsDisplay && shownDisplay === "embed");++ /** Applies the link picked, through `opts.addLink` or `opts.addLinkPreview`. */function applyLink() {if (!opts || !suggestion) return;@@ -367,9 +398,16 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {: suggestion.notePath;opts.addLink(path, linkType === "reference-link" ? null : linkTitle);} else if (suggestion.externalLink) {+ const url = suggestion.externalLink;+ const text = linkTitle.trim();+ if (isPreview && opts.addLinkPreview) {+ // A text that only repeats the address leaves the page's own title.+ const title = shownDisplay !== "embed" && text && text !== url ? text : null;+ void opts.addLinkPreview(url, shownDisplay, title);+ return;+ }// 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);+ opts.addLink(url, text || url, true);}}@@ -387,18 +425,26 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {const buttonText = opts?.fixLink ? t("add_link.button_fix_link"): opts?.currentLink ? t("add_link.button_edit_link") : t("add_link.button_add_link");- const showsTitle = !opts?.hasSelection && !opts?.targetOnly && !opts?.fixLink;const titleSection = (<OptionCardSectionclassName="add-link-text" name="link-title" label={t("add_link.link_title")}><FormTextBoxcurrentValue={linkTitle}- placeholder={target === "url" ? suggestion?.externalLink : undefined}+ placeholder={target !== "url" ? undefined+ : isPreview ? t("add_link.page_title") : suggestion?.externalLink}onChange={setLinkTitle}/></OptionCardSection>);+ const displays = [+ { value: "plain", title: t("add_link.display_plain") },+ { value: "inline", title: t("add_link.display_inline") },+ { value: "card", title: t("add_link.display_card") },+ ...(hasPlayer(suggestion?.externalLink)+ ? [ { value: "embed", title: t("add_link.display_embed") } ]+ : [])+ ];return {title,@@ -423,22 +469,40 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {<Card>{target === "url" ? (- <OptionCardSection- className="add-link-url" name="url" label={t("add_link.url")}- subSectionsVisible={showsTitle}- subSections={titleSection}- >- <FormTextBox- inputRef={webLinkRef}- inputMode="url"- autoCapitalize="off"- autoCorrect="off"- spellcheck={false}- placeholder="https://"- currentValue={webLink}- onChange={changeWebLink}- />- </OptionCardSection>+ <>+ <OptionCardSection+ className="add-link-url" name="url" label={t("add_link.url")}+ subSectionsVisible={showsWebLinkTitle}+ subSections={titleSection}+ >+ <FormTextBox+ inputRef={webLinkRef}+ inputMode="url"+ autoCapitalize="off"+ autoCorrect="off"+ spellcheck={false}+ placeholder="https://"+ currentValue={webLink}+ onChange={changeWebLink}+ />+ </OptionCardSection>++ {showsDisplay && (+ <OptionCardSection+ className="add-link-display" name="display"+ label={t("add_link.display_as")}+ >+ <FormSelect+ values={displays}+ keyProperty="value"+ titleProperty="title"+ currentValue={shownDisplay}+ disabled={!canPreview(suggestion?.externalLink)}+ onChange={(next) => setDisplay(next as LinkDisplayMode)}+ />+ </OptionCardSection>+ )}+ </>) : (<><OptionCardSection@@ -523,6 +587,27 @@ function getInitialWebLink(opts: AddLinkOpts): string | null {return opts.target === "url" ? "" : null;}+/**+ * How the web link to `url` is displayed when `display` is picked: as a plain link when the address+ * is not a web page, and as a card in place of a player that the address does not have.+ *+ * Exported for testing.+ */+export function getShownDisplay(display: LinkDisplayMode, url: string | undefined): LinkDisplayMode {+ if (!canPreview(url)) return "plain";+ return display === "embed" && !hasPlayer(url) ? "card" : display;+}++/** Whether a web link to `url` can be a preview: a web page, or no address typed yet. */+function canPreview(url: string | undefined) {+ return !url || isHttpUrl(url);+}++/** Whether `url` has a video player to embed. */+function hasPlayer(url: string | undefined) {+ return !!url && detectEmbedType(url) !== "opengraph";+}+/** Whether `text` is a whole URL with a scheme, the way the note search tells URLs apart. */function hasScheme(text: string) {return /^[a-z][a-z0-9+.-]*:\/\/\S+$/i.test(text);diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsxindex 8c782be30e..fd5efba361 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx@@ -1,7 +1,7 @@import {type CKEditorError, CKTextEditor, ClassicEditor, getLinkAtSelection, type IconPickerRequest,- type LinkDialogRequest, onTextEditorError, PopupEditor, replaceLinkAtSelection,- SnippetDefinition+ type LinkAtSelection, type LinkDialogRequest, type LinkDisplayMode, onTextEditorError,+ PopupEditor, replaceLinkAtSelection, SnippetDefinition} from "@triliumnext/ckeditor5";import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";import { createPortal, HTMLAttributes, RefObject } from "preact";@@ -21,11 +21,19 @@ export interface CKEditorApi {/** returns true if user selected some text, false if there's no selection */hasSelection(): boolean;getSelectedText(): string;- /** The address and the whole text of the link around the caret, or `null` outside one. */- getCurrentLink(): { href: string; text: string } | null;+ /** The link around the caret or the selected link preview, or `null` outside one. */+ getCurrentLink(): LinkAtSelection | null;addLink(notePath: string, linkTitle: string | null, externalLink?: boolean): void;- /** Rewrites the link around the caret, as {@link addLink} would write a new one. */+ /**+ * Rewrites the link around the caret or the selected link preview, as {@link addLink} would+ * write a new one.+ */updateLink(notePath: string, linkTitle: string | null, externalLink?: boolean): Promise<void>;+ /**+ * Puts a preview of `url` in place of the link around the caret or the selected link preview,+ * or at the selection. `title` replaces the page's own title.+ */+ addLinkPreview(url: string, display: LinkDisplayMode, title: string | null): void;addLinkToEditor(linkHref: string, linkTitle: string): void;addHtmlToEditor(html: string): void;addContentEmbed(noteId: string, boxSize?: BoxSize): void;@@ -201,6 +209,13 @@ export default function CKEditor({const href = externalLink ? notePath : `#${notePath}`;await replaceLinkAtSelection(editor, href, linkTitle);},+ addLinkPreview(url, display, title) {+ const editor = editorRef.current;+ if (!editor) return;++ editor.editing.view.focus();+ void editor.execute("insertLinkEmbed", { url, mode: display, title: title ?? undefined });+ },addLink(notePath, linkTitle, externalLink) {const editor = editorRef.current;if (!editor) return;diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex fa3b3c04de..16f54b0dc3 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -6,7 +6,9 @@* crash and restarted the editor, which reverted the note to its last saved content — the images* being uploaded flickered and vanished instead of a "cannot upload" toast appearing.*/-import type { CKEditorError, CKTextEditor, FileUploadData } from "@triliumnext/ckeditor5";+import type {+ CKEditorError, CKTextEditor, FileUploadData, LinkAtSelection+} from "@triliumnext/ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";import type FAttachment from "../../../entities/fattachment";@@ -444,13 +446,14 @@ describe("parseLinkHref", () => {});describe("getAddLinkOpts", () => {- function createApi(currentLink: { href: string; text: string } | null) {+ function createApi(currentLink: LinkAtSelection | null) {return {hasSelection: vi.fn(() => true),getSelectedText: vi.fn(() => "chosen words"),getCurrentLink: vi.fn(() => currentLink),addLink: vi.fn(),updateLink: vi.fn(),+ addLinkPreview: vi.fn(),addLinkToEditor: vi.fn(),addHtmlToEditor: vi.fn(),addContentEmbed: vi.fn(),@@ -460,16 +463,30 @@ describe("getAddLinkOpts", () => {const ready = async () => {};it("edits the link at the caret, rewriting it on save", async () => {- const api = createApi({ href: "#root/abc?bookmark=part", text: "See there" });+ const api = createApi({+ href: "#root/abc?bookmark=part", text: "See there", display: "plain"+ });const opts = getAddLinkOpts(api, ready);expect(opts).toMatchObject({text: "See there", hasSelection: false, currentTitle: "See there",- currentLink: { notePath: "root/abc" }, currentBookmark: "part"+ currentLink: { notePath: "root/abc" }, currentBookmark: "part", display: "plain"});await opts.addLink("root/def", "Elsewhere");expect(api.updateLink).toHaveBeenCalledExactlyOnceWith("root/def", "Elsewhere", undefined);expect(api.addLink).not.toHaveBeenCalled();++ await opts.addLinkPreview?.("https://example.com", "card", "Example");+ expect(api.addLinkPreview)+ .toHaveBeenCalledExactlyOnceWith("https://example.com", "card", "Example");+ });++ 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", display: "card" });+ expect(getAddLinkOpts(api, ready, { display: "inline" })).toMatchObject({+ currentLink: { externalLink: "https://example.com" }, currentTitle: "Example",+ display: "card"+ });});it("adds a link from the selection outside one", async () => {@@ -481,10 +498,17 @@ describe("getAddLinkOpts", () => {await opts.addLink("https://example.com", "Example", true);expect(api.addLink).toHaveBeenCalledExactlyOnceWith("https://example.com", "Example", true);expect(api.updateLink).not.toHaveBeenCalled();++ await opts.addLinkPreview?.("https://example.com", "inline", null);+ expect(api.addLinkPreview)+ .toHaveBeenCalledExactlyOnceWith("https://example.com", "inline", null);});- it("opens a new link on the side it is asked for", () => {- expect(getAddLinkOpts(createApi(null), ready, "url").target).toBe("url");- expect(getAddLinkOpts(createApi(null), ready).target).toBeUndefined();+ it("opens a new link on the side and with the display it is asked for", () => {+ const opts = getAddLinkOpts(createApi(null), ready, { target: "url", display: "embed" });+ expect(opts).toMatchObject({ target: "url", display: "embed" });+ expect(getAddLinkOpts(createApi(null), ready)).toMatchObject({+ target: undefined, display: undefined+ });});});diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex a70d4f3d20..e940d35297 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -259,7 +259,7 @@ export default function EditableText({function showLinkDialog(request: LinkDialogRequest) {if (!editorApiRef.current) return null;- const opts = getAddLinkOpts(editorApiRef.current, waitForEditor, request.target);+ const opts = getAddLinkOpts(editorApiRef.current, waitForEditor, request);if (isMobile()) {parentComponent?.triggerCommand("showAddLinkDialog", opts);return null;@@ -586,23 +586,31 @@ export default function EditableText({* now. An empty editor still holds a block, whose id keeps the place of the blocks in the note.*//**- * What the Add link dialog opens on: the link around the caret, which saving rewrites, or a new- * link at the selection, on the `target` side.+ * What the Add link dialog opens on: the link around the caret or the selected link preview, which+ * saving rewrites, or a new link at the selection, on the `target` side and shown as `display`.*/export function getAddLinkOpts(- api: CKEditorApi, ready: () => Promise<unknown>, target?: AddLinkOpts["target"]+ api: CKEditorApi, ready: () => Promise<unknown>,+ { target, display }: Pick<AddLinkOpts, "target" | "display"> = {}): AddLinkOpts {+ async function addLinkPreview(...args: Parameters<CKEditorApi["addLinkPreview"]>) {+ await ready();+ api.addLinkPreview(...args);+ }+const currentLink = api.getCurrentLink();if (currentLink) {return {text: currentLink.text,hasSelection: false,currentTitle: currentLink.text,+ display: currentLink.display,...parseLinkHref(currentLink.href),async addLink(notePath, linkTitle, externalLink) {await ready();await api.updateLink(notePath, linkTitle, externalLink);- }+ },+ addLinkPreview};}@@ -610,10 +618,12 @@ export function getAddLinkOpts(text: api.getSelectedText(),hasSelection: api.hasSelection(),target,+ display,async addLink(notePath, linkTitle, externalLink) {await ready();api.addLink(notePath, linkTitle, externalLink);- }+ },+ addLinkPreview};}diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts b/apps/client/src/widgets/type_widgets/text/toolbar.spec.tsindex e1d403d850..94e6a6f3a5 100644--- a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts@@ -241,7 +241,7 @@ describe("buildMobileToolbar", () => {"|","math", "drawingCanvas", "mermaid","|",- "bookmark", "linkEmbed", "childNote", "contentEmbed",+ "bookmark", "childNote", "contentEmbed","|","specialCharacters", "emoji", "insertIcon","|",diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.tsindex c61e7485d5..f2294cb40c 100644--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts@@ -77,7 +77,7 @@ export function buildMobileToolbar(aiAssistant: boolean) {"|","math", "drawingCanvas", "mermaid","|",- "bookmark", "linkEmbed", "childNote", "contentEmbed",+ "bookmark", "childNote", "contentEmbed","|","specialCharacters", "emoji", "insertIcon","|",@@ -179,8 +179,7 @@ export function buildClassicToolbar(multilineToolbar: boolean, aiAssistant: bool{...buildInsertGroup(),items: [- "link", "linkEmbed", "bookmark", "internallink",- "childNote", "contentEmbed",+ "link", "bookmark", "internallink", "childNote", "contentEmbed","|","collapsible", "tabs", "multicolumnLayout", ...getExtendedCodeBlockItems(),"math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak",@@ -258,7 +257,7 @@ export function buildFloatingToolbar(aiAssistant: boolean) {{...buildInsertGroup(),items: [- "link", "linkEmbed", "bookmark", "internallink", "childNote", "contentEmbed",+ "link", "bookmark", "internallink", "childNote", "contentEmbed","|","collapsible", "tabs", "multicolumnLayout", ...getExtendedCodeBlockItems(),"math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "dateTime"diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex 55c697d2b0..62025a2d9a 100644--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@ -138,9 +138,9 @@"_help_CohkqWQC1iBv": "<p>Press the <span class=\"tn-icon cke cke-plus\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> to reveal special inserable items and blocks such as symbols, Math expressions and separators.</p><h2>Bookmarks</h2><p>See the dedicated <a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a> section.</p><h2>New child note</h2><p>Choose <span class=\"tn-icon bx bx-subdirectory-right\"></span> <em>New child note</em> to create an empty child note of the current note and insert a link to it at the cursor. The new note opens in <a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a> with its title selected, so typing names it, and the link shows the new title. While the note is still empty, Quick edit offers the note types to turn it into.</p><p>The same action is available as <em>Create a new child note</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. A child note of a protected note is protected too.</p><h2>Emoji</h2><figure class=\"image image-style-align-right image_resized\" style=\"width:42.4%;\"><img style=\"aspect-ratio:366/410;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_plus.png\" width=\"366\" height=\"410\"></figure><p>This feature allows inserting Unicode emoji characters. Simply select a category and a desired emoji to insert it.</p><p>Emojis can also be searched by their English name and the skin tone can be selected via a combo box to the right.</p><p>There is also the possibility of inserting emojis directly by typing <code>:</code> followed by a name of an emoji, triggering the display of a list of emojis. Simply use the arrow keys to select one and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to insert it.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_plus.png\" width=\"272\" height=\"187\"><h2>Symbols</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:346/322;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_image.png\" width=\"346\" height=\"322\"></figure><p>Pressing the <span class=\"tn-icon cke cke-special-characters\"></span> button will reveal a popup window displaying a list of characters that are generally more difficult to insert directly from the keyboard, such as a subset of emojis, quotation characters, etc.</p><p>Interaction:</p><ul><li>Click on a character to insert it at the current cursor position.</li><li>The window can be dragged around by the top bar where the title is, to avoid it getting in the way of the text.</li><li>Click on the <em>Category</em> selector to filter the characters.</li></ul><h2>Multicolumn layout</h2><p>See the dedicated <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a> page.</p><h2>Extended code block</h2><p>Choose <span class=\"tn-icon bx bx-code-block\"></span> <em>Extended code block</em> to insert a code block that is edited as a code note. This entry is experimental and is shown only once it is turned on. See <em>Extended code blocks</em> in <a class=\"reference-link\" href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a>.</p><h2>Math equations</h2><p>See the dedicated <a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a> page.</p><h2>Drawing canvas</h2><p>Choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em> to draw on an Excalidraw canvas inside the text. See <em>Drawing canvases</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><h2>Mermaid diagram</h2><p>Press the <span class=\"tn-icon cke cke-trilium-mermaid-insert\"></span> button to create an inline Mermaid diagram. The arrow next to it lists a template for each kind of diagram. The diagram is also available as <em>Mermaid diagram</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</p><p>This feature is quite similar to the <a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a> note types and is meant as an alternative to it for simple diagrams. For more complex diagrams, use the <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a> feature for a dedicated Mermaid note.</p><figure class=\"image\"><img style=\"aspect-ratio:1174/358;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Insert%20buttons_image.png\" width=\"1174\" height=\"358\"></figure><p>A diagram shows in a box like the one of an included note, so it can be resized, given another box size (<em>Small</em>, <em>Medium</em> or <em>Full</em>) from its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu or shown in fullscreen, as described in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><ul><li>The <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of the diagram's toolbar decides whether its source can be changed. While it is off, the source still shows, but read-only.</li><li>The buttons next to it choose what the diagram shows, as for a Mermaid note: <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em> for the Mermaid source alone, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> for the source with the diagram next to it, and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em> for the diagram alone. Its <em>More actions</em> menu offers the same choice.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of its <em>More actions</em> menu change how the source shows, each with <em>Auto</em>, <em>On</em> and <em>Off</em>, as for an included code note (see <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>).</li><li>A new diagram starts editable, in <em>Split view</em>. The diagram updates a moment after you stop typing. If the source has an error, the error shows over the last diagram that worked, which stays dimmed, as in a Mermaid note. On desktop, drag the divider between the source and the diagram to resize them.</li><li>A diagram without a chosen view shows the source next to the diagram while it is editable, and the diagram alone otherwise. In a read-only note, the source can never be changed. A read-only note and the AI chat show a diagram in the same box, in the view it was saved with, and with the zoom buttons over the diagram instead of in a toolbar. A <em>Medium</em> or <em>Full</em> diagram also has a <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button there, or over the source in the <em>Source</em> view.</li><li>To zoom, use the <span class=\"tn-icon bx bx-zoom-out\"></span> and <span class=\"tn-icon bx bx-zoom-in\"></span> buttons of the diagram's toolbar; the zoom level between them resets the zoom. In fullscreen, where the toolbar is hidden, the same buttons show over the diagram. Drag the diagram to move around it, and double-click it to reset the view. The mouse wheel scrolls the note until you click the diagram, and then zooms it.</li><li>While the source shows, the <span class=\"tn-icon bx bx-help-circle\"></span> <em>Mermaid syntax help</em> button at the end of the toolbar opens the help on <a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>, which links to the Mermaid syntax.</li><li>The changes made to the source of a diagram are part of the undo history of the text note, in the order they were made. <kbd>Ctrl</kbd>+<kbd>Z</kbd> and <kbd>Ctrl</kbd>+<kbd>Y</kbd> undo and redo them from the source as well as from the text, as described in <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</li></ul><p>The source of the diagram stays in the note as a Mermaid code block, so the diagram is exported to Markdown as a <code>mermaid</code> code block that other applications can show.</p><p>Diagrams created in earlier versions keep the view they were saved with, and open editable.</p><h2>Horizontal ruler</h2><p>This feature will display a horizontal line, generally useful to separate different sections of the text. To do so, press the <span class=\"tn-icon cke cke-horizontal-line\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_image.png\" width=\"502\" height=\"95\"><p>Alternatively, it's possible to insert a horizontal ruler by typing <code>---</code>.</p><h2>Page break</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:371/79;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Insert%20buttons_image.png\" width=\"371\" height=\"79\"></figure><p>Page breaks provide a way to force the next paragraph or block (table, image, etc.) to be displayed onto the next page when printing (either to a real printer to <a href=\"#root/_help_NRnIZmSMc5sj\">when exporting to PDF</a>).</p><p>Page breaks are marked in the editor with the words <em>Page break</em>, but they will not actually be shown when printed.</p><ul><li>To insert a page break, press the <span class=\"tn-icon cke cke-page-break\"></span> in the formatting toolbar.</li><li>To insert many page breaks at once, insert a page break first, click on it and press <kbd>Ctrl</kbd>+<kbd>C</kbd>. Then use <kbd>Ctrl</kbd>+<kbd>V</kbd>, to paste as many times as needed.</li></ul><h2>Date and time</h2><p>The <span class=\"tn-icon cke cke-trilium-date-time\"></span> button inserts the current date and time at the cursor, replacing the selected text if there is any. The inserted text takes the formatting of the text around it, so a date inserted inside bold text is bold too.</p><ul><li>To insert the date in the default format, press the button itself or press <kbd>Alt</kbd>+<kbd>T</kbd>.</li><li>To insert it in another format, press the arrow next to the button and pick a format from the list. Each entry shows the current date and time in that format: the default one, the date or the time alone, the date written out, and ISO 8601.</li><li>The same formats are offered by the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>: type <code>/date</code>, <code>/time</code>, <code>/now</code> or <code>/today</code>. The <em>Insert date/time</em> entry uses the default format, and shows what it inserts underneath; the other entries show their output in the title.</li></ul><p>The default format can be changed in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em>, using <a href=\"https://day.js.org/docs/en/display/format\">Day.js format tokens</a> (for example <code>DD.MM.YYYY HH:mm</code>).</p><h2>Icons</h2><p>Icons just like the ones for the <a href=\"#root/_help_p9kXRFAkwN4o\">note icon</a> can be inserted in text. For more information see <a class=\"reference-link\" href=\"#root/_help_hD8GawVuazff\">Icons</a>.</p>","_help_hD8GawVuazff": "<p>Icons just like the <a href=\"#root/_help_hD8GawVuazff\">note icons</a> can be inserted in the content of a note, including from any other <a href=\"#root/_help_gOKqSJgXLcIj\">custom icon packs</a>.</p><h2>Features</h2><ul><li>The icon can be formatted through the<a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a> tools of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:<ul><li>Foreground/icon color</li><li>Background color/highlight</li><li>Font size</li></ul></li><li>Custom <a class=\"reference-link\" href=\"#root/_help_gOKqSJgXLcIj\">Icon Packs</a> are also supported.<ul><li>For emojis, prefer the Emoji functionality from <a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</li></ul></li><li>When an icon is clicked a floating toolbar appears with the following functions:<ul><li><span class=\"tn-icon bx bx-sticker\"></span> which changes the icon.</li><li><span class=\"tn-icon bx bx-reflect-horizontal\"></span> which applies transforms: rotate (90 / 180 / 270) and flip horizontal/vertical. Only one transform can be used per icon.</li></ul></li></ul><h2>Usage</h2><ul><li>The in-app help/user guide makes use of these icons in order to illustrate buttons in the UI.</li><li>The <a class=\"reference-link\" href=\"#root/_help_GnhlmrATVqcH\">Microsoft OneNote</a> importer also makes use of them for the <a class=\"reference-link\" href=\"#root/_help_LpvyEIBIAAj7\">Tags</a>.</li></ul><h2>Inserting an icon</h2><p>There are two ways to insert an icon:</p><ul><li>Via the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> look for the <span class=\"tn-icon bx bx-plus\"></span> icon and then the <span class=\"tn-icon bx bx-sticker\"></span> icon.</li><li>Via <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>, type <code>/icon</code>.</li></ul><p>An icon picker will appear, search for an icon and click it to insert it in the document.</p><h2>Finding notes by their icons</h2><p>An icon can be <a href=\"#root/_help_eIg8jdvaoNNd\">searched</a>. A note containing a <span class=\"tn-icon bx bx-star\"></span> icon can be found by searching for <code>star</code>, or its <code>iconClass</code> (<code>bx-star</code>).</p><p>To find the name of the icon, hover the mouse over an icon while in the icon picker.</p><h2>Markdown rendering</h2><p>When exporting to <a class=\"reference-link\" href=\"#root/_help_Oau6X9rCuegd\">Markdown</a>, the item will render as raw HTML representation of the icon as is used by Trilium:</p><pre><code class=\"language-text-html\"><span class=\"tn-icon bx bx-star\"></span></code></pre>","_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 <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, <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><br></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 <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 <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <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 <a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a> 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><title></code> and <code><meta name=\"description\"></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 <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 <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_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 <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 <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <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.</li><li>Optionally, type a <em>Link title</em> to show instead of the page's own title.</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 <a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a> 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) and how it is displayed. A new address shows the title of the new page, unless you type one.</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><title></code> and <code><meta name=\"description\"></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 <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 <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> for links to other notes within Trilium.<ul><li>The list of notes that refer to a particular note is called <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 <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>:<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 <span class=\"tn-icon cke cke-trilium\"></span> button and <kbd>Ctrl</kbd>+<kbd>L</kbd> of <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 <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 <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_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 <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>:<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 <span class=\"tn-icon cke cke-trilium\"></span> button and <kbd>Ctrl</kbd>+<kbd>L</kbd> of <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 <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 <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 <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=\"#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 <a class=\"reference-link\" href=\"#root/_help_S0Fos78ZfcY7\">Note Inbox</a> (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 <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 <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> 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 <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> 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 <a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a> 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: <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>, <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>, <a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a> and <a class=\"reference-link\" href=\"#root/_help_GBBMSlVSOIGP\">AI</a> chats. A link written inside a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> 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 <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> notes and for <a class=\"reference-link\" href=\"#root/_help_GBBMSlVSOIGP\">AI</a> 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 <a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a> 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 <a class=\"reference-link\" href=\"#root/_help_KRlZFoIH0j6p\">Connections tab</a> of the <a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>, as a dedicated section.</li><li>As a badge in the <a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a> 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 <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 <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> Bulleted lists (also known as unordered lists).</li><li><span class=\"tn-icon cke cke-numbered-list\"></span> Numbered lists (or ordered lists).</li><li><span class=\"tn-icon cke cke-todo-list\"></span> 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 <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 <span class=\"tn-icon cke cke-indent\"></span> button (see <em>Indentation</em> in <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 <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 <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 <a class=\"reference-link\" href=\"#root/_help_mHbBMPDPkVV5\">Import & 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>",diff --git a/docs/User Guide/User Guide/Note Types/Text/Link Previews.md b/docs/User Guide/User Guide/Note Types/Text/Link Previews.mdindex 50803c3eec..836ffa3764 100644--- a/docs/User Guide/User Guide/Note Types/Text/Link Previews.md+++ b/docs/User Guide/User Guide/Note Types/Text/Link Previews.md@@ -49,11 +49,18 @@ If the link is not accessible to the Trilium server (or the network request fail> [!NOTE]> A URL is only auto-converted when the pasted text _is_ the URL. Links with a display name (e.g. [Trilium Notes website](https://triliumnotes.org)) are left as plain links.-### 2\. By using the "Link preview" toolbar button or slash command+### 2\. From the link dialog-Click _Link preview_ (<span class="tn-icon cke cke-trilium-link-preview"></span>) in the formatting toolbar to open the _Link preview_ popup. Paste the URL and choose the type of preview.+Since v0.107.0, a link preview is created from the same _Add link_ dialog as any other link (see <a class="reference-link" href="Links/External%20links.md">External links</a>):-Alternatively, use <a class="reference-link" href="Slash%20Commands.md">Slash Commands</a> and look for _link preview_ (it is also found by _embed_, _url_ or _video_), which opens the same popup at the cursor.+* 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>, to open the dialog on _Web link_.+* Type or paste the address, then pick the preview in _Display as_: _Inline_, _Card_ or, for a YouTube video, _YouTube embed_. _Plain link_ inserts an ordinary link.+* Optionally, type a _Link title_ to show instead of the page's own title.+* Press <kbd>Enter</kbd> or _Add link_ to confirm. The link appears right away and turns into the preview once Trilium has read the page.++Alternatively, use <a class="reference-link" href="Slash%20Commands.md">Slash Commands</a> and look for _link preview_ (it is also found by _embed_, _url_ or _video_). It opens the same dialog with a preview already picked: a _YouTube embed_ for a YouTube video, a _Card_ for any other page.++To turn an existing link into a preview, open its _Edit link_ dialog and change _Display as_. A link whose text differs from its address keeps that text as the title of the preview.### 3\. By saving browser tabs from the Web Clipper@@ -66,7 +73,7 @@ When _Autogenerate link previews_ is turned off, the tabs are saved as a list ofClick on an inserted link preview to select it, and a small toolbar will appear with the following options:* The normal link operations (opening in a new tab, copying the link, unlinking).-* A button to edit the title of the link preview. This is especially useful if the title is hidden behind a login screen.+* The <span class="tn-icon cke cke-pencil"></span> _Edit link_ button, which opens the _Edit link_ dialog on the link preview, as does pressing <kbd>Ctrl</kbd>+<kbd>K</kbd> while it is selected. The dialog changes its address, its _Link title_ (especially useful if the title is hidden behind a login screen) and how it is displayed. A new address shows the title of the new page, unless you type one.* A way to switch between the link preview modes (Inline, Card or Embed) as well as to convert it to a normal link instead.* The Embed option is only enabled when the URL points to a supported service (YouTube today).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.mdindex 24062cbd0a..63a851c91e 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@@ -5,6 +5,7 @@ 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_, 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.+ * _Display as_ inserts the address as a _Plain link_, or as one of the <a class="reference-link" href="../Link%20Previews.md">Link Previews</a>: _Inline_, _Card_ or, for a YouTube video, _YouTube embed_.* 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/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 56518bdc21..503a97a9f7 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -5,7 +5,6 @@ import "ckeditor5/ckeditor5.css";import "./theme/blockquote.css";import "./theme/content_colors.css";import "./theme/code_block_toolbar.css";-import "./theme/link_embed_form.css";import type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";import type { ImageEditingSourceConfig } from "./plugins/image_editing_source.js";import type { PasteTarget } from "./plugins/cuttonote.js";@@ -31,7 +30,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 { LinkAtSelection, 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";@@ -39,7 +38,7 @@ export type { ToolbarGroupMenuEntry, ToolbarGroupMenuHost, ToolbarGroupMenuItem,export type { default as TextFormattingToolbar } from "./plugins/text_formatting_toolbar.js";export type { default as ContextToolbar } from "./plugins/context_toolbar.js";export type { default as MobileToolbarItems } from "./plugins/mobile_toolbar_items.js";-export type { LinkEmbedHost } from "./plugins/link_embed/link_embed_commands.js";+export type { LinkDisplayMode, LinkEmbedHost } from "./plugins/link_embed/link_embed_commands.js";export type { AttachmentUploadHost } from "./plugins/uploadimage.js";export type { IconPickerRequest } from "./plugins/inline_icon/inline_icon_ui.js";export type { BlockReferenceHost } from "./plugins/block_reference/block_reference.js";diff --git a/packages/ckeditor5/src/plugins/internallink.spec.ts b/packages/ckeditor5/src/plugins/internallink.spec.tsindex 6b22bd3f14..800a1f4b73 100644--- a/packages/ckeditor5/src/plugins/internallink.spec.ts+++ b/packages/ckeditor5/src/plugins/internallink.spec.ts@@ -9,6 +9,7 @@ import { createTestEditor } from "../../test/editor-kit.js";import InternalLinkPlugin, {COMMAND_NAME, getLinkAtSelection, type LinkDialogRequest, replaceLinkAtSelection} from "./internallink.js";+import LinkEmbedEditing from "./link_embed/link_embed_editing.js";describe("InternalLinkPlugin", () => {let editor: ClassicEditor;@@ -123,9 +124,10 @@ describe("the link at the selection", () => {beforeEach(async () => {getTitle = vi.fn(async () => "Target");- editor = await createTestEditor([Essentials, Paragraph, Bold, LinkEditing, InternalLinkPlugin], {- referenceLink: { getTitle, getTitleSync: () => "Target" }- });+ editor = await createTestEditor(+ [Essentials, Paragraph, Bold, LinkEditing, LinkEmbedEditing, InternalLinkPlugin],+ { referenceLink: { getTitle, getTitleSync: () => "Target" } }+ );});const LINKED = "<paragraph>a <$text bold=\"true\" linkHref=\"https://a.example\">fo[]o</$text> b"@@ -133,7 +135,8 @@ describe("the link at the selection", () => {it("reads the address and whole text of the link around the caret, and none outside", () => {setModelData(editor.model, LINKED);- expect(getLinkAtSelection(editor)).toStrictEqual({ href: "https://a.example", text: "foo" });+ expect(getLinkAtSelection(editor))+ .toStrictEqual({ href: "https://a.example", text: "foo", display: "plain" });setModelData(editor.model,"<paragraph>a[] <$text linkHref=\"https://a.example\">foo</$text></paragraph>");@@ -149,7 +152,35 @@ describe("the link at the selection", () => {setModelData(editor.model, "<paragraph><$text linkHref=\"https://a.example\">a[]b</$text>"+ "<reference href=\"#root/abc\" linkHref=\"https://a.example\"></reference>"+ "<$text linkHref=\"https://a.example\">c</$text></paragraph>");- expect(getLinkAtSelection(editor)).toStrictEqual({ href: "https://a.example", text: "abc" });+ expect(getLinkAtSelection(editor))+ .toStrictEqual({ href: "https://a.example", text: "abc", display: "plain" });+ });++ 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\"></linkMention>]</paragraph>");+ expect(getLinkAtSelection(editor))+ .toStrictEqual({ href: "https://a.example", text: "A", display: "inline" });++ setModelData(editor.model,+ "[<linkEmbed url=\"https://a.example\" embedType=\"opengraph\"></linkEmbed>]");+ expect(getLinkAtSelection(editor))+ .toStrictEqual({ href: "https://a.example", text: "", display: "card" });+ });++ it("replaces a selected link preview, in a paragraph of its own for a block one", async () => {+ const data = () => getModelData(editor.model, { withoutSelection: true });+ setModelData(editor.model, "[<linkEmbed url=\"https://a.example\" embedType=\"opengraph\""+ + " title=\"A\"></linkEmbed>]");+ await replaceLinkAtSelection(editor, "https://b.example", "B");+ expect(data())+ .toBe("<paragraph><$text linkHref=\"https://b.example\">B</$text></paragraph>");++ setModelData(editor.model, "<paragraph>a [<linkMention url=\"https://a.example\""+ + " title=\"A\"></linkMention>] b</paragraph>");+ await replaceLinkAtSelection(editor, "#root/abc", null);+ expect(data()).toContain("<paragraph>a <reference href=\"#root/abc\"");+ expect(data()).not.toContain("linkMention");});it("replaces the address and the text of the whole link, keeping its formatting", () => {diff --git a/packages/ckeditor5/src/plugins/internallink.ts b/packages/ckeditor5/src/plugins/internallink.tsindex 361b8c2f20..9bfa94abfe 100644--- a/packages/ckeditor5/src/plugins/internallink.ts+++ b/packages/ckeditor5/src/plugins/internallink.ts@@ -5,6 +5,9 @@ import {import type { Editor, LinkCommand, ModelRange, View } from 'ckeditor5';import HostedBalloon from '../hosted_balloon.js';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';export const COMMAND_NAME = 'insertInternalLink';@@ -15,6 +18,11 @@ const LINK_KEYSTROKE = 'Ctrl+K';export interface InternalLinkDialogOptions {/** The side the dialog opens on for a new link: a note, or a web address. */target?: 'note' | 'url';+ /**+ * How a new web link is displayed. `embed` falls back to a card for an address without a+ * player.+ */+ display?: LinkDisplayMode;}/** The request that the editor passes to the host's link dialog. */@@ -168,8 +176,25 @@ class InsertInternalLinkCommand extends Command {}}-/** The address and the whole text of the link around the selection, or `null` outside one. */-export function getLinkAtSelection(editor: Editor): { href: string; text: string } | null {+/** A link in the text, 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. */+ text: string;+ display: LinkDisplayMode;+}++/** The link around the selection or the selected link preview, or `null` outside one. */+export function getLinkAtSelection(editor: Editor): LinkAtSelection | null {+ const preview = getSelectedLinkWidget(editor);+ if (preview) {+ return {+ href: preview.getAttribute('url') as string,+ text: (preview.getAttribute('title') as string | undefined) ?? '',+ display: getLinkWidgetMode(preview)+ };+ }+const found = findLinkAtSelection(editor);if (!found) {return null;@@ -181,12 +206,13 @@ export function getLinkAtSelection(editor: Editor): { href: string; text: stringtext += item.data;}}- return { href: found.href, text };+ return { href: found.href, text, display: 'plain' };}/**- * Replaces the link around the selection with `text` linking to `href`, keeping the formatting of- * its 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 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.*/@@ -213,9 +239,8 @@ export async function replaceLinkAtSelection(editor: Editor, href: string, text:model.change((writer) => {const attributes = referenceAttributes(href, title);const reference = writer.createElement('reference', attributes);- const start = range.start;- writer.remove(range);- writer.insert(reference, start);+ // `insertContent()` puts a paragraph around it in place of a block preview.+ model.insertContent(reference, range);if (!selectionMoved) {writer.setSelection(reference, 'after');}@@ -229,17 +254,21 @@ export async function replaceLinkAtSelection(editor: Editor, href: string, text:model.change((writer) => {// A link ends where its attribute does, so its range starts at the boundary of a node.- const start = found.range.start;- const attributes = new Map(start.nodeAfter?.getAttributes());- writer.remove(found.range);+ const first = found.range.start.nodeAfter;+ const attributes = new Map(first?.is('$text') ? first.getAttributes() : []);attributes.set('linkHref', href);- writer.insertText(text, attributes, start);- writer.setSelection(start.getShiftedBy(text.length));+ const inserted = model.insertContent(writer.createText(text, attributes), found.range);+ writer.setSelection(inserted.end);});}function findLinkAtSelection(editor: Editor): { href: string; range: ModelRange } | null {const model = editor.model;+ const preview = getSelectedLinkWidget(editor);+ if (preview) {+ return { href: preview.getAttribute('url') as string, range: model.createRangeOn(preview) };+ }+const selection = model.document.selection;const href = selection.getAttribute('linkHref');const position = selection.getFirstPosition();diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.tsindex 6959ae5725..1e7f4bc27e 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed.spec.ts@@ -12,12 +12,12 @@ describe("LinkEmbed", () => {editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, { linkEmbed: createLinkEmbedHost() });});- it("loads the plugin, registers the commands and the toolbar button", () => {+ it("loads the plugin and registers the commands, with no toolbar button of its own", () => {expect(editor.plugins.get(LinkEmbed)).toBeInstanceOf(LinkEmbed);expect(editor.commands.get(LINK_EMBED_COMMAND)).toBeDefined();expect(editor.commands.get(CHANGE_LINK_DISPLAY_COMMAND)).toBeDefined();expect(editor.commands.get(REMOVE_LINK_EMBED_COMMAND)).toBeDefined();- expect(editor.ui.componentFactory.has("linkEmbed")).toBe(true);+ expect(editor.ui.componentFactory.has("linkEmbed")).toBe(false);});it("shows previews as their title or URL, and inserts unresolved cards, without linkEmbed", async () => {diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed.tsindex 48d651ee40..24690eb0df 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed.ts@@ -1,11 +1,9 @@import { Plugin } from 'ckeditor5';import AutoLinkToMention from './link_embed_autodetect.js';import LinkEmbedEditing from './link_embed_editing.js';-import LinkEmbedUI from './link_embed_ui.js';export {CHANGE_LINK_DISPLAY_COMMAND,- CHANGE_LINK_PREVIEW_TITLE_COMMAND,getLinkDisplayModeLabel,LINK_DISPLAY_MODES,LINK_EMBED_COMMAND,@@ -20,13 +18,14 @@ export {** The feature is assembled from:* - {@link LinkEmbedEditing} — schema, converters and the commands ({@link module:link_embed_commands});- * - {@link LinkEmbedUI} — the toolbar button and its balloon form;* - {@link AutoLinkToMention} — auto-conversion of typed/pasted URLs;* - LinkEmbedToolbar (loaded separately by the host) — the widget toolbar, whose Display dropdown* also serves the native link balloon.+ *+ * The host's link dialog inserts previews through `LINK_EMBED_COMMAND`.*/export default class LinkEmbed extends Plugin {static get requires() {- return [LinkEmbedEditing, LinkEmbedUI, AutoLinkToMention];+ return [LinkEmbedEditing, AutoLinkToMention];}}diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.tsindex 0e40f88e34..b17b629586 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts@@ -76,7 +76,7 @@ export default class AutoLinkToMention extends Plugin {* URL rather than once at startup, so the host can supply a getter and have the option apply to* already-open editors. A plain boolean is honoured too, and an absent config means enabled.*- * Only auto-detection is gated: inserting a preview from the toolbar dialog goes through+ * Only auto-detection is gated: inserting a preview from the link dialog goes through* InsertLinkEmbedCommand and stays available either way.*/private _autoDetectEnabled(): boolean {diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.tsindex 2a6036e4a5..b7ec5d0ff2 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.spec.ts@@ -8,9 +8,12 @@ import {findElement,LINK_EMBED_TEST_PLUGINS,META,- type LinkEmbedHostMocks+ type LinkEmbedHostMocks,+ useDeferredFetch} from "../../../test/link-embed-kit.js";-import { CHANGE_LINK_DISPLAY_COMMAND, CHANGE_LINK_PREVIEW_TITLE_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND } from "./link_embed_commands.js";+import {+ CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND+} from "./link_embed_commands.js";describe("LinkEmbed commands", () => {let editor: ClassicEditor;@@ -66,6 +69,77 @@ describe("LinkEmbed commands", () => {expect(findElement(editor, "linkMention")).toBeUndefined();expect(findElement(editor, "linkEmbed")).toBeUndefined();expect(editor.getData()).toBe(`<p><a href="${url}">${url}</a></p>`);++ setModelData(editor.model, "<paragraph>[]</paragraph>");+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "plain", title: "The article" });+ expect(editor.getData()).toBe(`<p><a href="${url}">The article</a></p>`);+ });++ it("shows the link at once, then the preview titled as asked once fetched", async () => {+ const url = "https://example.com/article";+ const { resolveFetch } = useDeferredFetch(fetchMetadata);+ setModelData(editor.model, "<paragraph>see []</paragraph>");++ const executed = editor.execute(LINK_EMBED_COMMAND, {+ url, mode: "inline", title: "My title"+ }) as unknown as Promise<void>;+ expect(editor.getData()).toBe(`<p>see <a href="${url}">My title</a></p>`);+ resolveFetch({ ...META, url });+ await executed;++ const mention = findElement(editor, "linkMention");+ expect(mention?.getAttribute("title")).toBe("My title");+ expect(mention?.getAttribute("description")).toBe(META.description);+ expect(editor.model.document.selection.getSelectedElement()).toBe(mention);+ });++ it("replaces the link the selection is in, which is the link being edited", async () => {+ const url = "https://example.com/new";+ setModelData(editor.model, '<paragraph>see '+ + '<$text linkHref="https://example.com/old">the []old one</$text> here</paragraph>');++ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "card" });++ const embed = findElement(editor, "linkEmbed");+ expect(embed?.getAttribute("url")).toBe(url);+ expect(embed?.getAttribute("title")).toBe(META.title);+ expect(editor.getData()).not.toContain("example.com/old");+ expect(editor.getData()).not.toContain("old one");+ });++ it("reshapes and retitles a selected preview of the same address unfetched", async () => {+ const url = "https://example.com/article";+ setModelData(editor.model, `<paragraph>[<linkMention url="${url}" embedType="opengraph"`+ + ` title="Page" description="About"></linkMention>]</paragraph>`);++ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "card", title: "Mine" });++ const card = findElement(editor, "linkEmbed");+ expect(fetchMetadata).not.toHaveBeenCalled();+ expect(findElement(editor, "linkMention")).toBeUndefined();+ expect(card?.getAttribute("embedType")).toBe("opengraph");+ expect(card?.getAttribute("title")).toBe("Mine");+ expect(card?.getAttribute("description")).toBe("About");+ expect(editor.model.document.selection.getSelectedElement()).toBe(card);++ // Without a title, the stored one stays.+ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "inline" });+ expect(findElement(editor, "linkMention")?.getAttribute("title")).toBe("Mine");+ });++ it("replaces a selected preview of another address, or turned into a plain link", async () => {+ const url = "https://example.com/new";+ setModelData(editor.model, '[<linkEmbed url="https://example.com/old" embedType="opengraph"'+ + ' title="Old"></linkEmbed>]');++ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "inline" });++ expect(fetchMetadata).toHaveBeenCalledExactlyOnceWith(url);+ expect(findElement(editor, "linkEmbed")).toBeUndefined();+ expect(findElement(editor, "linkMention")?.getAttribute("url")).toBe(url);++ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "plain", title: "New" });+ expect(editor.getData()).toBe(`<p><a href="${url}">New</a></p>`);});it("is enabled in a paragraph and disabled when read-only", () => {@@ -237,67 +311,6 @@ describe("LinkEmbed commands", () => {expect(editor.getData()).toBe(before);});- // ------------------------------------------------------------------------ // ChangeLinkPreviewTitleCommand (the widget toolbar's Edit title button)- // ------------------------------------------------------------------------- it("edits the displayed title, keeping every other attribute and the selection", () => {- setModelData(- editor.model,- '<paragraph>[<linkMention url="https://e.com/page" embedType="opengraph" title="Old | Site | Blog" favicon="F"></linkMention>]</paragraph>'- );- const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND);- expect(command?.isEnabled).toBe(true);- // The stored title is what the edit form prefills with.- expect(command?.value).toBe("Old | Site | Blog");-- editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: "My own words" });-- const mention = findElement(editor, "linkMention");- expect(mention?.getAttribute("title")).toBe("My own words");- expect(mention?.getAttribute("url")).toBe("https://e.com/page");- expect(mention?.getAttribute("favicon")).toBe("F");- // The widget stays selected, so its toolbar stays up after the edit.- expect(editor.model.document.selection.getSelectedElement()).toBe(mention);-- // A block card edits the same way — it is the same attribute.- setModelData(editor.model, '[<linkEmbed url="https://e.com/" embedType="opengraph" title="T"></linkEmbed>]');- editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: "Card title" });- expect(findElement(editor, "linkEmbed")?.getAttribute("title")).toBe("Card title");- });-- it("reports the renderers' hostname fallback when no title is stored, and the raw URL when it cannot parse", () => {- setModelData(editor.model, '[<linkEmbed url="https://e.com/page" embedType="opengraph"></linkEmbed>]');- expect(editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND)?.value).toBe("e.com");-- setModelData(editor.model, '[<linkEmbed url="not-a-url" embedType="opengraph"></linkEmbed>]');- expect(editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND)?.value).toBe("not-a-url");- });-- it("treats an unchanged or blank title as a no-op, and is disabled without a widget", () => {- setModelData(editor.model, '<paragraph>[<linkMention url="https://e.com/" title="T"></linkMention>]</paragraph>');- const original = findElement(editor, "linkMention");-- // Saving the prefilled value back, or a blank one, must not even replace the element.- editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: "T" });- expect(findElement(editor, "linkMention")).toBe(original);- editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: " " });- expect(findElement(editor, "linkMention")).toBe(original);-- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");- const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND);- expect(command?.isEnabled).toBe(false);- expect(command?.value).toBeNull();-- // Command swallows execute() while disabled, so force it enabled to exercise the early return.- const before = editor.getData();- if (command) {- command.isEnabled = true;- }- command?.execute({ title: "anything" });- expect(editor.getData()).toBe(before);- });-// -----------------------------------------------------------------------// ChangeLinkDisplayCommand on a native link (the link balloon's Display dropdown)// -----------------------------------------------------------------------diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.tsindex 46112e263a..5668b070be 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts@@ -1,10 +1,12 @@import { isHttpUrl } from '@triliumnext/commons';-import { Command, type Editor, findAttributeRange, ModelLiveRange } from 'ckeditor5';+import {+ Command, type Editor, findAttributeRange, type ModelElement, ModelLiveRange, type ModelRange,+ type ModelWriter+} from 'ckeditor5';export const LINK_EMBED_COMMAND = 'insertLinkEmbed';export const CHANGE_LINK_DISPLAY_COMMAND = 'changeLinkDisplay';export const REMOVE_LINK_EMBED_COMMAND = 'removeLinkEmbed';-export const CHANGE_LINK_PREVIEW_TITLE_COMMAND = 'changeLinkPreviewTitle';export const LINK_DISPLAY_MODES = ['inline',@@ -18,8 +20,7 @@ export const LINK_DISPLAY_MODES = [export type LinkDisplayMode = typeof LINK_DISPLAY_MODES[number];/**- * The user-facing name of a display mode, as shown by the insert form's dropdown and the widget- * toolbar's.+ * The user-facing name of a display mode, as shown by the widget toolbar's Display dropdown.** A switch rather than a table of labels, so that each one is written as a literal argument of a* `t()` call: that is how the messages this package owns are discovered (see `messages.ts`) and a@@ -56,40 +57,50 @@ export const META_KEYS = ['url', 'embedType', 'title', 'description', 'favicon',export type MetaKey = (typeof META_KEYS)[number];/**- * Inserts a preview for a URL: fetches its metadata through the host, then puts the widget in.+ * Puts a link to `url` at the selection, or in place of the link or the link preview the selection+ * is in, and turns it into a preview of the `mode` shape once the page's metadata arrives. `title`+ * replaces the page's own title, and is the text of a plain link.+ *+ * A selected preview of `url` changes its shape and title from the metadata it stores, without+ * fetching the page again.** All the metadata is written onto the element whichever shape is chosen — an inline mention stores* the description and image it does not itself show — so that switching modes later, via the widget* toolbar's Display dropdown, never has to go back to the network.*/export class InsertLinkEmbedCommand extends Command {- override async execute({ url, mode }: { url: string; mode: LinkDisplayMode }) {+ override async execute(+ { url, mode, title }: { url: string; mode: LinkDisplayMode; title?: string }+ ) {const editor = this.editor;-- // A plain link is not a preview at all, so no metadata is fetched: the URL becomes an- // ordinary link, exactly as the editor's own link balloon would have inserted it.- if (mode === 'plain') {- editor.model.change((writer) => {- editor.model.insertContent(writer.createText(url, { linkHref: url }));+ const model = editor.model;+ const selection = model.document.selection;+ const selected = getSelectedLinkWidget(editor);+ if (selected && mode !== 'plain' && selected.getAttribute('url') === url) {+ model.change((writer) => {+ writer.setSelection(rebuildLinkWidget(editor, writer, selected, mode, title), 'on');});return;}- const metadata = await getLinkEmbedHost(editor).fetchMetadata(url);-- editor.model.change((writer) => {- editor.model.insertContent(writer.createElement(mode === 'inline' ? 'linkMention' : 'linkEmbed', {- url: metadata.url,- // A card is an embed that declines to play: forcing "opengraph" is what tells the- // renderer to draw the static card rather than the provider's player.- embedType: mode === 'card' ? 'opengraph' : metadata.embedType,- title: metadata.title,- description: metadata.description,- favicon: metadata.favicon,- siteName: metadata.siteName,- image: metadata.image- }));+ const href = selection.getAttribute('linkHref');+ const position = selection.getFirstPosition();+ const target = typeof href === 'string' && position+ ? findAttributeRange(position, 'linkHref', href, model)+ : selection;++ // The plain link shows at once; the metadata fetch reads the page server-side and can take+ // seconds.+ const linkRange = model.change((writer) => {+ const link = writer.createText(title || url, { linkHref: url });+ const range = model.insertContent(link, target);+ writer.setSelection(range.end);+ return range;});++ if (mode !== 'plain') {+ await replaceLinkWithPreview(editor, linkRange, url, mode, title);+ }}override refresh() {@@ -126,17 +137,10 @@ export class ChangeLinkDisplayCommand extends Command {}const targetMode = options.value;- const currentMode = this._getMode(selected);+ const currentMode = getLinkWidgetMode(selected);if (targetMode === currentMode) return;- // Collect all metadata from the current element.- const attrs: Record<string, unknown> = {};- for (const key of META_KEYS) {- const val = selected.getAttribute(key);- if (val != null) attrs[key] = val;- }-- const url = attrs.url as string;+ const url = selected.getAttribute('url') as string;// "Plain link" leaves the preview system: the widget becomes an ordinary link whose text is// the URL. Inserted as new content (not an attribute change), so AutoLinkToMention does not@@ -150,19 +154,8 @@ export class ChangeLinkDisplayCommand extends Command {return;}- // Detect the actual embed type from the URL via the client service.- const detectedType = this._detectEmbedType(url);-model.change(writer => {- if (targetMode === 'inline') {- const mention = writer.createElement('linkMention', attrs);- model.insertContent(mention, writer.createRangeOn(selected));- } else {- // 'card' forces opengraph; 'embed' uses detected type.- attrs.embedType = targetMode === 'card' ? 'opengraph' : detectedType;- const embed = writer.createElement('linkEmbed', attrs);- model.insertContent(embed, writer.createRangeOn(selected));- }+ rebuildLinkWidget(this.editor, writer, selected, targetMode);});}@@ -171,7 +164,7 @@ export class ChangeLinkDisplayCommand extends Command {if (selected) {this.isEnabled = true;- this.value = this._getMode(selected);+ this.value = getLinkWidgetMode(selected);const url = selected.getAttribute('url') as string;this.embedAvailable = this._detectEmbedType(url) !== 'opengraph';// Only ever hand out an http(s) URL. `url` comes from the stored `data-url`, which the@@ -207,8 +200,7 @@ export class ChangeLinkDisplayCommand extends Command {* text is replaced by the preview.*/private async _convertNativeLink(targetMode: LinkDisplayMode) {- const editor = this.editor;- const model = editor.model;+ const model = this.editor.model;const position = model.document.selection.getFirstPosition();const href = model.document.selection.getAttribute('linkHref');/* v8 ignore next -- refresh() disables the command unless the selection carries a linkHref */@@ -216,48 +208,8 @@ export class ChangeLinkDisplayCommand extends Command {// The link already is one.if (targetMode === 'plain') return;- // The linked text is tracked as a live range: the metadata fetch reads the page server-side- // and can take seconds, and edits made meanwhile must not shift what gets replaced.- const liveRange = ModelLiveRange.fromRange(findAttributeRange(position, 'linkHref', href, model));- const metadata = await getLinkEmbedHost(editor).fetchMetadata(href);- const range = liveRange.toRange();- liveRange.detach();-- model.change(writer => {- // The link may have been edited away while the fetch was in flight.- let linkStillThere = false;- for (const { item } of range.getWalker()) {- if (item.is('$textProxy') && item.getAttribute('linkHref') === href) {- linkStillThere = true;- break;- }- }- if (!linkStillThere) return;-- const element = writer.createElement(targetMode === 'inline' ? 'linkMention' : 'linkEmbed', {- url: metadata.url,- // Same rule as the widget path above: a card is an embed that declines to play.- embedType: targetMode === 'card' ? 'opengraph'- : targetMode === 'embed' ? this._detectEmbedType(href)- : metadata.embedType,- title: metadata.title,- description: metadata.description,- favicon: metadata.favicon,- siteName: metadata.siteName,- image: metadata.image- });-- model.insertContent(element, range);- // Leave the new widget selected, so its toolbar — this same dropdown included — takes- // over from the link balloon.- writer.setSelection(element, 'on');- });- }-- private _getMode(element: any): LinkDisplayMode {- if (element.name === 'linkMention') return 'inline';- const embedType = element.getAttribute('embedType') as string;- return embedType === 'opengraph' ? 'card' : 'embed';+ const range = findAttributeRange(position, 'linkHref', href, model);+ await replaceLinkWithPreview(this.editor, range, href, targetMode, undefined);}/** Delegates to the host to avoid duplicating URL detection logic. */@@ -287,69 +239,89 @@ export class RemoveLinkEmbedCommand extends Command {}/**- * Edits the title a link preview displays — the pill text of a mention, the heading of a card.- * The preview counterpart of the "Displayed text" field the editor's own link form offers for- * native links: the fetched title is often noisy ("Article | Site | Section"), and converting a- * labeled link replaces the user's wording, so both need a way back to words of the user's choosing.+ * Replaces the link to `href` in `range` with a preview of the `mode` shape, once the page's+ * metadata arrives, and selects it. `title` replaces the page's own title.*- * `value` is what the preview currently shows (the stored title, or the hostname the renderers- * fall back to), for the edit form to prefill. As in the official form, saving it back unchanged —- * or blank — changes nothing.+ * The range is tracked as a live range while the metadata is fetched, so edits made meanwhile do+ * not shift what gets replaced. Nothing is replaced when the link is no longer in the range by+ * then.*/-export class ChangeLinkPreviewTitleCommand extends Command {- declare value: string | null;-- override execute({ title }: { title: string }) {- const model = this.editor.model;- const selected = getSelectedLinkWidget(this.editor);- if (!selected) return;-- const newTitle = title.trim();- if (!newTitle || newTitle === effectiveTitle(selected)) return;-- model.change(writer => {- const attrs: Record<string, unknown> = {};- for (const key of META_KEYS) {- const val = selected.getAttribute(key);- if (val != null) attrs[key] = val;+async function replaceLinkWithPreview(+ editor: Editor, range: ModelRange, href: string,+ mode: Exclude<LinkDisplayMode, 'plain'>, title: string | undefined+) {+ const model = editor.model;+ const liveRange = ModelLiveRange.fromRange(range);+ const metadata = await getLinkEmbedHost(editor).fetchMetadata(href);+ const currentRange = liveRange.toRange();+ liveRange.detach();++ model.change(writer => {+ let linkStillThere = false;+ for (const { item } of currentRange.getWalker()) {+ if (item.is('$textProxy') && item.getAttribute('linkHref') === href) {+ linkStillThere = true;+ break;}- attrs.title = newTitle;-- // Clone-replace rather than setAttribute: the editing downcast is elementToElement,- // which does not re-render on attribute changes — replacing does (and it is how mode- // switching already works). The widget stays selected, so its toolbar stays up.- const replacement = writer.createElement(selected.name, attrs);- model.insertContent(replacement, writer.createRangeOn(selected));- writer.setSelection(replacement, 'on');+ }+ if (!linkStillThere) return;++ const element = writer.createElement(mode === 'inline' ? 'linkMention' : 'linkEmbed', {+ url: metadata.url,+ // A card is an embed that declines to play: forcing "opengraph" is what tells the+ // renderer to draw the static card rather than the provider's player.+ embedType: mode === 'card' ? 'opengraph'+ : mode === 'embed' ? getLinkEmbedHost(editor).detectEmbedType(href)+ : metadata.embedType,+ title: title || metadata.title,+ description: metadata.description,+ favicon: metadata.favicon,+ siteName: metadata.siteName,+ image: metadata.image});- }- override refresh() {- const selected = getSelectedLinkWidget(this.editor);- this.isEnabled = !!selected;- this.value = selected ? effectiveTitle(selected) : null;- }+ model.insertContent(element, currentRange);+ // The widget toolbar, with its Display dropdown, takes over from the link balloon.+ writer.setSelection(element, 'on');+ });}/**- * The title a preview currently displays: its stored title, or — mirroring the renderers'- * fallback (see MentionPreview in the client) — the hostname of its URL.+ * Replaces the link preview `element` with one of the `mode` shape, built from the metadata it+ * stores, and returns it. `title` replaces its title.*/-function effectiveTitle(element: any): string {- const title = element.getAttribute('title') as string | undefined;- if (title) return title;-- /* v8 ignore next -- every linkEmbed/linkMention is created with a url attribute (a widget without one does not even render), so the fallback arm is unreachable */- const url = (element.getAttribute('url') ?? '') as string;- try {- return new URL(url).hostname;- } catch {- return url;+function rebuildLinkWidget(+ editor: Editor, writer: ModelWriter, element: ModelElement,+ mode: Exclude<LinkDisplayMode, 'plain'>, title?: string+) {+ const attrs: Record<string, unknown> = {};+ for (const key of META_KEYS) {+ const val = element.getAttribute(key);+ if (val != null) attrs[key] = val;}+ if (title) attrs.title = title;+ if (mode !== 'inline') {+ // A card is an embed that declines to play.+ attrs.embedType = mode === 'card' ? 'opengraph'+ : getLinkEmbedHost(editor).detectEmbedType(attrs.url as string);+ }++ // Replaced rather than given new attributes: the editing downcast is elementToElement, which+ // does not re-render on attribute changes.+ const name = mode === 'inline' ? 'linkMention' : 'linkEmbed';+ const replacement = writer.createElement(name, attrs);+ editor.model.insertContent(replacement, writer.createRangeOn(element));+ return replacement;+}++/** The display mode of the link preview `element`. */+export function getLinkWidgetMode(element: ModelElement): Exclude<LinkDisplayMode, 'plain'> {+ if (element.name === 'linkMention') return 'inline';+ return element.getAttribute('embedType') === 'opengraph' ? 'card' : 'embed';}/** Returns the currently selected linkEmbed/linkMention element, or null. */-function getSelectedLinkWidget(editor: any) {+export function getSelectedLinkWidget(editor: Editor): ModelElement | null {const selected = editor.model.document.selection.getSelectedElement();if (selected && (selected.name === 'linkMention' || selected.name === 'linkEmbed')) {return selected;diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.tsindex 778cdbfc41..342d690519 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts@@ -2,9 +2,7 @@ import { Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget } fromimport { preventCKEditorHandling, restoreRendererFocusOnInput } from '../widget_utils.js';import {CHANGE_LINK_DISPLAY_COMMAND,- CHANGE_LINK_PREVIEW_TITLE_COMMAND,ChangeLinkDisplayCommand,- ChangeLinkPreviewTitleCommand,getLinkEmbedHost,InsertLinkEmbedCommand,LINK_EMBED_COMMAND,@@ -38,7 +36,6 @@ export default class LinkEmbedEditing extends Plugin {this.editor.commands.add(LINK_EMBED_COMMAND, new InsertLinkEmbedCommand(this.editor));this.editor.commands.add(CHANGE_LINK_DISPLAY_COMMAND, new ChangeLinkDisplayCommand(this.editor));this.editor.commands.add(REMOVE_LINK_EMBED_COMMAND, new RemoveLinkEmbedCommand(this.editor));- this.editor.commands.add(CHANGE_LINK_PREVIEW_TITLE_COMMAND, new ChangeLinkPreviewTitleCommand(this.editor));restoreRendererFocusOnInput(this);}diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.tsdeleted file mode 100644index 771aef4e1f..0000000000--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_form.spec.ts+++ /dev/null@@ -1,288 +0,0 @@-import { BlockQuote, ClassicEditor, ContextualBalloon, Essentials, Link, Paragraph, Undo, _setModelData as setModelData } from "ckeditor5";-import { beforeEach, describe, expect, it, vi } from "vitest";--import { createTestEditor } from "../../../test/editor-kit.js";-import LinkEmbed, { LINK_EMBED_COMMAND } from "./link_embed.js";-import LinkEmbedFormView from "./link_embed_form.js";--const META = {- url: "https://example.com/",- embedType: "opengraph",- title: "Example title",- description: "Some description",- favicon: "https://example.com/favicon.ico",- siteName: "Example",- image: "https://example.com/image.png"-};--describe("LinkEmbedFormView", () => {- let editor: ClassicEditor;- let fetchMetadata: ReturnType<typeof vi.fn>;-- beforeEach(async () => {- fetchMetadata = vi.fn(async (url: string) => ({ ...META, url }));-- editor = await createTestEditor([Essentials, Paragraph, BlockQuote, Link, Undo, LinkEmbed], {- linkEmbed: {- renderEmbed: vi.fn(),- renderMention: vi.fn(),- fetchMetadata,- // YouTube-like URLs are embeddable; everything else is not.- detectEmbedType: (url: string) => (url.includes("youtube") ? "youtube" : "opengraph")- }- });- setModelData(editor.model, "<paragraph>[]</paragraph>");- });-- /** Opens the balloon by clicking the toolbar button, and returns the form inside it. */- function openForm(): LinkEmbedFormView {- const button = editor.ui.componentFactory.create("linkEmbed") as unknown as { fire(name: string): void };- button.fire("execute");-- const form = editor.plugins.get(ContextualBalloon).visibleView;- if (!(form instanceof LinkEmbedFormView)) {- throw new Error("The balloon does not hold the link-preview form.");- }- return form;- }-- function isInBalloon(form: LinkEmbedFormView) {- return editor.plugins.get(ContextualBalloon).hasView(form);- }-- /** Types into the URL field the way a user does, so the input event fires. */- function typeUrl(form: LinkEmbedFormView, url: string) {- const input = form.urlInputView.fieldView.element;- if (!input) {- throw new Error("The URL field is not rendered.");- }- input.value = url;- input.dispatchEvent(new Event("input"));- }-- // ------------------------------------------------------------------------ // Structure- // ------------------------------------------------------------------------- it("wears CKEditor's own link-form classes, so it matches the native link balloon", () => {- const form = openForm();- const classes = form.element?.classList;-- expect(classes?.contains("ck-link-form")).toBe(true);- expect(classes?.contains("ck-responsive-form")).toBe(true);- expect(form.element?.tagName).toBe("FORM");- });-- it("holds a heading, a URL field, a display-mode selector and an Insert button — and nothing else", () => {- const form = openForm();-- expect(form.element?.querySelector(".ck-link-embed-form__heading")?.textContent).toBe("Link preview");- expect(form.urlInputView.label).toBe("URL");- expect(form.urlInputView.fieldView.placeholder).toBe("http://");- expect(form.modeDropdownView.buttonView.label).toBe("Card");-- // A text button, like the Insert button of the editor's own link form.- expect(form.insertButtonView.label).toBe("Insert");- expect(form.insertButtonView.withText).toBe(true);- expect(form.insertButtonView.element?.classList.contains("ck-button-action")).toBe(true);- expect(form.insertButtonView.element?.classList.contains("ck-button_with-text")).toBe(true);-- // The dropdown and the button share a row below the field.- const actions = form.element?.querySelector(".ck-link-embed-form__actions");- expect(actions?.contains(form.modeDropdownView.element ?? null)).toBe(true);- expect(actions?.contains(form.insertButtonView.element ?? null)).toBe(true);- });-- it("puts the caret straight in the URL field, so the user can just type", () => {- const form = openForm();-- expect(document.activeElement).toBe(form.urlInputView.fieldView.element);- });-- it("resolves its labels through the editor's dictionary when there is one", async () => {- // Keyed by `en`, the language the editor resolves messages under when none is configured.- editor = await createTestEditor(- [Essentials, Paragraph, Link, Undo, LinkEmbed],- { translations: [ {}, { en: { dictionary: { "URL": "Adresă", "Insert": "Inserează" } } } ] }- );- setModelData(editor.model, "<paragraph>[]</paragraph>");-- const form = openForm();- expect(form.urlInputView.label).toBe("Adresă");- expect(form.insertButtonView.label).toBe("Inserează");- });-- // ------------------------------------------------------------------------ // The mode selector- // ------------------------------------------------------------------------- it("defaults to Card, and to Embed once the URL turns out to have a player", () => {- const form = openForm();- expect(form.mode).toBe("card");- expect(form.embedAvailable).toBe(false);-- typeUrl(form, "https://youtube.com/watch?v=abc12345678");- expect(form.embedAvailable).toBe(true);- expect(form.mode).toBe("embed");-- // Back to an ordinary page: the player is neither offered nor kept.- typeUrl(form, "https://example.com/article");- expect(form.embedAvailable).toBe(false);- expect(form.mode).toBe("card");- });-- it("stops following the URL once the user picks a mode, but never leaves them on an impossible one", () => {- const form = openForm();-- form.modeDropdownView.fire("execute", { source: { _displayMode: "inline" } });- form.mode = "inline";-- // The user has spoken: an embeddable URL no longer overrules them.- typeUrl(form, "https://youtube.com/watch?v=abc12345678");- expect(form.mode).toBe("inline");-- // But a mode that the URL cannot support falls back rather than being submitted.- form.mode = "embed";- typeUrl(form, "https://example.com/article");- expect(form.mode).toBe("card");- });-- // ------------------------------------------------------------------------ // Submitting- // ------------------------------------------------------------------------- it("keeps Insert disabled until a URL is typed", () => {- const form = openForm();- expect(form.insertButtonView.isEnabled).toBe(false);-- typeUrl(form, "https://example.com/article");- expect(form.insertButtonView.isEnabled).toBe(true);- });-- it("inserts the preview, closes the balloon and leaves the form ready for next time", async () => {- const form = openForm();- typeUrl(form, "https://example.com/article");-- form.fire("submit");- await vi.waitFor(() => expect(isInBalloon(form)).toBe(false));-- expect(fetchMetadata).toHaveBeenCalledWith("https://example.com/article");- expect(editor.getData()).toContain('data-url="https://example.com/article"');-- // Reopening starts blank rather than showing the last URL.- const reopened = openForm();- expect(reopened.url).toBe("");- expect(reopened.mode).toBe("card");- });-- it("defaults the scheme, so a bare domain is not inserted as a dead link", async () => {- const form = openForm();- typeUrl(form, "example.com/article");-- form.fire("submit");- await vi.waitFor(() => expect(isInBalloon(form)).toBe(false));-- expect(fetchMetadata).toHaveBeenCalledWith("https://example.com/article");- });-- it("does nothing when submitted with an empty URL", () => {- const form = openForm();-- form.fire("submit");-- expect(fetchMetadata).not.toHaveBeenCalled();- expect(isInBalloon(form)).toBe(true);- });-- it("refuses a URL that cannot be a preview, leaving the form open", async () => {- const form = openForm();- typeUrl(form, "javascript:alert(1)");-- form.fire("submit");-- expect(fetchMetadata).not.toHaveBeenCalled();- expect(isInBalloon(form)).toBe(true);- });-- it("disables the form while the metadata is being fetched, so it cannot be submitted twice", async () => {- let resolveFetch: ((metadata: unknown) => void) | undefined;- fetchMetadata.mockImplementation(() => new Promise((resolve) => {- resolveFetch = resolve;- }));-- const form = openForm();- typeUrl(form, "https://example.com/article");-- form.fire("submit");- expect(form.isFetching).toBe(true);- expect(form.insertButtonView.isEnabled).toBe(false);- expect(form.modeDropdownView.isEnabled).toBe(false);-- // A second Enter while the first fetch is in flight must not fetch again.- form.fire("submit");- expect(fetchMetadata).toHaveBeenCalledTimes(1);-- resolveFetch?.({ ...META, url: "https://example.com/article" });- await vi.waitFor(() => expect(isInBalloon(form)).toBe(false));- expect(form.isFetching).toBe(false);- });-- // ------------------------------------------------------------------------ // Dismissing- // ------------------------------------------------------------------------- it("closes on Esc without inserting anything", () => {- const form = openForm();- typeUrl(form, "https://example.com/article");-- const before = editor.getData();- form.keystrokes.press({ keyCode: 27, preventDefault: () => {}, stopPropagation: () => {} } as unknown as KeyboardEvent);-- expect(isInBalloon(form)).toBe(false);- expect(fetchMetadata).not.toHaveBeenCalled();- expect(editor.getData()).toBe(before);- });-- it("follows the URL again after a dismissal, forgetting the earlier mode pick", () => {- const form = openForm();- typeUrl(form, "https://example.com/article");- form.modeDropdownView.fire("execute", { source: { _displayMode: "inline" } });- form.mode = "inline";-- // Dismiss without inserting: the pick was for that URL only.- form.keystrokes.press({ keyCode: 27, preventDefault: () => {}, stopPropagation: () => {} } as unknown as KeyboardEvent);- expect(isInBalloon(form)).toBe(false);-- // Reopened with an embeddable URL, the mode follows the URL again instead of the old pick.- openForm();- typeUrl(form, "https://youtube.com/watch?v=abc12345678");- expect(form.mode).toBe("embed");- });-- it("closes when the user clicks away from it", () => {- const form = openForm();- expect(isInBalloon(form)).toBe(true);-- // clickOutsideHandler watches for a mousedown outside the balloon.- document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));-- expect(isInBalloon(form)).toBe(false);- expect(fetchMetadata).not.toHaveBeenCalled();- });-- it("does not stack a second form when the button is clicked twice", () => {- const form = openForm();- openForm();-- expect(editor.plugins.get(ContextualBalloon).visibleView).toBe(form);- });-- it("only offers the insert command where a preview may go", () => {- const command = editor.commands.get(LINK_EMBED_COMMAND);- expect(command?.isEnabled).toBe(true);-- editor.enableReadOnlyMode("test");- expect(command?.isEnabled).toBe(false);- editor.disableReadOnlyMode("test");- });-});diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_form.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_form.tsdeleted file mode 100644index 91dbac3cd4..0000000000--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_form.ts+++ /dev/null@@ -1,216 +0,0 @@-import {- ButtonView,- Collection,- createDropdown,- createLabeledInputText,- DropdownButtonView,- FocusCycler,- FocusTracker,- KeystrokeHandler,- LabeledFieldView,- type DropdownView,- type FocusableView,- type InputTextView,- type ListDropdownButtonDefinition,- type Locale,- addListToDropdown,- submitHandler,- View,- ViewCollection,- ViewModel-} from "ckeditor5";--import { getLinkDisplayModeLabel, LINK_DISPLAY_MODES, type LinkDisplayMode } from "./link_embed_commands.js";--/** The editor's translation function, taking an English message id. */-type Translate = (message: string) => string;--/**- * The balloon form behind the "Link preview" toolbar button: a URL field, a display-mode selector- * and an Insert button.- *- * It wears CKEditor's own `ck-link-form ck-responsive-form` classes rather than a Trilium modal, so- * it looks and behaves exactly like the editor's native link balloon — including its narrow-screen- * layout — and so inserting a preview never leaves the editor.- */-export default class LinkEmbedFormView extends View {-- /** The URL to preview. */- declare public url: string;- /** The shape the preview will take. */- declare public mode: LinkDisplayMode;- /** Whether the URL supports a player (a YouTube link, say); "Embed" is hidden when it does not. */- declare public embedAvailable: boolean;- /** True while the metadata is being fetched, which disables the form. */- declare public isFetching: boolean;-- public readonly urlInputView: LabeledFieldView<InputTextView>;- public readonly modeDropdownView: DropdownView;- public readonly insertButtonView: ButtonView;-- public readonly focusTracker = new FocusTracker();- public readonly keystrokes = new KeystrokeHandler();-- private readonly _focusables = new ViewCollection<FocusableView>();- private readonly _focusCycler: FocusCycler;-- constructor(locale: Locale, t: Translate) {- super(locale);-- this.set("url", "");- this.set("mode", "card");- this.set("embedAvailable", false);- this.set("isFetching", false);-- this.urlInputView = this._createUrlInput(locale, t);- this.modeDropdownView = this._createModeDropdown(locale, t);- this.insertButtonView = this._createInsertButton(locale, t);-- this.setTemplate({- tag: "form",- attributes: {- // CKEditor's own link-balloon classes: same paddings, same responsive behaviour.- class: ["ck", "ck-link-form", "ck-responsive-form", "ck-link-embed-form"],- tabindex: "-1"- },- children: [- {- tag: "div",- attributes: { class: ["ck", "ck-link-embed-form__heading"] },- children: [{ text: t("Link preview") }]- },- this.urlInputView,- {- tag: "div",- attributes: { class: ["ck", "ck-link-embed-form__actions"] },- children: [- this.modeDropdownView,- this.insertButtonView- ]- }- ]- });-- this._focusCycler = new FocusCycler({- focusables: this._focusables,- focusTracker: this.focusTracker,- keystrokeHandler: this.keystrokes,- actions: {- focusPrevious: "shift + tab",- focusNext: "tab"- }- });- }-- public override render(): void {- super.render();-- // Turns a native form submit (the Enter key included) into the view's own `submit` event.- submitHandler({ view: this });-- for (const view of [this.urlInputView, this.modeDropdownView, this.insertButtonView]) {- this._focusables.add(view);- /* v8 ignore next -- a child view rendered as part of this template always has an element */- if (view.element) {- this.focusTracker.add(view.element);- }- }-- /* v8 ignore next -- super.render() has just built this view's element */- if (this.element) {- this.keystrokes.listenTo(this.element);- }- }-- public override destroy(): void {- super.destroy();- this.focusTracker.destroy();- this.keystrokes.destroy();- }-- /** Resets the form to a blank state, ready for the next insertion. */- public reset(): void {- this.url = "";- this.mode = "card";- this.embedAvailable = false;- this.isFetching = false;- }-- public focus(): void {- this._focusCycler.focusFirst();- }-- private _createUrlInput(locale: Locale, t: Translate) {- const urlInput = new LabeledFieldView(locale, createLabeledInputText);- urlInput.label = t("URL");- urlInput.fieldView.placeholder = "http://";-- // Two-way: the field drives `url`, and reset() drives the field.- urlInput.fieldView.bind("value").to(this, "url");- urlInput.fieldView.on("input", () => {- /* v8 ignore next -- the input event can only come from a rendered element */- this.url = urlInput.fieldView.element?.value ?? "";- });- urlInput.bind("isEnabled").to(this, "isFetching", (isFetching) => !isFetching);-- return urlInput;- }-- private _createModeDropdown(locale: Locale, t: Translate) {- const dropdown = createDropdown(locale, DropdownButtonView);-- dropdown.buttonView.set({ withText: true, tooltip: true });- dropdown.buttonView.bind("label").to(this, "mode", (mode) => getLinkDisplayModeLabel(t, mode));- dropdown.bind("isEnabled").to(this, "isFetching", (isFetching) => !isFetching);-- const items = new Collection<ListDropdownButtonDefinition>();- for (const mode of LINK_DISPLAY_MODES) {- const definition: ListDropdownButtonDefinition = {- type: "button",- model: new ViewModel({- _displayMode: mode,- label: getLinkDisplayModeLabel(t, mode),- role: "menuitemradio",- withText: true- })- };-- definition.model.bind("isOn").to(this, "mode", (current) => current === mode);-- // A player only exists for a URL that has one.- if (mode === "embed") {- definition.model.bind("isVisible").to(this, "embedAvailable");- }-- items.add(definition);- }- addListToDropdown(dropdown, items);-- dropdown.on("execute", (evt) => {- this.mode = (evt.source as unknown as { _displayMode: LinkDisplayMode })._displayMode;- });-- return dropdown;- }-- private _createInsertButton(locale: Locale, t: Translate) {- const button = new ButtonView(locale);-- // A text button, like the Insert button of the editor's own link form.- button.set({- label: t("Insert"),- withText: true,- type: "submit",- class: "ck-button-action ck-button-bold"- });-- // A URL is required, and nothing may be submitted twice while the first fetch is in flight.- button.bind("isEnabled").to(- this, "url",- this, "isFetching",- (url, isFetching) => !!String(url).trim() && !isFetching- );-- return button;- }-}diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.spec.tsdeleted file mode 100644index af08fd9568..0000000000--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.spec.ts+++ /dev/null@@ -1,58 +0,0 @@-import { Locale } from "ckeditor5";-import { describe, expect, it, vi } from "vitest";--import LinkEmbedTitleFormView from "./link_embed_title_form.js";--// Stands in for `editor.t`: no dictionary, so each message id renders as its own English text.-const t = (message: string) => message;--function createForm(): LinkEmbedTitleFormView {- const form = new LinkEmbedTitleFormView(new Locale(), t);- form.render();- return form;-}--describe("LinkEmbedTitleFormView", () => {- it("holds a heading, a Title field and a Save button, and prefills via reset()", () => {- const form = createForm();-- expect(form.element?.querySelector(".ck-link-embed-form__heading")?.textContent).toBe("Edit title");- expect(form.titleInputView.label).toBe("Title");- expect(form.saveButtonView.label).toBe("Save");-- form.reset("Current title");- expect(form.title).toBe("Current title");- expect(form.titleInputView.fieldView.value).toBe("Current title");-- form.focus();- form.destroy();- });-- it("enables Save only for a non-blank title, and follows typing in the field", () => {- const form = createForm();-- form.reset("");- expect(form.saveButtonView.isEnabled).toBe(false);- form.reset(" ");- expect(form.saveButtonView.isEnabled).toBe(false);-- const input = form.titleInputView.fieldView.element as HTMLInputElement;- input.value = "My words";- form.titleInputView.fieldView.fire("input");- expect(form.title).toBe("My words");- expect(form.saveButtonView.isEnabled).toBe(true);-- form.destroy();- });-- it("turns a native form submit into the view's own submit event", () => {- const form = createForm();- const submitted = vi.fn();- form.on("submit", submitted);-- form.element?.dispatchEvent(new Event("submit", { cancelable: true }));-- expect(submitted).toHaveBeenCalled();- form.destroy();- });-});diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.tsdeleted file mode 100644index 5a93a2249f..0000000000--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_title_form.ts+++ /dev/null@@ -1,145 +0,0 @@-import {- ButtonView,- createLabeledInputText,- FocusCycler,- FocusTracker,- KeystrokeHandler,- LabeledFieldView,- submitHandler,- View,- ViewCollection,- type FocusableView,- type InputTextView,- type Locale-} from "ckeditor5";--/** The editor's translation function, taking an English message id. */-type Translate = (message: string) => string;--/**- * The balloon form behind the widget toolbar's "Edit title" button: a single Title field and a- * Save button — the preview counterpart of the "Displayed text" field the editor's own link form- * offers for native links.- *- * It wears the same classes as the insert form (which reuses CKEditor's own `ck-link-form`), so it- * looks and behaves like the editor's native link balloons.- */-export default class LinkEmbedTitleFormView extends View {-- /** The title being edited, prefilled with what the preview currently shows. */- declare public title: string;-- public readonly titleInputView: LabeledFieldView<InputTextView>;- public readonly saveButtonView: ButtonView;-- public readonly focusTracker = new FocusTracker();- public readonly keystrokes = new KeystrokeHandler();-- private readonly _focusables = new ViewCollection<FocusableView>();- private readonly _focusCycler: FocusCycler;-- constructor(locale: Locale, t: Translate) {- super(locale);-- this.set("title", "");-- this.titleInputView = this._createTitleInput(locale, t);- this.saveButtonView = this._createSaveButton(locale, t);-- this.setTemplate({- tag: "form",- attributes: {- class: ["ck", "ck-link-form", "ck-responsive-form", "ck-link-embed-form"],- tabindex: "-1"- },- children: [- {- tag: "div",- attributes: { class: ["ck", "ck-link-embed-form__heading"] },- children: [{ text: t("Edit title") }]- },- this.titleInputView,- {- tag: "div",- attributes: { class: ["ck", "ck-link-embed-form__actions"] },- children: [this.saveButtonView]- }- ]- });-- this._focusCycler = new FocusCycler({- focusables: this._focusables,- focusTracker: this.focusTracker,- keystrokeHandler: this.keystrokes,- actions: {- focusPrevious: "shift + tab",- focusNext: "tab"- }- });- }-- public override render(): void {- super.render();-- // Turns a native form submit (the Enter key included) into the view's own `submit` event.- submitHandler({ view: this });-- for (const view of [this.titleInputView, this.saveButtonView]) {- this._focusables.add(view);- /* v8 ignore next -- a child view rendered as part of this template always has an element */- if (view.element) {- this.focusTracker.add(view.element);- }- }-- /* v8 ignore next -- super.render() has just built this view's element */- if (this.element) {- this.keystrokes.listenTo(this.element);- }- }-- public override destroy(): void {- super.destroy();- this.focusTracker.destroy();- this.keystrokes.destroy();- }-- /** Prefills the form with the title the preview currently shows. */- public reset(currentTitle: string): void {- this.title = currentTitle;- }-- public focus(): void {- this._focusCycler.focusFirst();- }-- private _createTitleInput(locale: Locale, t: Translate) {- const titleInput = new LabeledFieldView(locale, createLabeledInputText);- titleInput.label = t("Title");-- // Two-way: the field drives `title`, and reset() drives the field.- titleInput.fieldView.bind("value").to(this, "title");- titleInput.fieldView.on("input", () => {- /* v8 ignore next -- the input event can only come from a rendered element */- this.title = titleInput.fieldView.element?.value ?? "";- });-- return titleInput;- }-- private _createSaveButton(locale: Locale, t: Translate) {- const button = new ButtonView(locale);-- button.set({- label: t("Save"),- withText: true,- type: "submit",- class: "ck-button-action ck-button-bold"- });-- // A blank title is never saved — clearing the field is not how a title is removed.- button.bind("isEnabled").to(this, "title", (title) => !!String(title).trim());-- return button;- }-}diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.tsindex f17057fe36..7d15ee5673 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.spec.ts@@ -1,9 +1,11 @@-import { ClassicEditor, ContextualBalloon, Essentials, Link, Paragraph, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";+import {+ ClassicEditor, Essentials, Link, Paragraph, WidgetToolbarRepository, _setModelData as setModelData+} from "ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";+import InternalLinkPlugin from "../internallink.js";import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_DISPLAY_MODES } from "./link_embed.js";-import LinkEmbedTitleFormView from "./link_embed_title_form.js";import LinkEmbedToolbar from "./link_embed_toolbar.js";// ---------------------------------------------------------------------------@@ -104,9 +106,10 @@ describe("LinkEmbedToolbar", () => {expect(repository._toolbarDefinitions.has("linkEmbed")).toBe(true);});- it("registered toolbar contains the linkEmbedDisplayDropdown item", () => {+ it("registered toolbar contains the Edit link and Display items", () => {const def = getToolbarDef(editor);expect(def).toBeDefined();+ expect(def?.itemsConfig).toContain("linkEmbedEditLink");expect(def?.itemsConfig).toContain("linkEmbedDisplayDropdown");});@@ -677,66 +680,21 @@ describe("LinkEmbedToolbar", () => {expect(editor.getData()).toBe(`<p>${URL}</p>`);});- it("linkEmbedEditTitle opens a balloon form prefilled with the current title and saves the edit", () => {- const button = createButton("linkEmbedEditTitle");- expect(button.isEnabled).toBe(false);-- selectLinkMention();- expect(button.isEnabled).toBe(true);-- // Put the widget toolbar in the balloon first, as it necessarily is when the user- // clicks the pencil inside it — otherwise it would stack itself over the form when- // focusing the form flips the UI focus tracker.- editor.ui.focusTracker.isFocused = true;- editor.ui.fire("update");+ it("linkEmbedEditLink opens the link dialog on the selected widget", async () => {+ expect(createButton("linkEmbedEditLink").isEnabled).toBe(false);- const balloon = editor.plugins.get(ContextualBalloon);- button.fire("execute");-- const form = balloon.visibleView as LinkEmbedTitleFormView;- expect(form).toBeInstanceOf(LinkEmbedTitleFormView);- // Prefilled with what the pill currently shows, so an untouched save changes nothing.- expect(form.title).toBe("T");-- form.title = "My words";- form.fire("submit");+ const showDialog = vi.fn(() => null);+ editor = await createTestEditor(+ [Essentials, Paragraph, LinkEmbed, LinkEmbedToolbar, InternalLinkPlugin],+ { internalLink: { showDialog } }+ );+ const button = createButton("linkEmbedEditLink");+ expect(button.label).toBe("Edit link");- // The form is gone and the title took: the widget re-rendered with the new title.- expect(balloon.hasView(form)).toBe(false);- const mention = editor.model.document.selection.getSelectedElement();- expect(mention?.getAttribute("title")).toBe("My words");-- // Esc dismisses without saving: reopening prefills with the widget's current title.- button.fire("execute");- expect(form.title).toBe("My words");- form.keystrokes.press({ keyCode: 27, preventDefault: () => {}, stopPropagation: () => {} } as unknown as Parameters<typeof form.keystrokes.press>[0]);- expect(balloon.hasView(form)).toBe(false);- });-- it("linkEmbedEditTitle guards reopening, closes on outside click, and opens blank without a widget", () => {- const button = createButton("linkEmbedEditTitle");selectLinkMention();- editor.ui.focusTracker.isFocused = true;- editor.ui.fire("update");-- const balloon = editor.plugins.get(ContextualBalloon);- button.fire("execute");- const form = balloon.visibleView as LinkEmbedTitleFormView;- expect(form).toBeInstanceOf(LinkEmbedTitleFormView);-- // A second click while the form is open is a no-op, not a second balloon entry.- button.fire("execute");- expect(balloon.visibleView).toBe(form);-- // A click outside the balloon dismisses the form without saving.- document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));- expect(balloon.hasView(form)).toBe(false);- expect(editor.model.document.selection.getSelectedElement()?.getAttribute("title")).toBe("T");-- // Fired with no widget under the selection, the form opens blank (the command reports null).- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");+ expect(button.isEnabled).toBe(true);button.fire("execute");- expect(form.title).toBe("");+ expect(showDialog).toHaveBeenCalledOnce();});});});diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.tsindex 99e7b85a49..f8284b806a 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts@@ -3,9 +3,7 @@ import {WidgetToolbarRepository,isWidget,type ViewElement,- clickOutsideHandler,Collection,- ContextualBalloon,ViewModel,createDropdown,addListToDropdown,@@ -17,28 +15,33 @@ import {type Locale,type Command} from "ckeditor5";+import { COMMAND_NAME as LINK_DIALOG_COMMAND } from "../internallink.js";import LinkEmbed, {CHANGE_LINK_DISPLAY_COMMAND,- CHANGE_LINK_PREVIEW_TITLE_COMMAND,getLinkDisplayModeLabel,LINK_DISPLAY_MODES,REMOVE_LINK_EMBED_COMMAND,type LinkDisplayMode} from "./link_embed.js";-import LinkEmbedTitleFormView from "./link_embed_title_form.js";import { createCopyUrlButton } from "../copy_link_url.js";export default class LinkEmbedToolbar extends Plugin {static get requires() {- return [WidgetToolbarRepository, LinkEmbed, LinkEmbedLinkButton, LinkEmbedCopyUrlButton, LinkEmbedEditTitleButton, LinkEmbedUnlinkButton, LinkEmbedDisplayDropdown] as const;+ return [+ WidgetToolbarRepository, LinkEmbed, LinkEmbedLinkButton, LinkEmbedCopyUrlButton,+ LinkEmbedEditLinkButton, LinkEmbedUnlinkButton, LinkEmbedDisplayDropdown+ ] as const;}afterInit() {const widgetToolbarRepository = this.editor.plugins.get(WidgetToolbarRepository);widgetToolbarRepository.register("linkEmbed", {- items: ["linkEmbedLink", "linkEmbedCopyUrl", "linkEmbedEditTitle", "linkEmbedUnlink", "|", "linkEmbedDisplayDropdown"],+ items: [+ "linkEmbedLink", "linkEmbedCopyUrl", "linkEmbedEditLink", "linkEmbedUnlink", "|",+ "linkEmbedDisplayDropdown"+ ],balloonClassName: "ck-toolbar-container link-embed-toolbar",getRelatedElement(selection) {const selectedElement = selection.getSelectedElement();@@ -235,110 +238,38 @@ class LinkEmbedUnlinkButton extends Plugin {}/**- * Registers the `linkEmbedEditTitle` toolbar item: a pencil button opening a balloon form that- * edits the title the selected preview displays — the widget counterpart of the "Displayed text"- * field the editor's own link form offers for native links.+ * Registers the `linkEmbedEditLink` toolbar item: opens the host's link dialog on the selected+ * preview, as the `editLink` button of the link toolbar does on a native link. The dialog edits its+ * address, title and display.*/-class LinkEmbedEditTitleButton extends Plugin {+class LinkEmbedEditLinkButton extends Plugin {static get requires() {- return [LinkEmbed, ContextualBalloon] as const;+ return [LinkEmbed] as const;}- private _formView: LinkEmbedTitleFormView | null = null;-public init() {const editor = this.editor;- editor.ui.componentFactory.add("linkEmbedEditTitle", (locale) => {- const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND);+ editor.ui.componentFactory.add("linkEmbedEditLink", (locale) => {+ const command = editor.commands.get(LINK_DIALOG_COMMAND);const button = new ButtonView(locale);button.set({- label: editor.t("Edit title"),+ label: editor.t("Edit link"),icon: IconPencil,- tooltip: true+ tooltip: true,+ isEnabled: false});- /* v8 ignore next -- LinkEmbedEditing always registers CHANGE_LINK_PREVIEW_TITLE_COMMAND (this plugin requires LinkEmbed), so the no-command branch is unreachable */if (command) {button.bind("isEnabled").to(command, "isEnabled");}- button.on("execute", () => this._showForm());+ button.on("execute", () => editor.execute(LINK_DIALOG_COMMAND));return button;});}-- public override destroy() {- super.destroy();- this._formView?.destroy();- }-- private _showForm() {- const editor = this.editor;- const balloon = editor.plugins.get(ContextualBalloon);- const form = this._getFormView();-- if (balloon.hasView(form)) return;-- // Prefill with what the preview currently shows, so a save without edits changes nothing.- // The command always exists: LinkEmbedEditing registers it and this plugin requires LinkEmbed.- const command = editor.commands.get(CHANGE_LINK_PREVIEW_TITLE_COMMAND) as Command & { value: string | null };- form.reset(command.value ?? "");-- balloon.add({- view: form,- position: {- target: () => {- const view = editor.editing.view;- const range = view.document.selection.getFirstRange();- /* v8 ignore next -- the editing view's selection always has a range while a widget is selected */- if (!range) return editor.ui.getEditableElement() as HTMLElement;- return view.domConverter.viewRangeToDom(range);- }- }- });- form.focus();- }-- private _hideForm() {- const balloon = this.editor.plugins.get(ContextualBalloon);- const form = this._formView;-- /* v8 ignore next -- the form is only ever hidden from its own handlers, so by then it exists and is shown */- if (!form || !balloon.hasView(form)) return;-- balloon.remove(form);- this.editor.editing.view.focus();- }-- private _getFormView(): LinkEmbedTitleFormView {- if (this._formView) return this._formView;-- const editor = this.editor;- const form = new LinkEmbedTitleFormView(editor.locale, editor.t);- this._formView = form;-- form.on("submit", () => {- editor.execute(CHANGE_LINK_PREVIEW_TITLE_COMMAND, { title: form.title });- this._hideForm();- });-- // Esc and clicking away dismiss the form, exactly as they do for the insert form.- form.keystrokes.set("Esc", (_data, cancel) => {- this._hideForm();- cancel();- });- clickOutsideHandler({- emitter: form,- activator: () => this.editor.plugins.get(ContextualBalloon).hasView(form),- contextElements: () => [this.editor.plugins.get(ContextualBalloon).view.element as HTMLElement],- callback: () => this._hideForm()- });-- return form;- }}/**diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.spec.tsdeleted file mode 100644index 621b11d8ca..0000000000--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.spec.ts+++ /dev/null@@ -1,32 +0,0 @@-import { ContextualBalloon, type ClassicEditor, _setModelData as setModelData } from "ckeditor5";-import { beforeEach, describe, expect, it } from "vitest";--import { createLinkEmbedHost, createTestEditor, LINK_EMBED_TEST_PLUGINS } from "../../../test/link-embed-kit.js";-import { LINK_EMBED_COMMAND } from "./link_embed_commands.js";-import LinkEmbedFormView from "./link_embed_form.js";--describe("LinkEmbedUI", () => {- let editor: ClassicEditor;-- beforeEach(async () => {- editor = await createTestEditor(LINK_EMBED_TEST_PLUGINS, { linkEmbed: createLinkEmbedHost() });- });-- it("binds the button to the insert command and opens the balloon form on click", () => {- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");-- const view = editor.ui.componentFactory.create("linkEmbed") as unknown as {- isEnabled: boolean;- fire(name: string): void;- };- const command = editor.commands.get(LINK_EMBED_COMMAND);- expect(view.isEnabled).toBe(command?.isEnabled);-- const balloon = editor.plugins.get(ContextualBalloon);- expect(balloon.visibleView).toBeNull();-- // The insert flow now happens in the editor's own balloon, not in a Trilium modal.- view.fire("execute");- expect(balloon.visibleView).toBeInstanceOf(LinkEmbedFormView);- });-});diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.tsdeleted file mode 100644index add6a825bd..0000000000--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_ui.ts+++ /dev/null@@ -1,172 +0,0 @@-import { isHttpUrl } from '@triliumnext/commons';-import { ButtonView, clickOutsideHandler, ContextualBalloon, Plugin, type Editor, type Observable } from 'ckeditor5';-import linkPreviewIcon from '../../icons/link-preview.svg?raw';-import { getLinkEmbedHost, LINK_EMBED_COMMAND } from './link_embed_commands.js';-import LinkEmbedFormView from './link_embed_form.js';--/**- * The "Link preview" toolbar button and the balloon form it opens.- *- * The form lives inside the editor — the same balloon the native link button uses — rather than in a- * Trilium modal, so inserting a preview never leaves the editing surface and needs no round trip- * out to the app and back.- */-export default class LinkEmbedUI extends Plugin {-- static get requires() {- return [ContextualBalloon];- }-- private _formView: LinkEmbedFormView | null = null;-- init() {- const editor = this.editor;-- editor.ui.componentFactory.add('linkEmbed', locale => {- const command = editor.commands.get(LINK_EMBED_COMMAND);- const buttonView = new ButtonView(locale);-- buttonView.set({- label: editor.t('Link preview'),- icon: linkPreviewIcon,- tooltip: true- });-- /* v8 ignore next -- LinkEmbedEditing always registers LINK_EMBED_COMMAND (both are required by LinkEmbed), so the no-command branch is unreachable */- if (command) {- buttonView.bind('isEnabled').to(command as Observable & { isEnabled: boolean }, 'isEnabled');- }-- this.listenTo(buttonView, 'execute', () => this.showForm());- return buttonView;- });- }-- override destroy() {- super.destroy();- this._formView?.destroy();- }-- /** Opens the balloon form at the selection, unless it is already open. */- showForm() {- const editor = this.editor;- const balloon = editor.plugins.get(ContextualBalloon);- const form = this._getFormView();-- if (balloon.hasView(form)) return;-- form.reset();- balloon.add({- view: form,- position: {- target: () => {- const view = editor.editing.view;- const range = view.document.selection.getFirstRange();- /* v8 ignore next -- the editing view's selection always has a range while the editor is focused */- if (!range) return editor.ui.getEditableElement() as HTMLElement;- return view.domConverter.viewRangeToDom(range);- }- }- });- form.focus();- }-- private _hideForm() {- const balloon = this.editor.plugins.get(ContextualBalloon);- const form = this._formView;-- /* v8 ignore next -- the form is only ever hidden from its own handlers, so by then it exists and is shown */- if (!form || !balloon.hasView(form)) return;-- balloon.remove(form);- // Whatever mode the user picked was for the URL of this session — however it ended, the- // next form opening follows its own URL again.- this._modePickedByUser = false;- this.editor.editing.view.focus();- }-- private _getFormView(): LinkEmbedFormView {- if (this._formView) return this._formView;-- const editor = this.editor;- const form = new LinkEmbedFormView(editor.locale, editor.t);- this._formView = form;-- // The mode selector only offers "Embed" for a URL that has a player behind it — the same- // question the widget toolbar's dropdown asks of an existing preview.- form.on('change:url', () => {- const embedAvailable = detectEmbedTypeFor(editor, form.url) !== 'opengraph';- form.embedAvailable = embedAvailable;-- // Follow the URL until the user overrules it: a video wants its player, anything else a card.- if (!this._modePickedByUser) {- form.mode = embedAvailable ? 'embed' : 'card';- } else if (!embedAvailable && form.mode === 'embed') {- form.mode = 'card';- }- });-- form.modeDropdownView.on('execute', () => {- this._modePickedByUser = true;- });-- form.on('submit', () => {- void this._insert(form);- });-- // Esc and clicking away dismiss the form, exactly as they do for the native link balloon.- form.keystrokes.set('Esc', (_data, cancel) => {- this._hideForm();- cancel();- });- clickOutsideHandler({- emitter: form,- activator: () => this.editor.plugins.get(ContextualBalloon).hasView(form),- contextElements: () => [this.editor.plugins.get(ContextualBalloon).view.element as HTMLElement],- callback: () => this._hideForm()- });-- return form;- }-- private _modePickedByUser = false;-- private async _insert(form: LinkEmbedFormView) {- // The Insert button is disabled mid-fetch, but Enter fires `submit` on the form itself, so- // the guard has to live here or a second Enter would fetch and insert twice.- if (form.isFetching) return;-- const url = normalizeUrl(form.url);- if (!url) return;-- // The metadata fetch takes a moment (the server reads the page and downloads the image), so- // the form stays open and disabled meanwhile rather than vanishing into an apparent no-op.- form.isFetching = true;- try {- await this.editor.execute(LINK_EMBED_COMMAND, { url, mode: form.mode });- } finally {- form.isFetching = false;- }-- this._hideForm();- }-}--/**- * Makes a typed URL absolute, defaulting the scheme the way the editor's own link field does.- * Returns null when what was typed cannot be a link preview at all.- */-function normalizeUrl(rawUrl: string): string | null {- const trimmed = rawUrl.trim();- if (!trimmed) return null;-- const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`;- return isHttpUrl(withScheme) ? withScheme : null;-}--/** Asks the host what kind of preview a URL supports. */-function detectEmbedTypeFor(editor: Editor, url: string): string {- if (!url.trim()) return 'opengraph';-- return getLinkEmbedHost(editor).detectEmbedType(normalizeUrl(url) ?? url);-}diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.tsindex c81128d158..9cdc65975e 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts@@ -23,8 +23,6 @@ import { INSERT_ICON_COMMAND } from "../inline_icon/inline_icon_editing.js";import InlineIconUI from "../inline_icon/inline_icon_ui.js";import InsertDateTimePlugin, { COMMAND_NAME as INSERT_DATE_TIME_COMMAND, DATE_TIME_PRESETS } from "../insert_date_time.js";import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from "../internallink.js";-import { LINK_EMBED_COMMAND } from "../link_embed/link_embed_commands.js";-import LinkEmbedUI from "../link_embed/link_embed_ui.js";import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";import MathUI from "../math/math_ui.js";import {@@ -591,7 +589,7 @@ describe("buildTriliumSlashCommands", () => {[ "collapsible", "Collapsible block", "collapsible" ],[ "footnote", "Footnote", "InsertFootnote" ],[ "internal-link", "Internal link", INTERNAL_LINK_COMMAND ],- [ "link-preview", "Link preview", LINK_EMBED_COMMAND ],+ [ "link-preview", "Link preview", INTERNAL_LINK_COMMAND ],[ "attach-file", "Attach file as a link", "fileUpload" ],[ "attach-and-embed-file", "Attach and embed file", "fileUpload" ],[ "drawing-canvas", "Drawing canvas", "fileUpload" ],@@ -839,6 +837,16 @@ describe("buildTriliumSlashCommands", () => {}});+ it("opens the link dialog for a web link displayed as a preview", () => {+ const { fake, executeSpy } = makeFakeEditor();++ definition("link-preview").execute?.(fake);++ expect(executeSpy).toHaveBeenCalledExactlyOnceWith(+ INTERNAL_LINK_COMMAND, { target: "url", display: "embed" }+ );+ });+it("opens the math balloon rather than running a command", () => {const { fake, pluginInstances } = makeFakeEditor();const showUI = vi.fn();@@ -853,8 +861,7 @@ describe("buildTriliumSlashCommands", () => {// finished its own DOM and selection cleanup.it.each([[ "anchor", BookmarkUI, "_showFormView" ],- [ "icon", InlineIconUI, "showPicker" ],- [ "link-preview", LinkEmbedUI, "showForm" ]+ [ "icon", InlineIconUI, "showPicker" ]] as const)("defers the %s entry's balloon to the next tick", (id, plugin, method) => {vi.useFakeTimers();try {diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.tsindex e88cfaf877..0718cab8e1 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts@@ -58,8 +58,6 @@ import { INSERT_ICON_COMMAND } from "../inline_icon/inline_icon_editing.js";import InlineIconUI from "../inline_icon/inline_icon_ui.js";import InsertDateTimePlugin, { COMMAND_NAME as INSERT_DATE_TIME_COMMAND, getDateTimeFormatOptions } from "../insert_date_time.js";import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from "../internallink.js";-import { LINK_EMBED_COMMAND } from "../link_embed/link_embed_commands.js";-import LinkEmbedUI from "../link_embed/link_embed_ui.js";import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";import MathUI from "../math/math_ui.js";import { INSERT_INLINE_EMBED_COMMAND } from "../content_embed/inline_source.js";@@ -414,12 +412,10 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitiodescription: t("Insert a preview of a web page or a video"),aliases: [ "embed", "url", "website", "youtube", "video" ],icon: linkPreviewIcon,- // `commandName` supplies the enabled state; `execute` opens the form that asks for the URL.- commandName: LINK_EMBED_COMMAND,- // Deferred for the reason the anchor entry is: the form opens in a balloon placed at the- // caret, which the palette has not put back until the tick is over.+ commandName: INTERNAL_LINK_COMMAND,+ // The link dialog on the web link side, with a video player or else a card.execute: (target: Editor) => {- setTimeout(() => target.plugins.get(LinkEmbedUI).showForm(), 0);+ target.execute(INTERNAL_LINK_COMMAND, { target: "url", display: "embed" });}},{diff --git a/packages/ckeditor5/src/theme/link_embed_form.css b/packages/ckeditor5/src/theme/link_embed_form.cssdeleted file mode 100644index 864aaee3d1..0000000000--- a/packages/ckeditor5/src/theme/link_embed_form.css+++ /dev/null@@ -1,40 +0,0 @@-/*- * The link-preview balloon form.- *- * It wears CKEditor's own `.ck-link-form.ck-responsive-form` so the paddings, the field styling and- * the narrow-screen behaviour come for free. What differs is the layout: a heading, the URL field,- * and then the display-mode dropdown next to the Insert button on a row of their own.- */-.ck.ck-link-embed-form {- display: flex;- flex-direction: column;- align-items: stretch;-}--.ck.ck-link-embed-form__heading {- font-size: var(--ck-font-size-small, var(--ck-font-size-sm));- font-weight: bold;- margin-bottom: var(--ck-spacing-standard, var(--ck-spacing-base));-}--.ck.ck-link-embed-form__actions {- display: flex;- align-items: center;- gap: var(--ck-spacing-standard, var(--ck-spacing-base));- margin-top: 8px;-- /* The responsive form indents its children; the row places them itself. */- & > .ck-dropdown {- margin-left: 0;-- & > .ck-button {- /* Keep the mode names on one line ("Inline", "Card", "Embed"). */- white-space: nowrap;- }- }-- /* Insert sits at the end of the row. */- & > .ck-button-action {- margin-left: auto;- }-}