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/youtube preview: refactor, extract as a component based on content embed
Adorian Doran0d58217db80c
diff --git a/.claude/skills/developing-content-embeds/SKILL.md b/.claude/skills/developing-content-embeds/SKILL.mdindex 0994e288f4..a7996ec012 100644--- a/.claude/skills/developing-content-embeds/SKILL.md+++ b/.claude/skills/developing-content-embeds/SKILL.md@@ -1,7 +1,7 @@---name: developing-content-embedsdescription: >-- Use when building or changing an embed in a text note — an included note, an attachment embed such as a canvas drawing (`CanvasDrawing`), or a source embed such as a Mermaid diagram (`MermaidDiagram`, `SOURCE_EMBED_TYPES`) — or adding an embed kind. Covers the storage forms (`data-note-id`, `data-attachment-id`, inline `<pre><code class="language-…">`), the editor plugin (`packages/ckeditor5/src/plugins/content_embed/`: `content_embed.ts`, `inline_source.ts`, toolbar, box-size dropdown), the host contract (`contentEmbed.loadAttachment()`, `contentEmbed.loadInline()`), the client box (`ContentEmbed`, `text/utils.ts`), the content component contract (`useEditableEmbed()`, `ContentEmbedToolProvider`, Editable, display modes, fullscreen), reusing the note type's component as canvas and Mermaid do, the read-only paths (AI chat, Markdown preview, print, share), and traps hit (detached content, CodeMirror read-only fixed at creation, the CKEditor `:first-child` separator rule, untitled box sizes, class clashes).+ Use when building or changing an embed in a text note — an included note, an attachment embed such as a canvas drawing (`CanvasDrawing`), a source embed such as a Mermaid diagram (`MermaidDiagram`, `SOURCE_EMBED_TYPES`), or a YouTube video (`ContentEmbedVideo`) — or adding an embed kind. Covers the storage forms (`data-note-id`, `data-attachment-id`, inline `<pre><code class="language-…">`), the editor plugin (`packages/ckeditor5/src/plugins/content_embed/`: `content_embed.ts`, `inline_source.ts`, toolbar, box-size dropdown), the host contract (`contentEmbed.loadAttachment()`, `contentEmbed.loadInline()`), the client box (`ContentEmbed`, `text/utils.ts`), the content component contract (`useEditableEmbed()`, `ContentEmbedToolProvider`, Editable, display modes, fullscreen), reusing the note type's component as canvas and Mermaid do, the read-only paths (AI chat, Markdown preview, print, share), and traps hit (detached content, CodeMirror read-only fixed at creation, the CKEditor `:first-child` separator rule, untitled box sizes, class clashes).---# Developing content embeds@@ -31,7 +31,7 @@ it too — `SplitEditor` → `SplitLayout` + `useMountedPanes()` is the worked ethat are about storage stay separate (the embed's source pane is `CodeEmbedEditor` bound to a`ContentEditor`, the note's is `EditableCode` bound to the note).-## The three storage forms+## The storage formsWhat the text note saves, and what the editor model holds (`contentEmbed` element):@@ -40,6 +40,7 @@ What the text note saves, and what the editor model holds (`contentEmbed` elemen| Included note | `<figure class="include-note" data-note-id="…" [data-block="…"]>` | `noteId`, `block` || Attachment | `<figure class="include-note" data-attachment-id="…">` | `attachmentId` || Inline source | `<pre data-box-size=… [data-display-mode=…] data-hide-title data-editable><code class="language-mermaid">…</code></pre>` | `language`, `source` |+| Video | `<section class="link-embed" data-url=… data-embed-type="youtube" … [data-position=…]>` | the link preview fields: `url`, `embedType`, `title`, `image`, … || Later kind | `<section data-trilium-embed="<kind>" …>fallback</section>` | `unknownContentEmbed`: `embedAttributes`, `embedContent` |All three carry `boxSize`, `hideTitle`, `editable`, `displayMode` (`data-box-size`,@@ -55,6 +56,19 @@ All three carry `boxSize`, `hideTitle`, `editable`, `displayMode` (`data-box-sizits history. It is converted only for languages in`contentEmbed.inlineLanguages` (from `SOURCE_EMBED_TYPES` in `text/config.ts`); a code block ofanother language stays a code block.+- **Video** (`video_embed.ts`, `ContentEmbedVideo`) is the _Embed_ display mode of a link preview+ whose URL has a video (`getLinkPreviewVideoId()` in commons). It keeps the saved form of the+ link preview, so released versions still play it, and adds `data-box-size`, `data-hide-title`,+ `data-position` and `--include-note-width`. Its sizes are Medium and Full+ (`VIDEO_EMBED_BOX_SIZES`); `readVideoEmbedBox()` reads a video saved before as Full and+ untitled, and `createVideoEmbed()` makes a new one Medium at `VIDEO_MEDIUM_WIDTH`, which the+ box size command sets again. Height follows width (`isHeightResizable` is per element). No+ caption. It renders through `contentEmbed.loadVideo()` (`loadVideoEmbed()`, whose title row+ opens the embed menu only in the editor) and has a toolbar of its own (`videoEmbed` in+ `content_embed_toolbar.ts`): Copy URL, the link preview's Display dropdown and ⋮.+ `ReadOnlyText`'s `applyVideoEmbeds()` swaps the section for the same box.+ `createLinkPreview()` in `link_embed_commands.ts` is the one place that picks `linkMention`,+ `linkEmbed` or a video embed for a display mode.- **Legacy blocks** — a `<pre>` without `data-box-size` predates the embed (the old Mermaidplugin). `getModeOfSavedView()` loads it editable, in the view of its`data-trilium-display-mode` or split, at Medium. A saved embed keeps exactly what it has.diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.tsindex 7dd2d9e2ae..6862181eff 100644--- a/apps/client/src/menus/link_context_menu.spec.ts+++ b/apps/client/src/menus/link_context_menu.spec.ts@@ -476,8 +476,9 @@ describe("openContextMenu", () => {selectEmbedAt.mockReset().mockReturnValue(true);hasPlugin = true;state = {- boxSize: "medium", isTitleShown: false, isTitleToggleable: true,- hasCaption: true, isCaptionToggleable: true, isConvertibleToLink: true+ boxSize: "medium", isTitleSupported: true, isTitleShown: false,+ isTitleToggleable: true, isCaptionSupported: true, hasCaption: true,+ isCaptionToggleable: true, isConvertibleToLink: true};mocks.getAttachmentOfNote.mockResolvedValue({ attachmentId: "att-1" });mocks.getAttachmentActionGroups.mockReturnValue([@@ -724,11 +725,35 @@ describe("openContextMenu", () => {expect(mocks.getAttachmentOfNote).not.toHaveBeenCalled();});+ it("leaves out the title and the caption of an embed that has none", async () => {+ embed().removeAttribute("data-attachment-id");+ state = {+ ...state, isTitleSupported: true, isCaptionSupported: false,+ position: "center", isConvertibleToLink: false+ };+ expect((await openOn(editable.querySelector("a"), {})).slice(4)).toMatchObject([+ { kind: "separator" },+ { title: "link_context_menu.include_size" },+ { title: "link_context_menu.include_position" },+ { title: "link_context_menu.show_title", enabled: true, checked: false }+ ]);++ state = { ...state, isTitleSupported: false };+ const items = await openOn(editable.querySelector("a"), {});+ expect(items.slice(4)).toMatchObject([+ { kind: "separator" },+ { title: "link_context_menu.include_size" },+ { title: "link_context_menu.include_position" }+ ]);+ expect(items).toHaveLength(7);+ });+it("disables what the embed cannot do, and offers nothing for no embed", async () => {embed().removeAttribute("data-attachment-id");state = {- boxSize: "tiny", isTitleShown: true, isTitleToggleable: false,- hasCaption: false, isCaptionToggleable: false, isConvertibleToLink: false+ boxSize: "tiny", isTitleSupported: true, isTitleShown: true,+ isTitleToggleable: false, isCaptionSupported: true, hasCaption: false,+ isCaptionToggleable: false, isConvertibleToLink: false};expect((await openOn(editable.querySelector("a"), {})).slice(4)).toMatchObject([{ kind: "separator" },diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.tsindex 5102c65430..b5ff0c28fc 100644--- a/apps/client/src/menus/link_context_menu.ts+++ b/apps/client/src/menus/link_context_menu.ts@@ -350,14 +350,14 @@ function getEmbedItems(embed: MenuEmbed): MenuItem<CommandNames>[] {uiIcon: "bx bx-expand-vertical"}, sizeItems),...getPositionItems(embed),- {+ ...(state.isTitleSupported ? [ {title: t("link_context_menu.show_title"),uiIcon: "bx bx-window-alt",enabled: state.isTitleToggleable,checked: state.isTitleShown,handler: () => runEmbedCommand(embed, "toggleContentEmbedTitle")- },- {+ } ] : []),+ ...(state.isCaptionSupported ? [ {title: t("link_context_menu.show_caption"),uiIcon: "bx bx-captions",enabled: state.isCaptionToggleable,@@ -365,7 +365,7 @@ function getEmbedItems(embed: MenuEmbed): MenuItem<CommandNames>[] {handler: () => runEmbedCommand(embed, "toggleContentEmbedCaption", {focusCaptionOnShow: true})- }+ } ] : [])];}diff --git a/apps/client/src/services/link_embed.ts b/apps/client/src/services/link_embed.tsindex 07f3d89bb0..bd8fe1283a 100644--- a/apps/client/src/services/link_embed.ts+++ b/apps/client/src/services/link_embed.ts@@ -78,9 +78,11 @@ export function unresolvedMetadata(url: string): EmbedMetadata {/*** Draws a block link preview into `container` from stored metadata, making no network request.- * Used by the editor for its link embed widget, with `editable` set.+ * Used by the editor for its link embed widget and video embeds, with `editable` set.*/-export function renderEmbedPreview(container: HTMLElement, meta: EmbedMetadata, editable?: boolean) {+export function renderEmbedPreview(+ container: HTMLElement, meta: LinkPreviewData, editable?: boolean+) {container.innerHTML = renderLinkEmbedHtml(meta, markupOptions(editable));enhanceLinkPreviews(container);}diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex e7d868983d..e7421b183d 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1520,7 +1520,14 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t}}-.include-note {+.link-embed:where([data-embed-type="youtube"]) {+ margin-inline: auto;+ max-width: 100%;+ width: var(--include-note-width, auto);+}++.include-note,+.link-embed:where([data-embed-type="youtube"]) {clear: both;&[data-position="left"] {@@ -1553,7 +1560,7 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t}}-body.mobile .include-note[data-position] {+body.mobile :is(.include-note, .link-embed)[data-position] {float: none;clear: both;margin-inline: 0;diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsxindex 59af0d90d2..2b719cada1 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx@@ -689,6 +689,39 @@ describe("ContentEmbed", () => {expect(container.querySelector(".include-note-fullscreen-controls")).toBeNull();});+ it("titles a video with the menu of its embed, or no menu, and no fullscreen", () => {+ const openMenu = vi.fn();+ const video = { notePath: undefined, boxSize: "medium", contentType: "videoEmbed" };+ renderBox({ ...video, openMenu });+ expect(titleRow()).toEqual([+ "include-note-title-label", "include-note-badges", "include-note-menu"+ ]);+ expect(container.querySelector(".include-note-fullscreen-controls")).toBeNull();++ const menu = button("include-note-menu");+ expect(click(menu).isStopped).toBe(true);+ expect(openMenu).toHaveBeenCalledExactlyOnceWith({ below: menu });+ openMenu.mockClear();+ const row = container.querySelector(".include-note-title-row");+ const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });+ act(() => {+ row?.dispatchEvent(event);+ });+ expect(openMenu).toHaveBeenCalledExactlyOnceWith(event);+ expect(event.defaultPrevented).toBe(true);+ expect(openContextMenu).not.toHaveBeenCalled();++ // Outside a text editor, the embed has no menu of its own.+ act(() => render(null, container));+ renderBox(video);+ expect(titleRow()).toEqual([ "include-note-title-label", "include-note-badges" ]);+ const unhandled = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });+ act(() => {+ container.querySelector(".include-note-title-row")?.dispatchEvent(unhandled);+ });+ expect(unhandled.defaultPrevented).toBe(false);+ });+it("keeps its content behind a backdrop until a click on it focuses what is under it", async () => {const content = element(`<div class="rendered-content"><p>body</p><div tabindex="0"><img></div></div>`diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsxindex 35e8d5cff5..0a16550ea7 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx@@ -3,7 +3,7 @@ import type { RefObject } from "preact";import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";-import linkContextMenu from "../../../menus/link_context_menu";+import linkContextMenu, { type LinkMenuOrigin } from "../../../menus/link_context_menu";import content_renderer from "../../../services/content_renderer";import keyboard_actions from "../../../services/keyboard_actions";import { t } from "../../../services/i18n";@@ -48,6 +48,11 @@ export interface ContentEmbedProps {/** The note opened by the buttons in the title row. */notePath?: string;viewScope?: ViewScope;+ /**+ * Opens the menu of the title row of content that shows no note, such as a video. Without it,+ * that title row has no menu.+ */+ openMenu?: (origin: LinkMenuOrigin) => void;/** Whether the embed shows only some blocks of its note, from a block reference. */isExcerpt?: boolean;/** Gives the focus to the content once mounted, as for a canvas drawing just added. */@@ -69,7 +74,8 @@ export interface TinyContentEmbedProps {/** The title row and the content of an embedded note or attachment. */export default function ContentEmbed({- boxSize, title, content, contentType, notePath, viewScope, isExcerpt, isFocusedOnMount+ boxSize, title, content, contentType, notePath, viewScope, openMenu, isExcerpt,+ isFocusedOnMount}: ContentEmbedProps) {const contentRef = useRef<HTMLDivElement>(null);const bodyRef = useRef<HTMLDivElement>(null);@@ -84,7 +90,9 @@ export default function ContentEmbed({const isExpandable = boxSize === "expandable" && !!title && !!notePath;const hasBackdrop = !isContentActive && !isDraggedOver&& !DIRECT_CONTENT_TYPES.has(contentType);- const hasFullscreen = !isExcerpt && (boxSize === "medium" || boxSize === "full");+ const hasFullscreen = !isExcerpt && !OWN_FULLSCREEN_CONTENT_TYPES.has(contentType)+ && (boxSize === "medium" || boxSize === "full");+ const openTitleMenu = notePath ? getNoteMenu(notePath, viewScope) : openMenu;const toggleExpanded = () => {setIsExpanded(!isOpen);setIsRevealed(false);@@ -114,14 +122,14 @@ export default function ContentEmbed({return (<>- {title && notePath && <div+ {title && <divclassName="include-note-title-row"onClick={(e) => {if (isExpandable && isTogglingClick(e)) {toggleExpanded();}}}- onContextMenu={(e) => openMenuOnRightClick(e, notePath, viewScope)}+ onContextMenu={(e) => openMenuOnRightClick(e, openTitleMenu)}>{isExpandable && (<ActionButton@@ -143,10 +151,10 @@ export default function ContentEmbed({{(!isExpandable || isOpen) && (<DisplayModeButtons contentRef={contentRef} content={content} />)}- <ContentEmbedActionButton+ {notePath && <ContentEmbedActionButtonclassName="include-note-open"action={getOpenInNewTabAction(notePath, viewScope)}- />+ />}{isExcerpt && (<ExcerptEditButtoncontentRef={contentRef}@@ -169,7 +177,7 @@ export default function ContentEmbed({}}/>)}- <MoreActionsButton notePath={notePath} viewScope={viewScope} />+ {openTitleMenu && <MoreActionsButton openMenu={openTitleMenu} />}</div>}<divref={bodyRef}@@ -221,10 +229,11 @@ export default function ContentEmbed({export function TinyContentEmbed({icon, title, description, notePath, viewScope, actions}: TinyContentEmbedProps) {+ const openMenu = getNoteMenu(notePath, viewScope);return (<divclassName="include-note-title-row"- onContextMenu={(e) => openMenuOnRightClick(e, notePath, viewScope)}+ onContextMenu={(e) => openMenuOnRightClick(e, openMenu)}><Icon className="include-note-icon" icon={icon} /><div className="include-note-heading">@@ -238,7 +247,7 @@ export function TinyContentEmbed({action={action}/>))}- <MoreActionsButton notePath={notePath} viewScope={viewScope} />+ <MoreActionsButton openMenu={openMenu} /></div>);}@@ -474,6 +483,9 @@ const SEARCHABLE_CONTENT_TYPES = new Set([ "text", "code", "markdown" ]);/** The content types that take the first click themselves, with no backdrop over them. */const DIRECT_CONTENT_TYPES = new Set([ "extendedCodeBlock" ]);+/** The content types with a fullscreen control of their own, such as a video player. */+const OWN_FULLSCREEN_CONTENT_TYPES = new Set([ "videoEmbed" ]);+/*** The element that a click at (`x`, `y`) would focus: the closest focusable element under that* point in `content`, which is focusable itself.@@ -615,21 +627,30 @@ function isTogglingClick(e: MouseEvent) {&& e.currentTarget instanceof HTMLElement && !findTextEditorAround(e.currentTarget);}+/** Opens the menu of the note at `notePath` from an origin. */+function getNoteMenu(notePath: string, viewScope?: ViewScope) {+ return (origin: LinkMenuOrigin) => {+ void linkContextMenu.openContextMenu(notePath, origin, viewScope);+ };+}+/**- * Opens the menu of the embed for a right click on its title row. The title link is left to the+ * Opens `openMenu` for a right click on the title row of the embed. The title link is left to the* handler of every link, which opens the same menu, or a quick edit with Ctrl.*/-function openMenuOnRightClick(e: MouseEvent, notePath: string, viewScope?: ViewScope) {- if (e.target instanceof Element && e.target.closest("a")) {+function openMenuOnRightClick(+ e: MouseEvent, openMenu: ((origin: LinkMenuOrigin) => void) | undefined+) {+ if (!openMenu || (e.target instanceof Element && e.target.closest("a"))) {return;}e.preventDefault();e.stopPropagation();- void linkContextMenu.openContextMenu(notePath, e, viewScope);+ openMenu(e);}-function MoreActionsButton({ notePath, viewScope }: { notePath: string; viewScope?: ViewScope }) {+function MoreActionsButton({ openMenu }: { openMenu: (origin: LinkMenuOrigin) => void }) {return (<ActionButtonclassName="include-note-menu"@@ -637,8 +658,7 @@ function MoreActionsButton({ notePath, viewScope }: { notePath: string; viewScoptext={t("common.more_actions")}onClick={(e) => {e.stopPropagation();- const origin = linkContextMenu.getOriginBelow(e.currentTarget);- void linkContextMenu.openContextMenu(notePath, origin, viewScope);+ openMenu(linkContextMenu.getOriginBelow(e.currentTarget));}}/>);diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex a69fb39efd..29bb3ea49f 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -49,6 +49,7 @@ import {loadEmbeddedNote,loadInlineEmbed,loadUnknownEmbed,+ loadVideoEmbed,openContentEmbedMenu,refreshEmbeddedNote,setupImageOpening,@@ -247,6 +248,9 @@ export default function EditableText({loadUnknown(wrapper, boxSize) {void loadUnknownEmbed(wrapper, boxSize);},+ loadVideo(preview, wrapper) {+ loadVideoEmbed(preview, wrapper, { hasMenu: true });+ },focusAttachment(attachmentId) {focusedAttachmentIdRef.current = attachmentId;},diff --git a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css b/apps/client/src/widgets/type_widgets/text/LinkEmbed.cssindex e290b76286..f94e395f91 100644--- a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css+++ b/apps/client/src/widgets/type_widgets/text/LinkEmbed.css@@ -114,13 +114,6 @@ body.light-theme .link-embed-favicon-light {display: block;}-.link-embed-preview-wrapper:has(> .link-embed-video) {- display: flex;- justify-content: center;- background: black;- border-radius: 8px;-}-/* ---------- Video embed (YouTube iframe) ---------- */.link-embed-video {@@ -136,9 +129,16 @@ body.light-theme .link-embed-favicon-light {}}-.link-embed-preview-wrapper > .link-embed-video {- padding: 8px;- background: var(--main-background-color);+.include-note.video-embed {+ --_link-embed-top-border-radius: var(--_include-note-content-top-radius);+ --_link-embed-bottom-border-radius: var(--_include-note-content-bottom-radius);++ .include-note-content.type-videoEmbed {+ padding: 0;+ height: auto;+ max-height: none;+ overflow: visible;+ }}.link-embed-video iframe {diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsxindex 444502eb21..198d1a06f3 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx@@ -32,9 +32,14 @@ import ReadOnlyText, { ReadOnlyTextContent } from "./ReadOnlyText";// Imported by ReadOnlyText only for its content styles; irrelevant (and heavy) in happy-dom.vi.mock("@triliumnext/ckeditor5", () => ({}));+vi.mock("../../../services/i18n", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ t: (key: string) => key+}));const {- watchContentEmbeds, stopWatchingEmbeds, loadEmbeddedNote, loadInlineEmbed, loadUnknownEmbed+ watchContentEmbeds, stopWatchingEmbeds, loadEmbeddedNote, loadInlineEmbed, loadUnknownEmbed,+ loadVideoEmbed} = vi.hoisted(() => {const stop = vi.fn();return {@@ -42,7 +47,8 @@ const {stopWatchingEmbeds: stop,loadEmbeddedNote: vi.fn(async () => {}),loadInlineEmbed: vi.fn(async () => {}),- loadUnknownEmbed: vi.fn(async () => {})+ loadUnknownEmbed: vi.fn(async () => {}),+ loadVideoEmbed: vi.fn()};});vi.mock("./utils", async (importOriginal) => ({@@ -50,7 +56,8 @@ vi.mock("./utils", async (importOriginal) => ({watchContentEmbeds,loadEmbeddedNote,loadInlineEmbed,- loadUnknownEmbed+ loadUnknownEmbed,+ loadVideoEmbed}));const disposeStickyTableHeaders = vi.hoisted(() => vi.fn());@@ -594,6 +601,75 @@ describe("ReadOnlyText Mermaid diagrams", () => {});});+describe("ReadOnlyText videos", () => {+ const url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";+ const html = `<section class="link-embed" style="--include-note-width:30em;"`+ + ` data-url="${url}" data-embed-type="youtube" data-title="A video"`+ + ` data-box-size="medium" data-position="wrap-left" data-trilium-block-id="b1">`+ + ` </section>`+ + `<section class="link-embed" data-url="${url}" data-embed-type="youtube"></section>`+ + `<section class="link-embed" data-url="https://example.com/"`+ + ` data-embed-type="opengraph" data-title="A card"></section>`;++ afterEach(() => {+ vi.stubGlobal("glob", { ...glob, device: "desktop" });+ });++ async function mountContent() {+ const container = document.createElement("div");+ document.body.append(container);+ await act(async () => render(<ReadOnlyTextContent html={html} />, container));+ return {+ container,+ async unmount() {+ await act(async () => render(null, container));+ container.remove();+ }+ };+ }++ it("shows each video in the box of the editor, with no menu, and a card in place", async () => {+ loadVideoEmbed.mockClear();+ const { container, unmount } = await mountContent();++ const videos = loadVideoEmbed.mock.calls.map((call: unknown[]) => {+ const [ preview, figure ] = call as [ { url: string; title: string }, HTMLElement ];+ return {+ url: preview.url,+ title: preview.title,+ isMenuless: call.length === 2,+ isInPage: figure.isConnected,+ className: figure.className,+ data: { ...figure.dataset },+ width: figure.style.getPropertyValue("--include-note-width")+ };+ });+ const box = {+ url, isMenuless: true, isInPage: true, className: "include-note video-embed"+ };+ expect(videos).toEqual([+ {+ ...box, title: "A video", width: "30em",+ data: { boxSize: "medium", position: "wrap-left", triliumBlockId: "b1" }+ },+ { ...box, title: null, width: "", data: { boxSize: "full", hideTitle: "true" } }+ ]);+ expect(container.querySelector("section.link-embed > a.link-embed-card")).not.toBeNull();+ await unmount();+ });++ it("draws the videos in place when printing", async () => {+ loadVideoEmbed.mockClear();+ vi.stubGlobal("glob", { ...glob, device: "print" });+ const { container, unmount } = await mountContent();++ expect(loadVideoEmbed).not.toHaveBeenCalled();+ expect(container.querySelectorAll("section.link-embed > .link-embed-video"))+ .toHaveLength(2);+ await unmount();+ });+});+describe("ReadOnlyText extended code blocks", () => {it("shows each extended code block in the embed box of the editor, and no other", async () => {loadInlineEmbed.mockClear();diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex 05461f84c7..0834e48d29 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@ -14,7 +14,8 @@ import {import { CLASSES as TAB_CLASSES } from "@triliumnext/ckeditor5/src/plugins/tabs/constants.js";import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";import {- EXTENDED_CODE_BLOCK_CLASS, EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE+ EXTENDED_CODE_BLOCK_CLASS, EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE, getLinkPreviewVideoId,+ readLinkPreviewData, readVideoEmbedBox, VIDEO_EMBED_CLASS} from "@triliumnext/commons";import clsx from "clsx";import { Ref } from "preact";@@ -49,6 +50,7 @@ import {loadEmbeddedNote,loadInlineEmbed,loadUnknownEmbed,+ loadVideoEmbed,refreshEmbeddedNote,setupImageOpening,watchContentEmbeds@@ -137,7 +139,7 @@ export function ReadOnlyTextContent({html, noteId, ntxId, dir, className, contentRef: externalContentRef, isChanging = false}: ReadOnlyTextContentProps) {// Printing snapshots the page, before an embed box would have drawn its diagram.- const hasDiagramEmbeds = !isChanging && glob.device !== "print";+ const hasEmbedBoxes = !isChanging && glob.device !== "print";const contentRef = useSyncedRef(externalContentRef);const [ codeBlockWordWrap ] = useTriliumOptionBool("codeBlockWordWrap");const [ codeBlockTabWidth ] = useTriliumOption("codeBlockTabWidth");@@ -165,8 +167,8 @@ export function ReadOnlyTextContent({trackPendingRender(container, Promise.all([// First, so that no other pass renders the content of these embeds.applyUnknownEmbeds(container),- ...(hasDiagramEmbeds- ? [ applySourceEmbeds(container) ]+ ...(hasEmbedBoxes+ ? [ applySourceEmbeds(container), applyVideoEmbeds(container) ]: [ rewriteMermaidDiagramsInContainer(container), applyInlineMermaid(container) ]),applyContentEmbeds(container),applyLinkEmbeds(container),@@ -200,12 +202,12 @@ export function ReadOnlyTextContent({dispose();}};- }, [ html, noteId, ntxId, contentRef, hasDiagramEmbeds ]);+ }, [ html, noteId, ntxId, contentRef, hasEmbedBoxes ]);useEffect(() => {if (!contentRef.current) return;return watchContentEmbeds(contentRef.current);- }, [ contentRef, hasDiagramEmbeds ]);+ }, [ contentRef, hasEmbedBoxes ]);useTriliumEvent("entitiesReloaded", () => {if (contentRef.current) applyNoteImageVersions(contentRef.current);@@ -226,7 +228,7 @@ export function ReadOnlyTextContent({return (<RawHtmlBlock// The drawings in place replace the code blocks, which the embed boxes need again.- key={hasDiagramEmbeds ? "embeds" : "drawings"}+ key={hasEmbedBoxes ? "embeds" : "drawings"}containerRef={contentRef}className={clsx("note-detail-readonly-text-content ck-content use-tn-links selectable-text", codeBlockWordWrap && "word-wrap", className)}tabindex={100}@@ -261,6 +263,38 @@ function applyContentEmbeds(container: HTMLDivElement) {return Promise.all(loaded);}+/**+ * Shows each video of a link preview in the embed box the editor shows it in, with its title row+ * and without the menu of the editor.+ */+function applyVideoEmbeds(container: HTMLDivElement) {+ for (const section of container.querySelectorAll<HTMLElement>("section.link-embed")) {+ const getAttribute = (name: string) => section.getAttribute(name);+ const preview = readLinkPreviewData(getAttribute);+ if (!preview || !getLinkPreviewVideoId(preview)) continue;++ const figure = document.createElement("figure");+ figure.className = `include-note ${VIDEO_EMBED_CLASS}`;+ const { boxSize, isTitleHidden } = readVideoEmbedBox(getAttribute);+ figure.dataset.boxSize = boxSize;+ if (isTitleHidden) {+ figure.dataset.hideTitle = "true";+ }+ const { position, triliumBlockId } = section.dataset;+ for (const [ name, value ] of Object.entries({ position, triliumBlockId })) {+ if (value) {+ figure.dataset[name] = value;+ }+ }+ const style = section.getAttribute("style");+ if (style) {+ figure.setAttribute("style", style);+ }+ section.replaceWith(figure);+ loadVideoEmbed(preview, figure);+ }+}+/** Shows each embed of a kind that this version does not know as the editor does: an error box. */function applyUnknownEmbeds(container: HTMLDivElement) {return Promise.all(emptyUnknownEmbeds(container)diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex 62c201cfd7..9bb2af42e6 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -495,6 +495,7 @@ describe("CK config - tables", () => {loadInline: vi.fn(),flushInline: vi.fn(),loadUnknown: vi.fn(),+ loadVideo: vi.fn(),focusAttachment: vi.fn(),getAttachmentHref: vi.fn(async () => "#root/n1?viewMode=attachments&attachmentId=a1"),openMenu: vi.fn(),@@ -506,6 +507,7 @@ describe("CK config - tables", () => {const embed = document.createElement("figure");const wrapper = document.createElement("div");const source = {} as InlineEmbedSource;+ const video = { url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", embedType: "youtube" };const onBlockChange = vi.fn();const host = (await buildConfig(baseOpts({ getContentEmbedHandlers: () => handlers }))).contentEmbed;@@ -517,6 +519,7 @@ describe("CK config - tables", () => {host?.loadInline?.(source, wrapper, "full", { isFocused: true });host?.flushInline?.();host?.loadUnknown?.(wrapper, "small");+ host?.loadVideo?.(video, wrapper);host?.focusAttachment?.("a1");host?.openMenu?.(embed, wrapper);@@ -526,6 +529,7 @@ describe("CK config - tables", () => {expect(first.loadInline).toHaveBeenCalledWith(source, wrapper, "full", { isFocused: true });expect(first.flushInline).toHaveBeenCalledOnce();expect(first.loadUnknown).toHaveBeenCalledWith(wrapper, "small");+ expect(first.loadVideo).toHaveBeenCalledWith(video, wrapper);expect(first.focusAttachment).toHaveBeenCalledWith("a1");expect(first.openMenu).toHaveBeenCalledWith(embed, wrapper);expect(await host?.getAttachmentHref?.("a1")).toBe("#root/n1?viewMode=attachments&attachmentId=a1");diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 007999d250..efa52eb6c9 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -446,6 +446,7 @@ function bindContentEmbedHandlers(loadInline: (...args) => getHandlers()?.loadInline(...args),flushInline: () => getHandlers()?.flushInline(),loadUnknown: (...args) => getHandlers()?.loadUnknown(...args),+ loadVideo: (...args) => getHandlers()?.loadVideo(...args),focusAttachment: (attachmentId) => getHandlers()?.focusAttachment(attachmentId),getAttachmentHref: async (attachmentId) =>(await getHandlers()?.getAttachmentHref(attachmentId)) ?? null,diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.tsindex 6011e668ac..dac24efbe7 100644--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts@@ -38,6 +38,7 @@ vi.mock("../../../services/attachment_actions", () => ({vi.mock("../../../menus/link_context_menu", () => ({default: {openContextMenu: vi.fn(),+ openEmbedContextMenu: vi.fn(),getOriginBelow: vi.fn((anchor: Element, target: Element) => ({ anchor, target }))}}));@@ -62,6 +63,7 @@ import {loadEmbeddedAttachment,loadEmbeddedNote,loadUnknownEmbed,+ loadVideoEmbed,openContentEmbedMenu,refreshEmbeddedNote,setupTodoCheckboxTaps,@@ -425,6 +427,49 @@ describe("loadUnknownEmbed", () => {});});+describe("loadVideoEmbed", () => {+ const url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";++ it("mounts the cover of the video under its title, even before it is in the page", () => {+ const wrapper = document.createElement("div");+ wrapper.className = "include-note-wrapper";++ loadVideoEmbed({+ url,+ embedType: "youtube",+ title: "A <video>",+ image: "api/attachments/abc123/image/youtube-dQw4w9WgXcQ.jpg"+ }, wrapper);++ const { type, props, container } = lastMount();+ expect(type).toBe(ContentEmbed);+ expect(container).toBe(wrapper);+ expect(props).toEqual({+ title: expect.any(HTMLElement),+ content: expect.any(HTMLElement),+ contentType: "videoEmbed"+ });+ expect(props.title?.outerHTML).toBe(`<span><span class="bx bxl-youtube"></span>`+ + `<a href="${url}" target="_blank" rel="noopener noreferrer">A <video></a>`+ + `</span>`);+ expect(props.content.className).toBe("rendered-content");+ const facade = props.content.querySelector(".link-embed-video > .link-embed-video-facade");+ expect(facade?.getAttribute("data-video-id")).toBe("dQw4w9WgXcQ");+ expect(facade?.querySelector("img")?.getAttribute("src"))+ .toBe("api/attachments/abc123/image/youtube-dQw4w9WgXcQ.jpg");+ });++ it("titles a video by its host without a title, and opens its menu in the editor", () => {+ loadVideoEmbed({ url, embedType: "youtube" }, createWrapper(), { hasMenu: true });++ const { props } = lastMount();+ expect(props.title?.textContent).toBe("www.youtube.com");+ const origin = { pageX: 1, pageY: 2, target: null };+ props.openMenu?.(origin);+ expect(linkContextMenu.openEmbedContextMenu).toHaveBeenCalledExactlyOnceWith(origin);+ });+});+describe("the element an embed box is mounted in", () => {it("is a wrapper created in a read-only embed ahead of its caption", async () => {const figure = inPage(document.createElement("figure"));@@ -623,6 +668,23 @@ describe("openContentEmbedMenu", () => {]);});+ it("opens the commands of the embed itself for a source or a video", async () => {+ const anchor = document.createElement("button");+ const source = inPage(document.createElement("figure"));+ source.dataset.language = "mermaid";+ const video = inPage(document.createElement("figure"));+ video.className = "include-note video-embed";++ await openContentEmbedMenu(source, anchor);+ await openContentEmbedMenu(video, anchor);++ expect(vi.mocked(linkContextMenu.openEmbedContextMenu).mock.calls).toEqual([+ [ { anchor, target: source } ],+ [ { anchor, target: video } ]+ ]);+ expect(linkContextMenu.openContextMenu).not.toHaveBeenCalled();+ });+it("opens nothing for an embed of a deleted attachment, or of nothing", async () => {vi.mocked(froca.getAttachment).mockResolvedValue(null);const embed = inPage(document.createElement("figure"));diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex 0e39098d39..c542e43975 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -1,5 +1,7 @@import type { CKTextEditor, InlineEmbedSource } from "@triliumnext/ckeditor5";-import { attachmentIcon } from "@triliumnext/commons";+import {+ attachmentIcon, type LinkPreviewData, safeHostname, safeLinkPreviewHref, VIDEO_EMBED_CLASS+} from "@triliumnext/commons";import { h, type JSX } from "preact";import appContext from "../../../components/app_context";@@ -12,6 +14,7 @@ import { getEmbedCaption, getEmbedCodeView } from "../../../services/content_renimport froca from "../../../services/froca";import { t } from "../../../services/i18n";import link, { ViewScope } from "../../../services/link";+import { renderEmbedPreview } from "../../../services/link_embed";import { getInlineEmbedType } from "../../../services/source_embeds";import utils from "../../../services/utils";import type { InlineSourceSaves } from "./attachment_saves";@@ -252,6 +255,27 @@ export async function loadUnknownEmbed(el: HTMLElement, boxSize: string | undefih(ContentEmbedError, { boxSize, icon: "bx bx-error", text }), getWrapper(el));}+/**+ * Fills an embed box with the player of the video of a link preview, which loads on a click, under+ * a title that links to the video. The title row opens the menu of the embed while `hasMenu`, as in+ * the editor.+ */+export function loadVideoEmbed(+ preview: LinkPreviewData, el: HTMLElement, { hasMenu = false }: { hasMenu?: boolean } = {}+) {+ const content = document.createElement("div");+ content.className = "rendered-content";+ renderEmbedPreview(content, preview, true);+ const box = h(ContentEmbed, {+ title: createVideoTitle(preview),+ content,+ contentType: "videoEmbed",+ ...(hasMenu ? { openMenu: linkContextMenu.openEmbedContextMenu } : {})+ });+ // The editor calls this before the box is in the page, which `mountEmbedBox()` skips.+ void content_renderer.mountInteractiveWidget(box, getWrapper(el));+}+/*** Mounts `box` in the embed `el`. An embed that left the page while it loaded gets no box,* and `content` rendered for it is disposed: `watchContentEmbeds()` has already passed it.@@ -278,6 +302,20 @@ async function mountEmbedBox(await content_renderer.mountInteractiveWidget(box, wrapper);}+/** The title of a video: its icon and a link to it, named by its title or its host. */+function createVideoTitle({ url, title }: LinkPreviewData) {+ const icon = document.createElement("span");+ icon.className = "bx bxl-youtube";+ const link = document.createElement("a");+ link.href = safeLinkPreviewHref(url);+ link.target = "_blank";+ link.rel = "noopener noreferrer";+ link.textContent = title || safeHostname(url);+ const heading = document.createElement("span");+ heading.append(icon, link);+ return heading;+}+function getEmbedBoxSize(el: HTMLElement) {return el.closest<HTMLElement>(".include-note")?.dataset.boxSize;}@@ -305,14 +343,15 @@ function getWrapper(el: HTMLElement) {}/**- * Opens the context menu of the note or attachment that `embed` shows, below `anchor`. The menu- * opens from the embed, so that the text editor that contains it stays focused.+ * Opens the context menu of the note or attachment that `embed` shows, or the commands of an embed+ * of a source or a video, below `anchor`. The menu opens from the embed, so that the text editor+ * that contains it stays focused.*/export async function openContentEmbedMenu(embed: HTMLElement, anchor: HTMLElement) {const { noteId, attachmentId, block, language } = embed.dataset;const origin = linkContextMenu.getOriginBelow(anchor, embed);- if (language) {+ if (language || embed.classList.contains(VIDEO_EMBED_CLASS)) {await linkContextMenu.openEmbedContextMenu(origin);return;}diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex 29ad169013..59d6910d87 100644--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@ -138,7 +138,7 @@"_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>YouTube video</h2><p>Choose <span class=\"tn-icon bx bxl-youtube\"></span> <em>YouTube video</em> to insert a YouTube video that can be watched inside the note. Paste the address of the video, then press <em>Insert video</em> or <kbd>Enter</kbd>. The video is inserted as a link preview in the <em>Embed</em> display mode, described in <a class=\"reference-link\" href=\"#root/_help_UmgZAfcltxkS\">Link Previews</a>. The same action is available as <em>Insert YouTube video</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</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 four 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. <em>Display as</em> is not shown when text is selected, since the link then keeps the selected text.</li><li>Optionally, type a <em>Link title</em> to show instead of the page's own title. A <em>Card</em> also offers a <em>Description</em> to show instead of the page's own description.</li><li>Press <kbd>Enter</kbd> or <em>Insert 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. From the Insert menu, for a YouTube video</h3><p>Choose <span class=\"tn-icon bx bxl-youtube\"></span> <em>YouTube video</em> from the <a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a> menu, or <em>Insert YouTube video</em> from the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. Paste the address of the video and press <em>Insert video</em> or <kbd>Enter</kbd> to insert it as an <em>Embed</em>.</p><h3>4. 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), the <em>Description</em> of a card and how it is displayed. A new address shows the title and description of the new page, unless you type your own.</li><li>A way to switch between the link preview modes (Inline, Card or Embed) as well as to convert it to a normal link instead.<ul><li>The Embed option is only enabled when the URL points to a supported service (YouTube today).</li></ul></li></ul><h2>Where the preview data comes from</h2><p>When you insert a link preview, Trilium fetches metadata once and stores it with the note:</p><ul><li><strong>YouTube URLs</strong>: the title and channel name are fetched via YouTube's public oEmbed endpoint, and the video's thumbnail is downloaded at up to 1280×720.</li><li><strong>All other URLs</strong>: Trilium fetches the page and reads OpenGraph tags (<code>og:title</code>, <code>og:description</code>, <code>og:image</code>, <code>og:site_name</code>), falling back to the page's <code><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><li>The video can be resized and aligned (see <em>Videos</em> below).</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 four 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. <em>Display as</em> is not shown when text is selected, since the link then keeps the selected text.</li><li>Optionally, type a <em>Link title</em> to show instead of the page's own title. A <em>Card</em> also offers a <em>Description</em> to show instead of the page's own description.</li><li>Press <kbd>Enter</kbd> or <em>Insert 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. From the Insert menu, for a YouTube video</h3><p>Choose <span class=\"tn-icon bx bxl-youtube\"></span> <em>YouTube video</em> from the <a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a> menu, or <em>Insert YouTube video</em> from the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. Paste the address of the video and press <em>Insert video</em> or <kbd>Enter</kbd> to insert it as an <em>Embed</em>.</p><h3>4. 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 <em>Inline</em> or <em>Card</em> link preview to select it, and a small toolbar will appear with the following options:</p><ul><li>The normal link operations (opening in a new tab, copying the link, unlinking).</li><li>The <span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> button, which opens the <em>Edit link</em> dialog on the link preview, as does pressing <kbd>Ctrl</kbd>+<kbd>K</kbd> while it is selected. The dialog changes its address, its <em>Link title</em> (especially useful if the title is hidden behind a login screen), the <em>Description</em> of a card and how it is displayed. A new address shows the title and description of the new page, unless you type your own.</li><li>A way to switch between the link preview modes (Inline, Card or Embed) as well as to convert it to a normal link instead.<ul><li>The Embed option is only enabled when the URL points to a supported service (YouTube today).</li></ul></li></ul><h3>Videos</h3><p>A YouTube video shown as an <em>Embed</em> has a size, a position and a title, like an <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>. In the editor, the first click on the video selects it and the next one plays it. The toolbar of a selected video offers:</p><ul><li><span class=\"tn-icon cke cke-trilium-copy\"></span> <em>Copy URL</em>.</li><li>The <em>Display</em> menu, which turns the video into an <em>Inline</em> or <em>Card</em> link preview, or a <em>Plain link</em>.</li><li>The <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu:<ul><li><em>Size</em>: a <em>Medium</em> video can be resized, a <em>Full</em> video takes the width of the note. A new video is <em>Medium</em>. A video inserted in an earlier version is <em>Full</em>.</li><li><em>Position</em>: under <em>Break text</em>, <span class=\"tn-icon cke cke-object-left\"></span> <em>Align left</em>, <span class=\"tn-icon cke cke-object-center\"></span> <em>Align center</em> and <span class=\"tn-icon cke cke-object-right\"></span> <em>Align right</em> place the video on lines of its own, at that side of the note. Under <em>Wrap text</em>, <span class=\"tn-icon cke cke-object-inline-left\"></span> <em>Align left</em> and <span class=\"tn-icon cke cke-object-inline-right\"></span> <em>Align right</em> place it at that side and let the text run beside it. <em>Align center</em> is the default.</li><li><em>Show title</em> shows the title of the video above it, as a link to the video. The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> button of the title opens this same menu.</li></ul></li></ul><p>To resize a <em>Medium</em> video, select it and drag the handle in its bottom-right corner, or its bottom-left corner for a video aligned to the right. The height follows the width. Choosing <em>Medium</em> again returns the video to its first size.</p><p>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the video keeps its width and position, but not its title. In the mobile layout, a video with a position other than <em>Align center</em> takes the full width.</p><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><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>Insert 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, so the dialog does not offer <em>Display as</em>.</li><li>Alternatively, simply paste (<kbd>Ctrl</kbd>+<kbd>V</kbd>) over the selected text to turn it into a link.</li></ul><p>Once a link is inserted:</p><ul><li>The text inside the link can be changed if needed but the link itself will remain.</li><li>To modify the link, click on the link to display the popup and press the <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><p>Since v0.107.0, clicking an internal link while editing a text note shows its popup instead, as clicking an external link does:</p><ul><li><em>Open note</em> opens the linked note, or <em>Open attachment</em> for a link to an attachment. A link into the same note reads <em>Jump to heading</em>, <em>Jump to block</em> or <em>Jump to anchor</em> instead, and scrolls to it without leaving the note.</li><li><span class=\"tn-icon cke cke-trilium-copy\"></span> <em>Copy URL</em> copies the address of the link.</li><li><span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> changes the link, as described below.</li><li><span class=\"tn-icon cke cke-unlink\"></span> <em>Unlink</em> turns the link into plain text.</li></ul><p>To open the note in a new tab without the popup, <kbd>Ctrl</kbd>+click or double-click the link. The preview does not show while the popup is open.</p><h2>Inserting internal links</h2><p>Internal links can be created at the current position in a text note by:</p><ol><li>Pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <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, depending on the <em>Link title</em> field of the dialog:</p><ol><li>When the link title is not set, the link will display the title of the note. If the title of the note gets changed, the link will be renamed automatically to the new name.<ol><li>This is sometimes also called \"reference link\".</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>When a link title is typed, the link shows that text instead.<ol><li>This will create a traditional hyperlink, where the text of the link can be different from the note title.</li></ol></li></ol><p>Since v0.107.0, to change a link, click it and press the <span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> button in its popup. For a link with a title of its own, placing the cursor inside it and pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class=\"tn-icon cke cke-trilium\"></span> button works too. The <em>Edit link</em> dialog opens on the linked note, with its anchor and, for a link with a title of its own, the link's text; <em>Save link</em> changes the whole link. Emptying the <em>Link title</em> there turns the link into one that displays the title of the note, and typing one gives it a title of its own.</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>",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 8815bb471e..428ddb608a 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@@ -10,6 +10,7 @@ A link preview can be displayed in one of three modes:* **Embed** — a block-level interactive embed.* Currently supported for YouTube videos, which render interactively (via an `iframe`).* 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.+ * The video can be resized and aligned (see _Videos_ below).<div class="trilium-multicolumn-layout" data-trilium-column-ratios="1-1-1"><div class="trilium-multicolumn-column">@@ -74,13 +75,28 @@ When _Autogenerate link previews_ is turned off, the tabs are saved as a list of## Altering an existing link preview-Click on an inserted link preview to select it, and a small toolbar will appear with the following options:+Click on an inserted _Inline_ or _Card_ 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).* 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), the _Description_ of a card and how it is displayed. A new address shows the title and description of the new page, unless you type your own.* 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).+### Videos++A YouTube video shown as an _Embed_ has a size, a position and a title, like an <a class="reference-link" href="Include%20Note.md">Include Note</a>. In the editor, the first click on the video selects it and the next one plays it. The toolbar of a selected video offers:++* <span class="tn-icon cke cke-trilium-copy"></span> _Copy URL_.+* The _Display_ menu, which turns the video into an _Inline_ or _Card_ link preview, or a _Plain link_.+* The <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu:+ * _Size_: a _Medium_ video can be resized, a _Full_ video takes the width of the note. A new video is _Medium_. A video inserted in an earlier version is _Full_.+ * _Position_: under _Break text_, <span class="tn-icon cke cke-object-left"></span> _Align left_, <span class="tn-icon cke cke-object-center"></span> _Align center_ and <span class="tn-icon cke cke-object-right"></span> _Align right_ place the video on lines of its own, at that side of the note. Under _Wrap text_, <span class="tn-icon cke cke-object-inline-left"></span> _Align left_ and <span class="tn-icon cke cke-object-inline-right"></span> _Align right_ place it at that side and let the text run beside it. _Align center_ is the default.+ * _Show title_ shows the title of the video above it, as a link to the video. The <span class="tn-icon bx bx-dots-vertical-rounded"></span> button of the title opens this same menu.++To resize a _Medium_ video, select it and drag the handle in its bottom-right corner, or its bottom-left corner for a video aligned to the right. The height follows the width. Choosing _Medium_ again returns the video to its first size.++On a [shared page](../../Advanced%20Usage/Sharing.md), the video keeps its width and position, but not its title. In the mobile layout, a video with a position other than _Align center_ takes the full width.+## Where the preview data comes fromWhen you insert a link preview, Trilium fetches metadata once and stores it with the note:diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.tsindex b3c87ecc58..ccd69bbb2e 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts@@ -1015,7 +1015,8 @@ describe("ContentEmbed with attachments", () => {const states = [ embed, note, tiny, unsized ].map((wrapper) => plugin.getEmbedStateAt(wrapper));const notEditable = {- isEditable: false, isEditableToggleable: false, displayMode: null, position: null+ isEditable: false, isEditableToggleable: false, displayMode: null, position: null,+ isTitleSupported: true, isCaptionSupported: true};expect(states).toEqual([ {...notEditable, boxSize: "small", isTitleShown: true, isTitleToggleable: true,diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex c29ddd9ba0..c0cc625d91 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -30,7 +30,8 @@ import dockLeftIcon from 'boxicons/svg/solid/bxs-dock-left.svg?raw';import windowIcon from 'boxicons/svg/regular/bx-window-alt.svg?raw';import noteIcon from '../../icons/note.svg?raw';import {- encodeBlockParameter, EXTENDED_CODE_BLOCK_CLASS, normalizeMimeTypeForCKEditor, parseBlockRange+ encodeBlockParameter, EXTENDED_CODE_BLOCK_CLASS, type LinkPreviewData,+ normalizeMimeTypeForCKEditor, parseBlockRange, VIDEO_EMBED_BOX_SIZES, VIDEO_EMBED_CLASS} from '@triliumnext/commons';import { getAttachmentId, getNoteId } from '../referencelink.js';import ResizableWidgets, {@@ -44,6 +45,7 @@ import ContentEmbedInlineSource, {} from './inline_source.js';import './nested_editor_events.js';import UnknownContentEmbed from './unknown_embed.js';+import ContentEmbedVideo, { isVideoEmbed, VIDEO_MEDIUM_WIDTH } from './video_embed.js';export const COMMAND_NAME = 'insertContentEmbed';export const BOX_SIZE_COMMAND_NAME = 'contentEmbedBoxSize';@@ -150,9 +152,13 @@ export interface ContentEmbedState {boxSize: BoxSizeValue | null;/** Where the embed is placed in the text, for content that has positions, otherwise `null`. */position: PositionValue | null;+ /** Whether the embed has a title row, which an embed of a source has not. */+ isTitleSupported: boolean;/** Whether the title shows, which a Tiny or an Expandable embed always does. */isTitleShown: boolean;isTitleToggleable: boolean;+ /** Whether the embed can have a caption, which an embed of a source or a video cannot. */+ isCaptionSupported: boolean;hasCaption: boolean;isCaptionToggleable: boolean;isConvertibleToLink: boolean;@@ -206,7 +212,7 @@ export default class ContentEmbed extends Plugin {static get requires() {return [ContentEmbedEditing, ContentEmbedUI, ContentEmbedInlineSource, EmbedHistory,- UnknownContentEmbed+ UnknownContentEmbed, ContentEmbedVideo];}@@ -267,8 +273,10 @@ export default class ContentEmbed extends Plugin {: null,boxSize: embed.getAttribute( 'boxSize' ) as BoxSizeValue | undefined ?? null,position: hasEmbedPositions( editor, embed ) ? getEmbedPosition( embed ) : null,+ isTitleSupported: hasTitleRow( embed ),isTitleShown: !isTitleToggleable || !embed.getAttribute( 'hideTitle' ),isTitleToggleable,+ isCaptionSupported: hasCaptionSupport( embed ),hasCaption: !!getCaption( embed ),isCaptionToggleable: isEmbedCaptionToggleable( editor, embed ),isConvertibleToLink: isEmbedConvertibleToLink( editor, embed )@@ -517,7 +525,8 @@ class ContentEmbedEditing extends Plugin {editor.plugins.get( ResizableWidgets ).register( 'contentEmbed', {propertyPrefix: '--include-note',isWidthResizable: true,- isHeightResizable: true,+ // A video takes its height from its width.+ isHeightResizable: embed => !isVideoEmbed( embed ),getAnchor: getEmbedAnchor,heightTarget: '.include-note-content',minWidth: MIN_EMBED_SIZE.width,@@ -642,13 +651,10 @@ class ContentEmbedEditing extends Plugin {const boxSize = modelElement.getAttribute( 'boxSize' ) as string | undefined;- const extendedClass = isExtendedCodeBlock( editor, modelElement )- ? ' ' + EXTENDED_CODE_BLOCK_CLASS- : '';const figure = viewWriter.createContainerElement( 'figure', {- class: 'include-note box-size-' + boxSize + extendedClass,+ class: getEditingClasses( editor, modelElement ),...getEmbeddedEntityAttributes( modelElement ),- 'data-box-size': boxSize,+ ...( boxSize ? { 'data-box-size': boxSize } : {} ),...getFlagAttributes( modelElement ),...getDisplayModeAttributes( modelElement ),...getPositionAttributes( modelElement ),@@ -674,7 +680,9 @@ class ContentEmbedEditing extends Plugin {// The label is announced by screen readers; lowercase to match the "image widget" /// "table widget" labels CKEditor gives its own widgets.return toWidget( figure, viewWriter, {- label: editor.t( 'include note widget' ),+ label: isVideoEmbed( modelElement )+ ? editor.t( 'link embed widget' )+ : editor.t( 'include note widget' ),hasSelectionHandle: true} );}@@ -862,7 +870,8 @@ class ContentEmbedBoxSizeCommand extends Command {/*** Sets the box size of the selected embed and resets its height. Tiny and Full reset the- * width too. Tiny takes the caption away, and a larger size shows it again.+ * width too, and Medium sets the width of a Medium video. Tiny takes the caption away, and a+ * larger size shows it again.*/override execute( options: { value: BoxSizeValue } ) {const editor = this.editor;@@ -875,6 +884,8 @@ class ContentEmbedBoxSizeCommand extends Command {writer.removeAttribute( SIZE_ATTRIBUTES.height, embedElement );if ( !RESIZABLE_BOX_SIZES.includes( options.value ) ) {writer.removeAttribute( SIZE_ATTRIBUTES.width, embedElement );+ } else if ( isVideoEmbed( embedElement ) ) {+ writer.setAttribute( SIZE_ATTRIBUTES.width, VIDEO_MEDIUM_WIDTH, embedElement );}if ( options.value === 'tiny' ) {@@ -1263,7 +1274,17 @@ export function isContentEmbed(/** Whether the title of `embed` can be hidden: a Tiny or an Expandable one always shows it. */function isEmbedTitleToggleable( embed: ModelElement ) {const boxSize = embed.getAttribute( 'boxSize' );- return boxSize !== 'tiny' && boxSize !== 'expandable' && !isInlineSourceEmbed( embed );+ return boxSize !== 'tiny' && boxSize !== 'expandable' && hasTitleRow( embed );+}++/** Whether `embed` has a title row: an embed of a source has none. */+function hasTitleRow( embed: ModelElement ) {+ return !isInlineSourceEmbed( embed );+}++/** Whether `embed` can have a caption: an embed of a source or of a video has none. */+function hasCaptionSupport( embed: ModelElement ) {+ return !isInlineSourceEmbed( embed ) && !isVideoEmbed( embed );}/** Whether the content of `embed` has an editable mode, which its content type opts in to. */@@ -1273,7 +1294,13 @@ function isEmbedEditableToggleable( editor: Editor, embed: ModelElement ) {/** The box sizes that `embed` can take, or all of them without an embed. */export function getEmbedBoxSizes( embed: ModelElement | null ): readonly BoxSizeValue[] {- return embed && isInlineSourceEmbed( embed ) ? INLINE_BOX_SIZES : BOX_SIZES;+ if ( !embed ) {+ return BOX_SIZES;+ }+ if ( isVideoEmbed( embed ) ) {+ return VIDEO_EMBED_BOX_SIZES;+ }+ return isInlineSourceEmbed( embed ) ? INLINE_BOX_SIZES : BOX_SIZES;}/** Whether the content of `embed` has display modes, which its content type opts in to. */@@ -1297,9 +1324,12 @@ export function toDisplayMode( value: unknown ): DisplayModeValue | null {return DISPLAY_MODES.find( mode => mode === value ) ?? null;}-/** Whether the content of `embed` can be positioned, which its content type opts in to. */+/**+ * Whether the content of `embed` can be positioned: a video can, other content when its type opts+ * in to it.+ */function hasEmbedPositions( editor: Editor, embed: ModelElement ) {- return !!getEmbedTools( editor, embed )?.hasPositions;+ return isVideoEmbed( embed ) || !!getEmbedTools( editor, embed )?.hasPositions;}/** Where `embed` is placed in the text: its saved position, or centered. */@@ -1320,9 +1350,9 @@ export function getEmbedAnchor( embed: ModelElement ): ResizeAnchor {return position === 'right' || position === 'wrap-right' ? 'right' : 'center';}-/** Whether `embed` can have a caption. A Tiny embed has none. */+/** Whether `embed` can have a caption now. A Tiny embed has none. */function isEmbedCaptionToggleable( editor: Editor, embed: ModelElement ) {- return embed.getAttribute( 'boxSize' ) !== 'tiny' && !isInlineSourceEmbed( embed )+ return embed.getAttribute( 'boxSize' ) !== 'tiny' && hasCaptionSupport( embed )&& editor.model.schema.checkChild( embed, 'caption' );}@@ -1351,6 +1381,22 @@ function getWrapperIndex( viewElement: ViewElement ) {.findIndex( child => child.is( 'uiElement' ) && child.hasClass( 'include-note-wrapper' ) );}+/** The classes of the view of `embed` in the editor. */+function getEditingClasses( editor: Editor, embed: ModelElement ) {+ const boxSize = embed.getAttribute( 'boxSize' ) as string | undefined;+ const classes = [ 'include-note' ];+ if ( boxSize ) {+ classes.push( `box-size-${ boxSize }` );+ }+ if ( isExtendedCodeBlock( editor, embed ) ) {+ classes.push( EXTENDED_CODE_BLOCK_CLASS );+ }+ if ( isVideoEmbed( embed ) ) {+ classes.push( VIDEO_EMBED_CLASS );+ }+ return classes.join( ' ' );+}+/** Adds `node`, when it is an embed, and every embed inside it to `embeds`. */function addContentEmbeds(embeds: Set<ModelElement>,@@ -1598,6 +1644,10 @@ function loadEmbeddedContent(editor.plugins.get( ContentEmbedInlineSource ).load( element, wrapper, boxSize );return;}+ if ( isVideoEmbed( element ) ) {+ editor.plugins.get( ContentEmbedVideo ).load( element, wrapper );+ return;+ }const host = editor.config.get( 'contentEmbed' );const attachmentId = element.getAttribute( 'attachmentId' ) as string | undefined;@@ -1837,6 +1887,8 @@ export interface ContentEmbedHost {sanitizeHtml( html: string ): string;/** Fills `wrapper` with the placeholder of an embed of an unknown kind. */loadUnknown( wrapper: HTMLElement, boxSize: string | undefined ): void;+ /** Fills `wrapper` with the player of the video of a link preview. */+ loadVideo( preview: LinkPreviewData, wrapper: HTMLElement ): void;/** Opens the context menu of what `embed` shows, below `anchor`. */openMenu( embed: HTMLElement, anchor: HTMLElement ): void;/** The buttons that what `embed` shows adds to the toolbar of the embed, or `null`. */diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.tsindex de27a5d6d6..44cf842258 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.spec.ts@@ -6,6 +6,9 @@ import { beforeEach, describe, expect, it } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";import LinkEmbed from "../link_embed/link_embed.js";+import {+ LinkEmbedCopyUrlButton, LinkEmbedDisplayDropdown+} from "../link_embed/link_embed_toolbar.js";import ContentEmbed, {CONVERT_EMBED_TO_LINK_COMMAND,CONTENT_EMBED_MENU,@@ -106,6 +109,48 @@ describe("ContentEmbedToolbar", () => {expect(requires).toContain(ContentEmbedPositionDropdown);expect(requires).toContain(ContentEmbedTools);expect(requires).toContain(ExtendedCodeBlock);+ expect(requires).toContain(LinkEmbedCopyUrlButton);+ expect(requires).toContain(LinkEmbedDisplayDropdown);+ });++ it("gives a video the copy and display items of a link preview, and its menu", () => {+ const repository = editor.plugins.get(WidgetToolbarRepository) as unknown as {+ _toolbarDefinitions: Map<string, {+ itemsConfig: string[];+ getRelatedElement: (selection: unknown) => unknown;+ positions: PositioningFunction[];+ }>;+ };+ const definition = repository._toolbarDefinitions.get("videoEmbed");+ expect(definition?.itemsConfig).toEqual([+ "linkEmbedCopyUrl", "|", "linkEmbedDisplayDropdown", CONTENT_EMBED_MENU+ ]);++ editor.setData(`<section class="link-embed" data-position="right"`+ + ` data-url="https://youtube.com/watch?v=abc12345678" data-embed-type="youtube">`+ + `</section><p>Text</p>`);+ editor.model.change((writer) => {+ const embed = editor.model.document.getRoot()?.getChild(0);+ if (embed?.is("element")) {+ writer.setSelection(embed, "on");+ }+ });+ const selection = editor.editing.view.document.selection;+ expect(definition?.getRelatedElement(selection))+ .toBe(editor.editing.view.document.getRoot()?.getChild(0));+ expect(getRelatedElementFn(editor)(selection)).toBeNull();++ const target = new Rect({+ left: 100, top: 300, right: 400, bottom: 500, width: 300, height: 200+ });+ const balloon = new Rect({+ left: 0, top: 0, right: 200, bottom: 40, width: 200, height: 40+ });+ expect(definition?.positions[0](target, balloon, new Rect(window)))+ .toMatchObject({ name: "arrow_se", left: 200 });++ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");+ expect(definition?.getRelatedElement(editor.editing.view.document.selection)).toBeNull();});it("offers Editable, the display modes, the content's tools, then the embed's items", () => {diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.tsindex c39fc9b687..79bf5c9fe5 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed_toolbar.ts@@ -1,8 +1,12 @@+import { VIDEO_EMBED_CLASS } from "@triliumnext/commons";import {BalloonPanelView, isWidget, Plugin, type PositioningFunction, type ViewDocumentSelection,type ViewElement, WidgetToolbarRepository} from "ckeditor5";+import {+ LinkEmbedCopyUrlButton, LinkEmbedDisplayDropdown+} from "../link_embed/link_embed_toolbar.js";import type { ResizeAnchor } from "../resizable_widgets/resizable_widgets.js";import ContentEmbed, {CONVERT_EMBED_TO_LINK_COMMAND,@@ -29,7 +33,8 @@ export default class ContentEmbedToolbar extends Plugin {static get requires() {return [WidgetToolbarRepository, ContentEmbed, ContentEmbedBoxSizeDropdown,- ContentEmbedPositionDropdown, ContentEmbedTools, ExtendedCodeBlock+ ContentEmbedPositionDropdown, ContentEmbedTools, ExtendedCodeBlock,+ LinkEmbedCopyUrlButton, LinkEmbedDisplayDropdown] as const;}@@ -37,11 +42,20 @@ export default class ContentEmbedToolbar extends Plugin {const editor = this.editor;const widgetToolbarRepository = editor.plugins.get(WidgetToolbarRepository);const getAnchor = () => {- const embed = findRelatedEmbed(editor.editing.view.document.selection);+ const selection = editor.editing.view.document.selection;+ const embed = findRelatedEmbed(selection) ?? findRelatedVideo(selection);const modelEmbed = embed && editor.editing.mapper.toModelElement(embed);return modelEmbed ? getEmbedAnchor(modelEmbed) : "center";};+ // A video has the copy and display items of a link preview, and the menu of an embed.+ widgetToolbarRepository.register("videoEmbed", {+ items: [ "linkEmbedCopyUrl", "|", "linkEmbedDisplayDropdown", CONTENT_EMBED_MENU ],+ balloonClassName: "ck-toolbar-container include-note-toolbar",+ positions: getToolbarPositions(getAnchor),+ getRelatedElement: findRelatedVideo+ });+widgetToolbarRepository.register("contentEmbed", {items: [TOGGLE_EDITABLE_COMMAND_NAME,@@ -81,8 +95,15 @@ function findRelatedEmbed(selection: ViewDocumentSelection) {return null;}+/** The video embed that the selection is on, which has a toolbar of its own. */+function findRelatedVideo(selection: ViewDocumentSelection) {+ const selected = selection.getSelectedElement();+ return selected && isWidget(selected) && selected.hasClass(VIDEO_EMBED_CLASS) ? selected : null;+}+function isContentEmbedWidget(element: ViewElement): boolean {- return isWidget(element) && element.hasClass("include-note");+ return isWidget(element) && element.hasClass("include-note")+ && !element.hasClass(VIDEO_EMBED_CLASS);}/**diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.tsindex d844491f58..42863fcc31 100644--- a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts@@ -299,6 +299,9 @@ describe("ContentEmbedInlineSource", () => {expect(editor.commands.get(TOGGLE_TITLE_COMMAND_NAME)?.isEnabled).toBe(false);expect(editor.commands.get(TOGGLE_CAPTION_COMMAND_NAME)?.isEnabled).toBe(false);expect(editor.commands.get(CONVERT_EMBED_TO_LINK_COMMAND)?.isEnabled).toBe(false);+ const figure = editor.editing.view.getDomRoot()?.querySelector(".include-note");+ expect(figure && editor.plugins.get(ContentEmbed).getEmbedStateAt(figure))+ .toMatchObject({ isTitleSupported: false, isCaptionSupported: false });});describe("extended code blocks", () => {diff --git a/packages/ckeditor5/src/plugins/content_embed/video_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/video_embed.spec.tsnew file mode 100644index 0000000000..96aae86996--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/video_embed.spec.ts@@ -0,0 +1,218 @@+import { type ClassicEditor, Essentials, getLabel, Paragraph, Undo, Widget } from "ckeditor5";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../../../test/editor-kit.js";+import { registerTestCleanup } from "../../../test/globals-test-kit.js";+import LinkEmbed from "../link_embed/link_embed.js";+import { SIZE_ATTRIBUTES } from "../resizable_widgets/resizable_widgets.js";+import ContentEmbed, {+ BOX_SIZE_COMMAND_NAME,+ POSITION_COMMAND_NAME,+ TOGGLE_CAPTION_COMMAND_NAME,+ TOGGLE_TITLE_COMMAND_NAME+} from "./content_embed.js";+import { isVideoEmbed, VIDEO_MEDIUM_WIDTH } from "./video_embed.js";++const VIDEO_URL = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";+const THUMBNAIL = "api/attachments/abc123/image/youtube-dQw4w9WgXcQ.jpg";+const PREVIEW_ATTRIBUTES = `data-url="${VIDEO_URL}" data-embed-type="youtube"`+ + ` data-title="A video" data-image="${THUMBNAIL}"`;+/** A video saved before videos were embeds. */+const SAVED_PREVIEW = `<section class="link-embed" ${PREVIEW_ATTRIBUTES}> </section>`;++describe("ContentEmbedVideo", () => {+ let editor: ClassicEditor;+ let loadVideo: ReturnType<typeof vi.fn>;++ beforeEach(async () => {+ loadVideo = vi.fn();+ editor = await createTestEditor([+ Essentials, Paragraph, Undo, Widget, ContentEmbed, LinkEmbed+ ], {+ contentEmbed: { loadVideo, sanitizeHtml: (html: string) => html }+ });+ });++ function getBlock(index = 0) {+ const block = editor.model.document.getRoot()?.getChild(index);+ if (!block?.is("element")) {+ throw new Error(`Expected a block at ${index}.`);+ }+ return block;+ }++ function getFigure() {+ const figure = editor.editing.view.getDomRoot()?.querySelector("figure.include-note");+ if (!(figure instanceof HTMLElement)) {+ throw new Error("Expected the figure of the embed.");+ }+ return figure;+ }++ function selectBlock(index: number) {+ editor.model.change((writer) => writer.setSelection(getBlock(index), "on"));+ }++ it("loads the link preview of a video as a Full untitled embed, and saves its box", () => {+ editor.setData(SAVED_PREVIEW);++ const embed = getBlock();+ expect(embed.name).toBe("contentEmbed");+ expect(isVideoEmbed(embed)).toBe(true);+ expect(Object.fromEntries(embed.getAttributes())).toEqual({+ url: VIDEO_URL,+ embedType: "youtube",+ title: "A video",+ image: THUMBNAIL,+ boxSize: "full",+ hideTitle: true+ });+ expect(editor.getData()).toBe(`<section class="link-embed" ${PREVIEW_ATTRIBUTES}`+ + ` data-box-size="full" data-hide-title="true"> </section>`);+ });++ it("leaves a card, and an embed type without a video, to the link preview", () => {+ editor.setData(+ `<section class="link-embed" data-url="${VIDEO_URL}" data-embed-type="opengraph">`+ + `</section><section class="link-embed" data-url="https://example.com/"`+ + ` data-embed-type="youtube"></section>`+ + `<section class="link-embed" data-url="${VIDEO_URL}"></section>`+ + `<section class="link-embed" data-embed-type="youtube"></section>`+ );++ expect([ 0, 1, 2, 3 ].map((index) => getBlock(index).name))+ .toEqual([ "linkEmbed", "linkEmbed", "linkEmbed", "linkEmbed" ]);+ });++ it("makes no embed of a section of an embed kind, or where the schema allows none", () => {+ editor.setData(`<section class="link-embed" data-trilium-embed="later"`+ + ` data-url="${VIDEO_URL}" data-embed-type="youtube"></section>`);+ expect(getBlock().name).toBe("unknownContentEmbed");++ editor.model.schema.addChildCheck((_context, definition) =>+ definition.name === "contentEmbed" ? false : undefined);+ editor.setData(SAVED_PREVIEW);+ expect(getBlock().name).toBe("linkEmbed");+ expect(loadVideo).not.toHaveBeenCalled();+ });++ it("keeps the box, the position and the width on the section, and drops what it holds", () => {+ const attributes = `class="link-embed" style="--include-note-width:30em;"`+ + ` data-url="${VIDEO_URL}" data-embed-type="youtube" data-box-size="medium"`+ + ` data-position="wrap-left"`;+ editor.setData(`<section ${attributes}><a href="${VIDEO_URL}">A video</a></section>`);++ const embed = getBlock();+ expect(embed.getAttribute("boxSize")).toBe("medium");+ expect(embed.getAttribute("hideTitle")).toBeUndefined();+ expect(embed.getAttribute("position")).toBe("wrap-left");+ expect(embed.getAttribute(SIZE_ATTRIBUTES.width)).toBe("30em");+ expect(embed.childCount).toBe(0);+ expect(editor.getData()).toBe(`<section ${attributes}> </section>`);+ });++ it("has the host render the player in an embed of its box", () => {+ editor.setData(SAVED_PREVIEW);++ const figure = getFigure();+ expect([ ...figure.classList ]).toEqual(expect.arrayContaining([+ "include-note", "video-embed", "box-size-full"+ ]));+ expect(figure.dataset).toMatchObject({ boxSize: "full", hideTitle: "true" });+ const view = editor.editing.mapper.toViewElement(getBlock());+ expect(view && getLabel(view)).toMatch(/^link embed widget\./);+ expect(loadVideo).toHaveBeenCalledExactlyOnceWith({+ url: VIDEO_URL,+ embedType: "youtube",+ title: "A video",+ image: THUMBNAIL+ }, figure.querySelector(":scope > .include-note-wrapper"));+ });++ it("has the Medium and Full sizes, a title, a position and no caption", () => {+ editor.setData(`<p>Text</p>${SAVED_PREVIEW}`);+ selectBlock(1);++ const commands = [+ BOX_SIZE_COMMAND_NAME, TOGGLE_TITLE_COMMAND_NAME, TOGGLE_CAPTION_COMMAND_NAME,+ POSITION_COMMAND_NAME+ ];+ expect(commands.map((name) => editor.commands.get(name)?.isEnabled))+ .toEqual([ true, true, false, true ]);+ const contentEmbed = editor.plugins.get(ContentEmbed);+ expect(contentEmbed.getBoxSizes(getFigure()))+ .toEqual([ { value: "medium", label: "Medium" }, { value: "full", label: "Full" } ]);+ expect(contentEmbed.getEmbedStateAt(getFigure())).toMatchObject({+ boxSize: "full", position: "center", isTitleSupported: true, isTitleShown: false,+ isTitleToggleable: true, isCaptionSupported: false+ });++ editor.execute(TOGGLE_TITLE_COMMAND_NAME);+ expect(getFigure().hasAttribute("data-hide-title")).toBe(false);+ expect(editor.getData()).not.toContain("data-hide-title");++ editor.execute(POSITION_COMMAND_NAME, { value: "right" });+ expect(editor.getData()).toContain(` data-position="right"`);+ });++ it("is resized in width at Medium, which a box size sets to its own width", () => {+ editor.setData(`<p>Text</p>${SAVED_PREVIEW}`);+ selectBlock(1);+ const classes = () => [ ...getFigure().classList ];+ expect(classes()).not.toContain("ck-widget_resizable");++ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "medium" });+ expect(getBlock(1).getAttribute(SIZE_ATTRIBUTES.width)).toBe(VIDEO_MEDIUM_WIDTH);+ expect(classes()).toEqual(expect.arrayContaining([+ "ck-widget_resizable", "ck-widget_fixed-height"+ ]));++ editor.model.change((writer) => {+ writer.setAttribute(SIZE_ATTRIBUTES.width, "20em", getBlock(1));+ });+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "medium" });+ expect(getBlock(1).getAttribute(SIZE_ATTRIBUTES.width)).toBe(VIDEO_MEDIUM_WIDTH);++ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "full" });+ expect(getBlock(1).hasAttribute(SIZE_ATTRIBUTES.width)).toBe(false);+ expect(classes()).not.toContain("ck-widget_resizable");+ });++ it("takes a new width from its corner at Medium, its only handle", () => {+ const capture = vi.spyOn(Element.prototype, "setPointerCapture")+ .mockImplementation(() => {});+ registerTestCleanup(() => capture.mockRestore());+ editor.setData(`<p>Text</p>${SAVED_PREVIEW}`);+ selectBlock(1);+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "medium" });+ const getHandle = (name: string) => {+ const handle = getFigure().querySelector(`.ck-widget__resize-handle_${name}`);+ if (!handle) {+ throw new Error(`Expected the ${name} handle.`);+ }+ return handle;+ };+ const drag = (handle: Element, x: number, y: number) => {+ handle.dispatchEvent(new PointerEvent("pointerdown", {+ bubbles: true, cancelable: true, pointerId: 1, isPrimary: true,+ clientX: 300, clientY: 300+ }));+ window.dispatchEvent(new PointerEvent("pointermove", {+ pointerId: 1, clientX: x, clientY: y+ }));+ window.dispatchEvent(new PointerEvent("pointerup", { pointerId: 1 }));+ };++ expect([ "width", "height", "corner" ]+ .map((name) => getComputedStyle(getHandle(name)).display))+ .toEqual([ "none", "none", "block" ]);+ drag(getHandle("height"), 300, 400);+ expect(getBlock(1).getAttribute(SIZE_ATTRIBUTES.width)).toBe(VIDEO_MEDIUM_WIDTH);++ drag(getHandle("corner"), 260, 360);+ const width = getBlock(1).getAttribute(SIZE_ATTRIBUTES.width);+ expect(width).toMatch(/^\d+(\.\d+)?em$/);+ expect(width).not.toBe(VIDEO_MEDIUM_WIDTH);+ expect(getBlock(1).hasAttribute(SIZE_ATTRIBUTES.height)).toBe(false);+ });+});diff --git a/packages/ckeditor5/src/plugins/content_embed/video_embed.ts b/packages/ckeditor5/src/plugins/content_embed/video_embed.tsnew file mode 100644index 0000000000..4e29cd67ee--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/video_embed.ts@@ -0,0 +1,136 @@+import {+ getLinkPreviewVideoId, LINK_PREVIEW_DATA_ATTRIBUTES, type LinkPreviewData, readLinkPreviewData,+ readVideoEmbedBox+} from "@triliumnext/commons";+import {+ type DowncastConversionApi,+ type DowncastInsertEvent,+ type Editor,+ type ModelElement,+ type ModelWriter,+ Plugin,+ type UpcastConversionApi,+ type UpcastElementEvent+} from "ckeditor5";++import { SIZE_ATTRIBUTES } from "../resizable_widgets/resizable_widgets.js";+import { getPositionAttributes, getPositionOfView } from "./content_embed.js";++/** The width of a Medium video: 20em high, as a Medium embed is. */+export const VIDEO_MEDIUM_WIDTH = "35.6em";++/** The fields of a link preview, which a video embed keeps as attributes of the same names. */+const PREVIEW_FIELDS = Object.keys(LINK_PREVIEW_DATA_ATTRIBUTES) as (keyof LinkPreviewData)[];++/**+ * Embeds that play the video of a link preview, such as a YouTube video. The embed keeps the fields+ * of the preview as attributes, and is saved as the `<section class="link-embed">` of the link+ * preview, with its box size, title flag, position and width, so that older versions show it as+ * a link preview.+ *+ * The player renders through the host's `contentEmbed.loadVideo()`.+ */+export default class ContentEmbedVideo extends Plugin {++ static get pluginName() {+ return "ContentEmbedVideo" as const;+ }++ init() {+ const editor = this.editor;++ editor.data.upcastDispatcher.on<UpcastElementEvent>(+ "element:section", (_evt, data, api) => upcast(data, api), { priority: "high" });+ editor.data.downcastDispatcher.on<DowncastInsertEvent<ModelElement>>(+ "insert:contentEmbed", (_evt, data, api) => downcastData(editor, data.item, api),+ { priority: "high" });+ }++ afterInit() {+ this.editor.model.schema.extend("contentEmbed", { allowAttributes: PREVIEW_FIELDS });+ }++ /** Has the host render the player of `embed` into `wrapper`. */+ load(embed: ModelElement, wrapper: HTMLElement) {+ this.editor.config.get("contentEmbed")?.loadVideo?.(getVideoPreview(embed), wrapper);+ }+}++/** Creates an embed that plays the video of the link preview with the fields `attributes`. */+export function createVideoEmbed(writer: ModelWriter, attributes: Record<string, unknown>) {+ return writer.createElement("contentEmbed", {+ ...attributes,+ boxSize: "medium",+ hideTitle: true,+ [SIZE_ATTRIBUTES.width]: VIDEO_MEDIUM_WIDTH+ });+}++/** Whether `embed` plays the video of a link preview. */+export function isVideoEmbed(embed: ModelElement) {+ return !!embed.getAttribute("url");+}++/** The link preview whose video `embed` plays. */+export function getVideoPreview(embed: ModelElement) {+ return Object.fromEntries(PREVIEW_FIELDS+ .filter((field) => embed.hasAttribute(field))+ .map((field) => [ field, embed.getAttribute(field) ])) as unknown as LinkPreviewData;+}++/** Turns the link preview of a video into an embed that plays it. Its content is dropped. */+function upcast(data: UpcastElementEvent["args"][0], api: UpcastConversionApi) {+ const section = data.viewItem;+ if (!section.hasClass("link-embed") || !api.consumable.test(section, { name: true })) {+ return;+ }++ const preview = readLinkPreviewData((name) => section.getAttribute(name));+ if (!preview || !getLinkPreviewVideoId(preview)) {+ return;+ }++ const fields = Object.entries(preview).filter(([ , value ]) => value);+ const { boxSize, isTitleHidden } = readVideoEmbedBox((name) => section.getAttribute(name));+ const embed = api.writer.createElement("contentEmbed", {+ ...Object.fromEntries(fields),+ boxSize,+ ...(isTitleHidden ? { hideTitle: true } : {}),+ ...getPositionOfView(section)+ });+ if (!api.safeInsert(embed, data.modelCursor)) {+ return;+ }++ api.consumable.consume(section, { name: true });+ api.updateConversionResult(embed, data);+}++/** Saves a video embed as the `<section>` of its link preview. */+function downcastData(editor: Editor, embed: ModelElement, api: DowncastConversionApi) {+ if (!isVideoEmbed(embed) || !api.consumable.consume(embed, "insert")) {+ return;+ }++ const preview = getVideoPreview(embed);+ const dataAttributes = PREVIEW_FIELDS+ .filter((field) => preview[field])+ .map((field) => [ LINK_PREVIEW_DATA_ATTRIBUTES[field], String(preview[field]) ]);+ const { writer, mapper } = api;+ const section = writer.createContainerElement("section", {+ class: "link-embed",+ ...Object.fromEntries(dataAttributes),+ "data-box-size": embed.getAttribute("boxSize") as string,+ ...(embed.getAttribute("hideTitle") ? { "data-hide-title": "true" } : {}),+ ...getPositionAttributes(embed)+ });+ writer.insert(mapper.toViewPosition(editor.model.createPositionBefore(embed)), section);+ // `ResizableWidgets` writes the width on the `<section>` through this mapping.+ mapper.bindElements(embed, section);+}++declare module "ckeditor5" {+ interface PluginsMap {+ [ContentEmbedVideo.pluginName]: ContentEmbedVideo;+ }+}diff --git a/packages/ckeditor5/src/plugins/internallink.spec.ts b/packages/ckeditor5/src/plugins/internallink.spec.tsindex 023de63374..f225193f46 100644--- a/packages/ckeditor5/src/plugins/internallink.spec.ts+++ b/packages/ckeditor5/src/plugins/internallink.spec.ts@@ -308,6 +308,13 @@ describe("the link at the selection", () => {expect(getLinkAtSelection(editor)).toStrictEqual({ href: "https://a.example", text: "", description: "", display: "card" });++ const videoUrl = "https://youtube.com/watch?v=abc12345678";+ setModelData(editor.model, `[<contentEmbed url="${videoUrl}" embedType="youtube"`+ + " title=\"V\"></contentEmbed>]");+ expect(getLinkAtSelection(editor)).toStrictEqual(+ { href: videoUrl, text: "V", description: "", display: "embed" }+ );});it("replaces a selected link preview, in a paragraph of its own for a block one", async () => {diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.spec.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.spec.tsindex 31cb5f5008..c298e7199a 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.spec.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.spec.ts@@ -125,7 +125,12 @@ describe("AutoLinkToMention", () => {await flushFetch();expect(findElement(editor, "linkMention")).toBeUndefined();- expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("youtube");+ expect(findElement(editor, "linkEmbed")).toBeUndefined();+ const embed = findElement(editor, "contentEmbed");+ expect(embed?.getAttribute("url")).toBe(VIDEO_URL);+ expect(embed?.getAttribute("embedType")).toBe("youtube");+ expect(embed?.getAttribute("title")).toBe(META.title);+ expect(embed?.getAttribute("boxSize")).toBe("medium");});it("keeps the URL inline while the caret is still on its line, embeddable or not", async () => {diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.tsindex b17b629586..7935876c05 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts@@ -1,6 +1,8 @@import { chooseLinkPreviewKind, isUrlAloneInBlock, type BlockChildLike } from '@triliumnext/commons';import { Plugin } from 'ckeditor5';-import { EMBEDDABLE_URL_REGEX, getLinkEmbedHost } from './link_embed_commands.js';+import {+ createLinkPreview, EMBEDDABLE_URL_REGEX, getLinkEmbedHost+} from './link_embed_commands.js';/*** Auto-converts typed/pasted URLs to link preview widgets.@@ -156,9 +158,8 @@ export default class AutoLinkToMention extends Plugin {// but the URL. Swapped with writer.insert/remove rather than insertContent: the// caret has moved on to the next line (that is what made this a block preview in// the first place) and may already be mid-word, so it must not be dragged back.- // 'card' vs 'embed' needs no branch here — the renderer keys off embedType,- // which is "opengraph" for a card and the provider's own type for an embed.- writer.insert(writer.createElement('linkEmbed', attributes), parentEl, 'before');+ const preview = createLinkPreview(writer, kind, attributes);+ writer.insert(preview, parentEl, 'before');writer.remove(parentEl);return;}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 bde4925b43..735fad9238 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@@ -11,6 +11,7 @@ import {type LinkEmbedHostMocks,useDeferredFetch} from "../../../test/link-embed-kit.js";+import { VIDEO_MEDIUM_WIDTH } from "../content_embed/video_embed.js";import {CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND, REMOVE_LINK_EMBED_COMMAND} from "./link_embed_commands.js";@@ -45,7 +46,7 @@ describe("LinkEmbed commands", () => {expect(mention?.getAttribute("siteName")).toBe(META.siteName);});- it("forces the opengraph type for a card, and keeps the detected one for an embed", async () => {+ it("forces the opengraph type for a card, and embeds the video for an embed", async () => {const url = "https://youtube.com/watch?v=abc12345678";fetchMetadata.mockResolvedValue({ ...META, url, embedType: "youtube" });@@ -56,7 +57,8 @@ describe("LinkEmbed commands", () => {setModelData(editor.model, "<paragraph>[]</paragraph>");await editor.execute(LINK_EMBED_COMMAND, { url, mode: "embed" });- expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("youtube");+ expect(findElement(editor, "linkEmbed")).toBeUndefined();+ expect(findElement(editor, "contentEmbed")?.getAttribute("embedType")).toBe("youtube");});it("inserts an ordinary link for the 'plain' mode, without fetching any metadata", async () => {@@ -315,6 +317,72 @@ describe("LinkEmbed commands", () => {expect(editor.getData()).toBe(before);});+ // -----------------------------------------------------------------------+ // Video embeds: the embed mode of a link preview that has a video+ // -----------------------------------------------------------------------++ describe("video embeds", () => {+ const url = "https://youtube.com/watch?v=abc12345678";+ const video = `<contentEmbed embedType="youtube" title="T" url="${url}"></contentEmbed>`;++ it("embeds the video of a mention, and makes a card of an embed type without one", () => {+ setModelData(editor.model, `<paragraph>[<linkMention url="${url}" embedType="youtube"`+ + ` title="T"></linkMention>]</paragraph>`);+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "embed" });++ const embed = findElement(editor, "contentEmbed");+ expect(embed && Object.fromEntries(embed.getAttributes())).toEqual({+ url, embedType: "youtube", title: "T",+ boxSize: "medium", hideTitle: true, customWidth: VIDEO_MEDIUM_WIDTH+ });+ expect(editor.model.document.selection.getSelectedElement()).toBe(embed);+ expect(findElement(editor, "linkMention")).toBeUndefined();++ setModelData(editor.model, `<paragraph>[<linkMention url="https://youtube.com/watch"`+ + ` embedType="youtube"></linkMention>]</paragraph>`);+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "embed" });+ expect(findElement(editor, "contentEmbed")).toBeUndefined();+ expect(findElement(editor, "linkEmbed")?.getAttribute("embedType")).toBe("youtube");+ });++ it("shows a selected video as a preview in the embed mode, which can change", () => {+ setModelData(editor.model, `[${video}]`);+ const command = changeCommand(editor);+ expect([ command.isEnabled, command.value, command.embedAvailable, command.url ])+ .toEqual([ true, "embed", true, url ]);++ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "card" });+ expect(findElement(editor, "contentEmbed")).toBeUndefined();+ const card = findElement(editor, "linkEmbed");+ expect(card?.getAttribute("embedType")).toBe("opengraph");+ expect(card?.getAttribute("title")).toBe("T");++ setModelData(editor.model, `[${video}]`);+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "plain" });+ expect(editor.getData()).toBe(`<p><a href="${url}">${url}</a></p>`);+ });++ it("keeps the box, title and position of a video retitled in the dialog", async () => {+ setModelData(editor.model, `[<contentEmbed boxSize="full" embedType="youtube"`+ + ` position="right" title="T" url="${url}"></contentEmbed>]`);++ await editor.execute(LINK_EMBED_COMMAND, { url, mode: "embed", title: "Mine" });++ const embed = findElement(editor, "contentEmbed");+ expect(fetchMetadata).not.toHaveBeenCalled();+ expect(embed && Object.fromEntries(embed.getAttributes())).toEqual({+ url, embedType: "youtube", title: "Mine", boxSize: "full", position: "right"+ });+ expect(editor.model.document.selection.getSelectedElement()).toBe(embed);+ });++ it("leaves other embeds alone", () => {+ setModelData(editor.model, "[<contentEmbed boxSize=\"medium\" noteId=\"n1\">"+ + "</contentEmbed>]");+ expect(changeCommand(editor).isEnabled).toBe(false);+ });+ });+// -----------------------------------------------------------------------// RemoveLinkEmbedCommand (the toolbar's unlink button)// -----------------------------------------------------------------------@@ -405,7 +473,7 @@ describe("LinkEmbed commands", () => {setModelData(editor.model, `<paragraph><$text linkHref="${url}">watch [] this</$text></paragraph>`);await editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "embed" });- const embed = findElement(editor, "linkEmbed");+ const embed = findElement(editor, "contentEmbed");expect(embed?.getAttribute("embedType")).toBe("youtube");expect(editor.model.document.selection.getSelectedElement()).toBe(embed);});diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.tsindex 30171925a7..fb22486c86 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts@@ -1,9 +1,11 @@-import { isHttpUrl } from '@triliumnext/commons';+import { getLinkPreviewVideoId, isHttpUrl } from '@triliumnext/commons';import {Command, type Editor, findAttributeRange, type ModelElement, ModelLiveRange, type ModelRange,type ModelWriter} from 'ckeditor5';+import { createVideoEmbed, isVideoEmbed } from '../content_embed/video_embed.js';+export const LINK_EMBED_COMMAND = 'insertLinkEmbed';export const CHANGE_LINK_DISPLAY_COMMAND = 'changeLinkDisplay';export const REMOVE_LINK_EMBED_COMMAND = 'removeLinkEmbed';@@ -276,12 +278,10 @@ async function replaceLinkWithPreview(}if (!linkStillThere) return;- const element = writer.createElement(mode === 'inline' ? 'linkMention' : 'linkEmbed', {+ const element = createLinkPreview(writer, mode, {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)+ embedType: mode === 'embed'+ ? getLinkEmbedHost(editor).detectEmbedType(href): metadata.embedType,title: title || metadata.title,description: description || metadata.description,@@ -317,32 +317,75 @@ function rebuildLinkWidget(}if (title) attrs.title = title;if (description) attrs.description = description;- if (mode !== 'inline') {- // A card is an embed that declines to play.- attrs.embedType = mode === 'card' ? 'opengraph'- : getLinkEmbedHost(editor).detectEmbedType(attrs.url as string);+ if (mode === 'card') {+ attrs.embedType = 'opengraph';+ } else if (mode === 'embed') {+ attrs.embedType = 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);+ // does not re-render on attribute changes. A preview that keeps its shape keeps its other+ // attributes, such as the box of a video.+ const ownAttributes = Object.fromEntries(element.getAttributes());+ const replacement = getLinkPreviewName(mode, attrs) === element.name+ ? writer.createElement(element.name, { ...ownAttributes, ...attrs })+ : createLinkPreview(writer, mode, attrs);editor.model.insertContent(replacement, writer.createRangeOn(element));return replacement;}+/**+ * Creates the element of the `mode` shape for a link preview with the fields `attributes`: a+ * `linkMention`, a `linkEmbed`, or a video embed (`ContentEmbedVideo`) for the embed of a URL+ * with a video.+ */+export function createLinkPreview(+ writer: ModelWriter,+ mode: Exclude<LinkDisplayMode, 'plain'>,+ attributes: Record<string, unknown>+) {+ switch (getLinkPreviewName(mode, attributes)) {+ case 'linkMention':+ return writer.createElement('linkMention', attributes);+ case 'contentEmbed':+ return createVideoEmbed(writer, attributes);+ default:+ // The renderers draw the `opengraph` type as a card, also for a URL with a video.+ return writer.createElement('linkEmbed', {+ ...attributes,+ embedType: mode === 'card' ? 'opengraph' : attributes.embedType+ });+ }+}++/** The element of a link preview of the `mode` shape with the fields `attributes`. */+function getLinkPreviewName(+ mode: Exclude<LinkDisplayMode, 'plain'>, attributes: Record<string, unknown>+) {+ if (mode === 'inline') {+ return 'linkMention';+ }+ const embedType = attributes.embedType as string | undefined;+ const hasVideo = mode === 'embed'+ && !!getLinkPreviewVideoId({ url: attributes.url as string, embedType });+ return hasVideo ? 'contentEmbed' : 'linkEmbed';+}+/** 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. */+/** Returns the selected linkEmbed or linkMention element, or video embed, or null. */export function getSelectedLinkWidget(editor: Editor): ModelElement | null {const selected = editor.model.document.selection.getSelectedElement();if (selected && (selected.name === 'linkMention' || selected.name === 'linkEmbed')) {return selected;}+ if (selected?.name === 'contentEmbed' && isVideoEmbed(selected)) {+ return selected;+ }return null;}diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.tsindex 342d690519..de6f2b6f81 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts@@ -1,4 +1,6 @@+import { LINK_PREVIEW_DATA_ATTRIBUTES } from '@triliumnext/commons';import { Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget } from 'ckeditor5';+import ContentEmbed from '../content_embed/content_embed.js';import { preventCKEditorHandling, restoreRendererFocusOnInput } from '../widget_utils.js';import {CHANGE_LINK_DISPLAY_COMMAND,@@ -13,11 +15,12 @@ import {} from './link_embed_commands.js';/**- * Schema, converters and command registration for linkEmbed (block) and linkMention (inline).+ * Schema, converters and command registration for linkEmbed (block) and linkMention (inline). The+ * embed of a URL with a video is a video embed of `ContentEmbed`.*/export default class LinkEmbedEditing extends Plugin {static get requires() {- return [Widget];+ return [Widget, ContentEmbed];}init() {@@ -183,16 +186,6 @@ export default class LinkEmbedEditing extends Plugin {}}-const DATA_ATTR_NAMES: Record<MetaKey, string> = {- url: 'data-url',- embedType: 'data-embed-type',- title: 'data-title',- description: 'data-description',- favicon: 'data-favicon',- siteName: 'data-site-name',- image: 'data-image'-};-/*** Builds the widget wrapper's class + `data-*` attributes from a linkEmbed/linkMention element.*@@ -212,7 +205,7 @@ function metadataViewAttributes(for (const key of META_KEYS) {const val = modelElement.getAttribute(key) as string | undefined;if (val || requiredKeys.includes(key)) {- attrs[DATA_ATTR_NAMES[key]] = val as string;+ attrs[LINK_PREVIEW_DATA_ATTRIBUTES[key]] = val as string;}}return attrs;diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.tsindex 82b1017e4f..404e0373a2 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts@@ -71,7 +71,7 @@ function isLinkEmbedWidget(element: ViewElement): boolean {return false;}-class LinkEmbedDisplayDropdown extends Plugin {+export class LinkEmbedDisplayDropdown extends Plugin {static get requires() {return [LinkEmbed] as const;@@ -183,7 +183,7 @@ class LinkEmbedLinkButton extends Plugin {* Registers the `linkEmbedCopyUrl` toolbar item: copies the selected widget's URL* to the clipboard, mirroring the default link toolbar's copy-URL button.*/-class LinkEmbedCopyUrlButton extends Plugin {+export class LinkEmbedCopyUrlButton extends Plugin {static get requires() {return [LinkEmbed] as const;diff --git a/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.spec.ts b/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.spec.tsindex 8bb7ab28e6..5840208f13 100644--- a/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.spec.ts+++ b/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.spec.ts@@ -2,6 +2,7 @@ import {_getModelData as getModelData,type ClassicEditor,Essentials,+ type ModelElement,Paragraph,Plugin,Undo,@@ -222,6 +223,48 @@ describe("ResizableWidgets", () => {expect(getBox().classList.contains("ck-widget_resizable")).toBe(true);});+ it("resizes only the axes that the state of the widget allows", async () => {+ const isRound = (element: ModelElement) => element.getAttribute("kind") !== "fixed";+ const getDisplays = () => [ "width", "height", "corner" ]+ .map((name) => getComputedStyle(getHandle(name)).display);++ await createEditor({ isHeightResizable: isRound });+ editor.setData(RESIZED);+ const box = editor.model.document.getRoot()?.getChild(0);+ if (!box?.is("element")) {+ throw new Error("Expected a box.");+ }+ editor.model.change((writer) => writer.setSelection(box, "on"));+ editor.editing.view.focus();+ await expect.poll(getDisplays).toEqual([ "block", "block", "block" ]);++ // Only the corner is left, which changes the width alone.+ editor.model.change((writer) => writer.setAttribute("kind", "fixed", box));+ expect(getBox().classList.contains("ck-widget_fixed-height")).toBe(true);+ expect(getDisplays()).toEqual([ "none", "none", "block" ]);+ expect(getComputedStyle(getHandle("corner"), "::after").content).toBe("\"\"");+ press(getHandle("height"));+ move(100, 400);+ expect(getBox().classList.contains("ck-widget_resizing")).toBe(false);+ press(getHandle("corner"));+ move(150, 400);+ release();+ expect(getSize())+ .toBe("<testBox customHeight=\"8em\" customWidth=\"35em\" kind=\"fixed\"></testBox>");++ editor.model.change((writer) => writer.removeAttribute("kind", box));+ expect(getBox().classList.contains("ck-widget_fixed-height")).toBe(false);++ await createEditor({ isWidthResizable: () => false });+ editor.setData(RESIZED);+ expect(getBox().classList.contains("ck-widget_fixed-width")).toBe(true);+ expect(getDisplays()).toEqual([ "none", "none", "block" ]);+ press(getHandle("corner"));+ move(150, 330);+ release();+ expect(getSize()).toBe("<testBox customHeight=\"11em\" customWidth=\"30em\"></testBox>");+ });+it("resizes from the corner, previewing in the view and saving in one undo step", async () => {await createEditor();editor.setData("<p>text</p><div class=\"test-box\"></div>");diff --git a/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.ts b/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.tsindex 1c7189735d..7e631ba1f7 100644--- a/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.ts+++ b/packages/ckeditor5/src/plugins/resizable_widgets/resizable_widgets.ts@@ -16,6 +16,9 @@ import {export type { ResizeAnchor } from "./resize_gesture.js";+/** Whether an axis can be resized: always, never, or depending on the state of `element`. */+export type ResizableAxisFlag = boolean | ((element: ModelElement) => boolean);+/** How the widgets of a model element are resized. */export interface ResizableWidgetConfig {/**@@ -23,8 +26,8 @@ export interface ResizableWidgetConfig {* `<prefix>-width` and `<prefix>-height`. The widget's stylesheet applies them.*/propertyPrefix: string;- isWidthResizable?: boolean;- isHeightResizable?: boolean;+ isWidthResizable?: ResizableAxisFlag;+ isHeightResizable?: ResizableAxisFlag;/*** The edge of `element` that stays in place while its width changes, as its stylesheet places* the widget. The inline start by default. The handles go on the opposite edge.@@ -60,6 +63,11 @@ const ANCHOR_CLASSES = {left: "ck-widget_resize-anchor-left",right: "ck-widget_resize-anchor-right"} as const;+/** The classes of a widget whose state fixes an axis, which hide the handles of that axis. */+const FIXED_CLASSES: Record<Axis, string> = {+ width: "ck-widget_fixed-width",+ height: "ck-widget_fixed-height"+};const RESIZING_CLASS = "ck-widget_resizing";const TOOLBAR_LOCK = "ResizableWidgets";const DEFAULT_MIN_SIZE = 2;@@ -119,7 +127,7 @@ export default class ResizableWidgets extends Plugin {updateWidgetClasses(api.writer, viewElement, item, config);}, { priority: "low" });- if (config.isResizable || config.getAnchor) {+ if (config.isResizable || config.getAnchor || hasStatefulAxes(config)) {dispatcher.on<DowncastAttributeEvent>("attribute", (_evt, { item }, api) => {if (!item.is("element", modelName)) {return;@@ -176,8 +184,13 @@ export default class ResizableWidgets extends Plugin {return;}- const heightTarget = handleAxes.height ? findHeightTarget(widget, config) : null;- const axes = { width: handleAxes.width, height: !!heightTarget };+ const heightTarget = handleAxes.height && isAxisResizable(config, "height", element)+ ? findHeightTarget(widget, config)+ : null;+ const axes = {+ width: handleAxes.width && isAxisResizable(config, "width", element),+ height: !!heightTarget+ };if (!axes.width && !axes.height) {return;}@@ -304,7 +317,19 @@ function getAxes(config: ResizableWidgetConfig) {return axes;}-/** Sets the resizable and anchor classes of the widget from the state of `element`. */+/** Whether an axis of `config` depends on the state of the element. */+function hasStatefulAxes(config: ResizableWidgetConfig) {+ return typeof config.isWidthResizable === "function"+ || typeof config.isHeightResizable === "function";+}++/** Whether `axis` of `element` can be resized in its current state. */+function isAxisResizable(config: ResizableWidgetConfig, axis: Axis, element: ModelElement) {+ const flag = axis === "width" ? config.isWidthResizable : config.isHeightResizable;+ return typeof flag === "function" ? flag(element) : !!flag;+}++/** Sets the resizable, anchor and fixed axis classes of the widget from the state of `element`. */function updateWidgetClasses(writer: ViewDowncastWriter,viewElement: ViewElement,@@ -316,6 +341,10 @@ function updateWidgetClasses(for (const [ name, className ] of Object.entries(ANCHOR_CLASSES)) {toggleClass(writer, viewElement, className, name === anchor);}+ for (const axis of getAxes(config)) {+ toggleClass(writer, viewElement, FIXED_CLASSES[axis],+ !isAxisResizable(config, axis, element));+ }}function toggleClass(diff --git a/packages/ckeditor5/src/plugins/youtube_video.spec.ts b/packages/ckeditor5/src/plugins/youtube_video.spec.tsindex e52cf139b4..cce45bf890 100644--- a/packages/ckeditor5/src/plugins/youtube_video.spec.ts+++ b/packages/ckeditor5/src/plugins/youtube_video.spec.ts@@ -58,8 +58,8 @@ describe("YouTubeVideoPlugin", () => {expect(release).toHaveBeenCalledOnce();expect(balloon().visibleView).toBeNull();- await vi.waitFor(() => expect(findElement(editor, "linkEmbed")).toBeDefined());- const embed = findElement(editor, "linkEmbed");+ await vi.waitFor(() => expect(findElement(editor, "contentEmbed")).toBeDefined());+ const embed = findElement(editor, "contentEmbed");expect(embed?.getAttribute("url")).toBe(VIDEO_URL);expect(embed?.getAttribute("embedType")).toBe("youtube");expect(linkEmbed.fetchMetadata).toHaveBeenCalledExactlyOnceWith(VIDEO_URL);diff --git a/packages/ckeditor5/src/plugins/youtube_video.ts b/packages/ckeditor5/src/plugins/youtube_video.tsindex eeaf2311c3..fd00d7f40a 100644--- a/packages/ckeditor5/src/plugins/youtube_video.ts+++ b/packages/ckeditor5/src/plugins/youtube_video.ts@@ -68,7 +68,7 @@ export default class YouTubeVideoPlugin extends Plugin {}}-/** Enabled wherever a block link preview can go, with a host to ask for the address. */+/** Enabled wherever an embed can go, with a host to ask for the address. */class YouTubeVideoCommand extends Command {override refresh() {@@ -78,7 +78,7 @@ class YouTubeVideoCommand extends Command {this.isEnabled = !!this.editor.config.get("youtubeVideo")&& !!position&& !position.findAncestor("codeBlock")- && model.schema.findAllowedParent(position, "linkEmbed") !== null;+ && model.schema.findAllowedParent(position, "contentEmbed") !== null;}override execute() {diff --git a/packages/ckeditor5/src/theme/resizable_widgets.css b/packages/ckeditor5/src/theme/resizable_widgets.cssindex d279add086..7eebd8a12e 100644--- a/packages/ckeditor5/src/theme/resizable_widgets.css+++ b/packages/ckeditor5/src/theme/resizable_widgets.css@@ -31,6 +31,12 @@display: none;}+/* The corner, the only handle with a grip on every screen, resizes the axis left. */+.ck :is(.ck-widget_fixed-width, .ck-widget_fixed-height) > .ck-widget__resize-handles+ > :not(.ck-widget__resize-handle_corner) {+ display: none;+}+.ck .ck-widget__resize-handle {--_offset: calc(var(--ck-resize-handle-hit-size) / -2);diff --git a/packages/commons/src/lib/content_embeds.ts b/packages/commons/src/lib/content_embeds.tsindex a6551a0b1f..366bf19bcb 100644--- a/packages/commons/src/lib/content_embeds.ts+++ b/packages/commons/src/lib/content_embeds.ts@@ -36,6 +36,9 @@ export const EXTENDED_CODE_BLOCK_CLASS = "extended-code-block";/** The language of an extended code block that names none, as a CKEditor code block language. */export const EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE = "text-plain";+/** The class of the embed box of a video, in the editor and in read-only views. */+export const VIDEO_EMBED_CLASS = "video-embed";+/*** The attribute that marks a `<section>` as a content embed and names its kind, for kinds added* after include notes and source embeds. A version that does not know the kind keeps the sectiondiff --git a/packages/commons/src/lib/link_embed_markup.spec.ts b/packages/commons/src/lib/link_embed_markup.spec.tsindex 407b370b33..02d2d93436 100644--- a/packages/commons/src/lib/link_embed_markup.spec.ts+++ b/packages/commons/src/lib/link_embed_markup.spec.ts@@ -1,8 +1,8 @@import { describe, expect, it } from "vitest";import {- LINK_EMBED_CARD_IMAGE_PLACEHOLDER, readLinkPreviewData, renderLinkEmbedHtml,- renderLinkMentionHtml+ getLinkPreviewVideoId, LINK_EMBED_CARD_IMAGE_PLACEHOLDER, LINK_PREVIEW_DATA_ATTRIBUTES,+ readLinkPreviewData, readVideoEmbedBox, renderLinkEmbedHtml, renderLinkMentionHtml} from "./link_embed_markup.js";const OPTIONS = { playVideoLabel: "Play \"video\"" };@@ -27,6 +27,38 @@ describe("readLinkPreviewData", () => {});expect(readLinkPreviewData(() => null)).toBeNull();});++ it("reads every field from the attribute that LINK_PREVIEW_DATA_ATTRIBUTES names", () => {+ const data = readLinkPreviewData((name) => `value of ${name}`);++ expect(data).toEqual(Object.fromEntries(Object.entries(LINK_PREVIEW_DATA_ATTRIBUTES)+ .map(([ field, attribute ]) => [ field, `value of ${attribute}` ])));+ });+});++describe("readVideoEmbedBox", () => {+ it("reads the box size and the title, Full and untitled for a video saved before", () => {+ const read = (attributes: Record<string, string>) =>+ readVideoEmbedBox((name) => attributes[name]);++ expect(read({ "data-box-size": "medium" }))+ .toEqual({ boxSize: "medium", isTitleHidden: false });+ expect(read({ "data-box-size": "full", "data-hide-title": "true" }))+ .toEqual({ boxSize: "full", isTitleHidden: true });+ expect(read({ "data-box-size": "tiny" }))+ .toEqual({ boxSize: "full", isTitleHidden: false });+ expect(read({})).toEqual({ boxSize: "full", isTitleHidden: true });+ });+});++describe("getLinkPreviewVideoId", () => {+ it("gives the ID of a video that plays, and nothing for a card or a page", () => {+ expect(getLinkPreviewVideoId({ url: VIDEO_URL, embedType: "youtube" })).toBe("dQw4w9WgXcQ");+ expect(getLinkPreviewVideoId({ url: VIDEO_URL })).toBe("dQw4w9WgXcQ");+ expect(getLinkPreviewVideoId({ url: VIDEO_URL, embedType: "opengraph" })).toBeNull();+ expect(getLinkPreviewVideoId({ url: "https://example.com", embedType: "youtube" }))+ .toBeNull();+ });});describe("renderLinkMentionHtml", () => {diff --git a/packages/commons/src/lib/link_embed_markup.ts b/packages/commons/src/lib/link_embed_markup.tsindex 3387642a38..52412b0e05 100644--- a/packages/commons/src/lib/link_embed_markup.ts+++ b/packages/commons/src/lib/link_embed_markup.ts@@ -22,27 +22,62 @@ export interface LinkPreviewMarkupOptions {playVideoLabel: string;}+/** The `data-*` attribute that stores each field of a link preview. */+export const LINK_PREVIEW_DATA_ATTRIBUTES = {+ url: "data-url",+ embedType: "data-embed-type",+ title: "data-title",+ description: "data-description",+ image: "data-image",+ favicon: "data-favicon",+ siteName: "data-site-name"+} as const satisfies Record<keyof LinkPreviewData, string>;+/*** The preview stored on a `section.link-embed` or `span.link-mention`, or `null` when it carries no* URL. A missing embed type reads as `opengraph`.*/export function readLinkPreviewData(getAttribute: (name: string) => string | null | undefined) {- const url = getAttribute("data-url");+ const attributes = LINK_PREVIEW_DATA_ATTRIBUTES;+ const url = getAttribute(attributes.url);if (!url) {return null;}return {url,- embedType: getAttribute("data-embed-type") || "opengraph",- title: getAttribute("data-title"),- description: getAttribute("data-description"),- image: getAttribute("data-image"),- favicon: getAttribute("data-favicon"),- siteName: getAttribute("data-site-name")+ embedType: getAttribute(attributes.embedType) || "opengraph",+ title: getAttribute(attributes.title),+ description: getAttribute(attributes.description),+ image: getAttribute(attributes.image),+ favicon: getAttribute(attributes.favicon),+ siteName: getAttribute(attributes.siteName)} satisfies LinkPreviewData;}+/** The box sizes of a video embed. */+export const VIDEO_EMBED_BOX_SIZES = [ "medium", "full" ] as const;++/**+ * The box size of a video saved as a link preview, and whether its title is hidden. A video saved+ * before videos were embeds has no box size: it is Full and untitled.+ */+export function readVideoEmbedBox(getAttribute: (name: string) => string | null | undefined) {+ const savedBoxSize = getAttribute("data-box-size");+ const boxSize = VIDEO_EMBED_BOX_SIZES.find((size) => size === savedBoxSize) ?? "full";+ return {+ boxSize,+ isTitleHidden: !savedBoxSize || getAttribute("data-hide-title") === "true"+ };+}++/** The YouTube ID of the video that a link preview plays, or `null` for a card. */+export function getLinkPreviewVideoId(+ { url, embedType }: Pick<LinkPreviewData, "url" | "embedType">+) {+ return embedType !== "opengraph" ? extractYouTubeVideoId(url) : null;+}+/*** The markup of an inline link mention: the site's favicon and the page title, or the host when* the note stores no title.@@ -64,7 +99,7 @@ export function renderLinkMentionHtml(data: LinkPreviewData, options: LinkPrevie* player on the reader's click.*/export function renderLinkEmbedHtml(data: LinkPreviewData, options: LinkPreviewMarkupOptions) {- const videoId = data.embedType !== "opengraph" ? extractYouTubeVideoId(data.url) : null;+ const videoId = getLinkPreviewVideoId(data);if (videoId) {const label = escapeHtml(options.playVideoLabel);return `<div class="link-embed-video">`diff --git a/packages/share-theme/src/content/content.css b/packages/share-theme/src/content/content.cssindex 35405e4e31..e5cfddb3ab 100644--- a/packages/share-theme/src/content/content.css+++ b/packages/share-theme/src/content/content.css@@ -343,12 +343,15 @@ body:not(.math-loaded) .math-tex {object-fit: contain;}-/* An include with a caption: the included content, then the caption. */-.ck-content figure.include-note {+/* An include, or the video of a link preview, placed and sized as the editor saved it. */+.ck-content :is(figure.include-note, section.link-embed:where([data-embed-type="youtube"])) {clear: both;margin: 1em 0;- &:is([data-box-size="small"], [data-box-size="medium"], [data-box-size="expandable"]) {+ &:is(+ [data-box-size="small"], [data-box-size="medium"], [data-box-size="expandable"],+ .link-embed+ ) {margin-inline: auto;max-width: 100%;width: var(--include-note-width, auto);@@ -386,7 +389,7 @@ body:not(.math-loaded) .math-tex {}@media (max-width: 48em) {- .ck-content figure.include-note[data-position] {+ .ck-content :is(figure.include-note, section.link-embed)[data-position] {float: none;clear: both;margin: 1em 0;diff --git a/packages/share-theme/src/content/link_embed.css b/packages/share-theme/src/content/link_embed.cssindex 833d8adbda..d60ab2f5e3 100644--- a/packages/share-theme/src/content/link_embed.css+++ b/packages/share-theme/src/content/link_embed.css@@ -70,7 +70,7 @@ html.theme-light .link-embed-favicon-light {display: grid;grid-template-columns: minmax(0, 1fr);position: relative;- max-width: 640px;+ max-width: var(--include-note-width, 640px);margin: auto;border-radius: 8px;overflow: hidden;diff --git a/packages/trilium-core/src/services/sanitizer.spec.ts b/packages/trilium-core/src/services/sanitizer.spec.tsindex 6f010fe25b..6d14fff4b6 100644--- a/packages/trilium-core/src/services/sanitizer.spec.ts+++ b/packages/trilium-core/src/services/sanitizer.spec.ts@@ -62,6 +62,15 @@ describe("sanitize", () => {// An embed that keeps its source in the note is saved as a code block.const inline = `<pre style="--include-note-width:30em;--include-note-height:12.5em" data-box-size="medium"><code class="language-mermaid">graph TD;</code></pre>`;expect(sanitizeHtml(inline)).toBe(inline);++ // A video takes its height from its width.+ const video = `<section class="link-embed" style="--include-note-width:30em"`+ + ` data-url="https://youtu.be/dQw4w9WgXcQ" data-embed-type="youtube"`+ + ` data-position="wrap-left"></section>`;+ const width = "--include-note-width:30em";+ expect(sanitizeHtml(video)).toBe(video);+ expect(sanitizeHtml(video.replace(width, "--include-note-height:12em")))+ .toBe(video.replace(` style="${width}"`, ""));});it("keeps the hidden-border style on table header cells", () => {diff --git a/packages/trilium-core/src/services/sanitizer.ts b/packages/trilium-core/src/services/sanitizer.tsindex 13c29286c3..2beed53a33 100644--- a/packages/trilium-core/src/services/sanitizer.ts+++ b/packages/trilium-core/src/services/sanitizer.ts@@ -94,6 +94,10 @@ export function sanitizeHtml(dirtyHtml: string) {"--include-note-width": sizeRegex,"--include-note-height": sizeRegex},+ // The width of a resized video, saved as the `<section>` of its link preview.+ section: {+ "--include-note-width": sizeRegex+ },img: {// Allow fractional ratios too (e.g. OneNote reports 577.5×277.5 screen clippings)."aspect-ratio": [ /^\d+(\.\d+)?\/\d+(\.\d+)?$/ ],