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: follow the original aspect ratio of the video
Adorian Doran15576e57272b
diff --git a/.claude/skills/developing-content-embeds/SKILL.md b/.claude/skills/developing-content-embeds/SKILL.mdindex a7996ec012..277a1e9c38 100644--- a/.claude/skills/developing-content-embeds/SKILL.md+++ b/.claude/skills/developing-content-embeds/SKILL.md@@ -61,9 +61,18 @@ All three carry `boxSize`, `hideTitle`, `editable`, `displayMode` (`data-box-sizlink 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+ untitled, and `createVideoEmbed()` makes a new one Medium at `getVideoMediumWidth()` (20em+ high), which the box size command sets again. Height follows width (`isHeightResizable` is+ per element). No caption.+ The shape is the link preview field `aspectRatio` (`data-aspect-ratio="9/16"`), which the+ server reads from oEmbed for the video's `/shorts/` address (the watch address of a Short+ answers 16:9). `getVideoAspectRatio()` validates it; every box that draws a player (the+ editing figure, `applyVideoEmbeds()`, `renderLinkEmbedHtml()`) writes it as+ `--video-aspect-ratio`, which the player's `aspect-ratio` and the 70vh cap of Full read. A+ preview without one is 16:9. A new link preview field goes into `LINK_PREVIEW_DATA_ATTRIBUTES`+ and `readLinkPreviewData()`, both `LinkEmbedMetadata` types (commons and the editor's+ `augmentation.ts`) and the client's `fetchMetadata()`; `META_KEYS`, the schemas and the+ converters follow the map. It renders through `contentEmbed.loadVideo()` (`loadVideoEmbed()`, whose title rowopens 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.diff --git a/apps/client/src/services/link_embed.spec.ts b/apps/client/src/services/link_embed.spec.tsindex 507e7adf63..af25a1e6cc 100644--- a/apps/client/src/services/link_embed.spec.ts+++ b/apps/client/src/services/link_embed.spec.ts@@ -72,7 +72,8 @@ describe("fetchMetadata", () => {description: "Desc",favicon: "https://example.com/favicon.ico",siteName: "Example",- image: "https://example.com/img.png"+ image: "https://example.com/img.png",+ aspectRatio: "9/16"};server.post = vi.fn(async () => fromServer) as typeof server.post;diff --git a/apps/client/src/services/link_embed.ts b/apps/client/src/services/link_embed.tsindex bd8fe1283a..8b91081a65 100644--- a/apps/client/src/services/link_embed.ts+++ b/apps/client/src/services/link_embed.ts@@ -18,6 +18,7 @@ export interface EmbedMetadata {favicon?: string;siteName?: string;image?: string;+ aspectRatio?: string;/** See {@link LinkEmbedMetadata.unresolved}. Not persisted into the note's HTML. */unresolved?: boolean;}@@ -53,6 +54,7 @@ export async function fetchMetadata(url: string, ownerNoteId: string): Promise<Efavicon: metadata.favicon,siteName: metadata.siteName,image: metadata.image,+ aspectRatio: metadata.aspectRatio,unresolved: metadata.unresolved};} catch {diff --git a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css b/apps/client/src/widgets/type_widgets/text/LinkEmbed.cssindex f94e395f91..d4acb8bb3f 100644--- a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css+++ b/apps/client/src/widgets/type_widgets/text/LinkEmbed.css@@ -120,7 +120,9 @@ body.light-theme .link-embed-favicon-light {display: grid;grid-template-columns: minmax(0, 1fr);position: relative;+ margin-inline: auto;width: 100%;+ max-width: calc(var(--link-preview-video-max-height) * var(--video-aspect-ratio, 16 / 9));overflow: hidden;& > iframe,@@ -133,19 +135,31 @@ body.light-theme .link-embed-favicon-light {--_link-embed-top-border-radius: var(--_include-note-content-top-radius);--_link-embed-bottom-border-radius: var(--_include-note-content-bottom-radius);+ &[data-box-size="full"] {+ max-width: min(100%, var(--link-preview-video-max-height)+ * var(--video-aspect-ratio, 16 / 9));+ }+.include-note-content.type-videoEmbed {padding: 0;height: auto;max-height: none;overflow: visible;}++ .link-embed-video {+ max-width: none;+ }+}++figure.include-note:where(.video-embed[data-box-size="full"]) {+ margin-inline: auto;}.link-embed-video iframe {width: 100%;height: 100%;- max-height: var(--link-preview-video-max-height);- aspect-ratio: 16 / 9;+ aspect-ratio: var(--video-aspect-ratio, 16 / 9);border: none;display: block;}@@ -160,8 +174,7 @@ body.light-theme .link-embed-favicon-light {display: block;width: 100%;height: 100%;- max-height: var(--link-preview-video-max-height);- aspect-ratio: 16 / 9;+ aspect-ratio: var(--video-aspect-ratio, 16 / 9);padding: 0;border: none;background: #000;@@ -180,7 +193,7 @@ body.light-theme .link-embed-favicon-light {.link-embed-video-facade .link-embed-video-thumbnail {width: 100%;height: 100%;- object-fit: contain;+ object-fit: cover;display: block;}diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsxindex 198d1a06f3..cbc36b908b 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx@@ -605,7 +605,8 @@ 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">`+ + ` data-aspect-ratio="9/16" 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/"`@@ -641,7 +642,8 @@ describe("ReadOnlyText videos", () => {isInPage: figure.isConnected,className: figure.className,data: { ...figure.dataset },- width: figure.style.getPropertyValue("--include-note-width")+ width: figure.style.getPropertyValue("--include-note-width"),+ shape: figure.style.getPropertyValue("--video-aspect-ratio")};});const box = {@@ -649,10 +651,13 @@ describe("ReadOnlyText videos", () => {};expect(videos).toEqual([{- ...box, title: "A video", width: "30em",+ ...box, title: "A video", width: "30em", shape: "0.5625",data: { boxSize: "medium", position: "wrap-left", triliumBlockId: "b1" }},- { ...box, title: null, width: "", data: { boxSize: "full", hideTitle: "true" } }+ {+ ...box, title: null, width: "", shape: "",+ data: { boxSize: "full", hideTitle: "true" }+ }]);expect(container.querySelector("section.link-embed > a.link-embed-card")).not.toBeNull();await unmount();diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex 0834e48d29..232ff46e17 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@ -15,7 +15,8 @@ import { CLASSES as TAB_CLASSES } from "@triliumnext/ckeditor5/src/plugins/tabs/import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";import {EXTENDED_CODE_BLOCK_CLASS, EXTENDED_CODE_BLOCK_DEFAULT_LANGUAGE, getLinkPreviewVideoId,- readLinkPreviewData, readVideoEmbedBox, VIDEO_EMBED_CLASS+ getVideoAspectRatio, readLinkPreviewData, readVideoEmbedBox, VIDEO_ASPECT_RATIO_PROPERTY,+ VIDEO_EMBED_CLASS} from "@triliumnext/commons";import clsx from "clsx";import { Ref } from "preact";@@ -290,6 +291,10 @@ function applyVideoEmbeds(container: HTMLDivElement) {if (style) {figure.setAttribute("style", style);}+ const aspectRatio = getVideoAspectRatio(preview);+ if (aspectRatio) {+ figure.style.setProperty(VIDEO_ASPECT_RATIO_PROPERTY, String(aspectRatio));+ }section.replaceWith(figure);loadVideoEmbed(preview, figure);}diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex 59d6910d87..99049d577b 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><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_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>. It keeps the shape of the video, so a YouTube Short stands upright and an older video can be 4:3. A video inserted in an earlier version is 16:9 until it is inserted again. 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, or less when it would be taller than most of the window. 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, the channel name and the shape of the video 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 428ddb608a..b9b2a4ec3b 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@@ -84,12 +84,12 @@ Click on an inserted _Inline_ or _Card_ link preview to select it, and a small t### 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:+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>. It keeps the shape of the video, so a YouTube Short stands upright and an older video can be 4:3. A video inserted in an earlier version is 16:9 until it is inserted again. 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_.+ * _Size_: a _Medium_ video can be resized, a _Full_ video takes the width of the note, or less when it would be taller than most of the window. 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.@@ -101,7 +101,7 @@ On a [shared page](../../Advanced%20Usage/Sharing.md), the video keeps its widthWhen you insert a link preview, Trilium fetches metadata once and stores it with the note:-* **YouTube URLs**: 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.+* **YouTube URLs**: the title, the channel name and the shape of the video are fetched via YouTube's public oEmbed endpoint, and the video's thumbnail is downloaded at up to 1280×720.* **All other URLs**: Trilium fetches the page and reads OpenGraph tags (`og:title`, `og:description`, `og:image`, `og:site_name`), falling back to the page's `<title>` and `<meta name="description">`. The site's favicon and the page's image are downloaded as well.The text is kept in the note's HTML. The images are kept as system <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/Notes/Attachments.md">Attachments</a> of the note, listed under _Generated by Trilium_.diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 2fa0b5f03a..73de8b52db 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -9,6 +9,7 @@ declare global {favicon?: string;siteName?: string;image?: string;+ aspectRatio?: string;/*** True when the host could not read the page (network error, bot challenge, non-HTML* response, or a page with no title of its own) and the fields above hold nothing but adiff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex c0cc625d91..d97ab156a8 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -45,7 +45,9 @@ 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';+import ContentEmbedVideo, {+ getVideoMediumWidth, getVideoPreview, getVideoShapeAttributes, isVideoEmbed+} from './video_embed.js';export const COMMAND_NAME = 'insertContentEmbed';export const BOX_SIZE_COMMAND_NAME = 'contentEmbedBoxSize';@@ -658,7 +660,8 @@ class ContentEmbedEditing extends Plugin {...getFlagAttributes( modelElement ),...getDisplayModeAttributes( modelElement ),...getPositionAttributes( modelElement ),- ...getCodeViewAttributes( modelElement )+ ...getCodeViewAttributes( modelElement ),+ ...getVideoShapeAttributes( modelElement )} );const embedWrapper = viewWriter.createUIElement( 'div', {@@ -885,7 +888,8 @@ class ContentEmbedBoxSizeCommand extends Command {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 );+ writer.setAttribute( SIZE_ATTRIBUTES.width,+ getVideoMediumWidth( getVideoPreview( embedElement ) ), embedElement );}if ( options.value === 'tiny' ) {diff --git a/packages/ckeditor5/src/plugins/content_embed/video_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/video_embed.spec.tsindex 96aae86996..ecc3e8d0c7 100644--- a/packages/ckeditor5/src/plugins/content_embed/video_embed.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/video_embed.spec.ts@@ -11,8 +11,10 @@ import ContentEmbed, {TOGGLE_CAPTION_COMMAND_NAME,TOGGLE_TITLE_COMMAND_NAME} from "./content_embed.js";-import { isVideoEmbed, VIDEO_MEDIUM_WIDTH } from "./video_embed.js";+import { isVideoEmbed } from "./video_embed.js";+/** The width of a 16:9 video at Medium, 20em high. */+const VIDEO_MEDIUM_WIDTH = "35.6em";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"`@@ -98,11 +100,12 @@ describe("ContentEmbedVideo", () => {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"`;+ + ` data-url="${VIDEO_URL}" data-embed-type="youtube" data-aspect-ratio="9/16"`+ + ` 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("aspectRatio")).toBe("9/16");expect(embed.getAttribute("boxSize")).toBe("medium");expect(embed.getAttribute("hideTitle")).toBeUndefined();expect(embed.getAttribute("position")).toBe("wrap-left");@@ -178,6 +181,19 @@ describe("ContentEmbedVideo", () => {expect(classes()).not.toContain("ck-widget_resizable");});+ it("has the shape of its video, and at Medium the width of that shape 20em high", () => {+ const vertical = SAVED_PREVIEW.replace(">", ` data-aspect-ratio="9/16">`);+ editor.setData(`<p>Text</p>${SAVED_PREVIEW}${vertical}`);+ const figures = editor.editing.view.getDomRoot()+ ?.querySelectorAll<HTMLElement>("figure.include-note") ?? [];+ expect([ ...figures ].map((figure) => figure.style.getPropertyValue("--video-aspect-ratio")))+ .toEqual([ "", "0.5625" ]);++ selectBlock(2);+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "medium" });+ expect(getBlock(2).getAttribute(SIZE_ATTRIBUTES.width)).toBe("11.3em");+ });+it("takes a new width from its corner at Medium, its only handle", () => {const capture = vi.spyOn(Element.prototype, "setPointerCapture").mockImplementation(() => {});diff --git a/packages/ckeditor5/src/plugins/content_embed/video_embed.ts b/packages/ckeditor5/src/plugins/content_embed/video_embed.tsindex 4e29cd67ee..22e2923e8d 100644--- a/packages/ckeditor5/src/plugins/content_embed/video_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/video_embed.ts@@ -1,6 +1,6 @@import {- getLinkPreviewVideoId, LINK_PREVIEW_DATA_ATTRIBUTES, type LinkPreviewData, readLinkPreviewData,- readVideoEmbedBox+ getLinkPreviewVideoId, getVideoAspectRatio, LINK_PREVIEW_DATA_ATTRIBUTES, type LinkPreviewData,+ readLinkPreviewData, readVideoEmbedBox, VIDEO_ASPECT_RATIO_PROPERTY} from "@triliumnext/commons";import {type DowncastConversionApi,@@ -16,8 +16,10 @@ import {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 height of a Medium video, in em, as a Medium embed is high. */+const VIDEO_MEDIUM_HEIGHT = 20;+/** The shape of the player of a video that stores none. */+const DEFAULT_ASPECT_RATIO = 16 / 9;/** 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)[];@@ -62,10 +64,22 @@ export function createVideoEmbed(writer: ModelWriter, attributes: Record<string,...attributes,boxSize: "medium",hideTitle: true,- [SIZE_ATTRIBUTES.width]: VIDEO_MEDIUM_WIDTH+ [SIZE_ATTRIBUTES.width]: getVideoMediumWidth(attributes as Partial<LinkPreviewData>)});}+/** The width of the video of `preview` at Medium: 20em high, in the shape of the video. */+export function getVideoMediumWidth(preview: Pick<LinkPreviewData, "aspectRatio">) {+ const aspectRatio = getVideoAspectRatio(preview) ?? DEFAULT_ASPECT_RATIO;+ return `${Math.round(VIDEO_MEDIUM_HEIGHT * aspectRatio * 10) / 10}em`;+}++/** The style that gives the view of `embed` the shape of its video, when it stores one. */+export function getVideoShapeAttributes(embed: ModelElement): Record<string, string> {+ const aspectRatio = isVideoEmbed(embed) ? getVideoAspectRatio(getVideoPreview(embed)) : null;+ return aspectRatio ? { style: `${VIDEO_ASPECT_RATIO_PROPERTY}:${aspectRatio}` } : {};+}+/** Whether `embed` plays the video of a link preview. */export function isVideoEmbed(embed: ModelElement) {return !!embed.getAttribute("url");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 c298e7199a..9d715cf4ed 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@@ -119,7 +119,9 @@ describe("AutoLinkToMention", () => {});it("turns an embeddable URL left alone on its own line into a player", async () => {- embeddable(VIDEO_URL);+ fetchMetadata.mockResolvedValueOnce({+ ...META, url: VIDEO_URL, embedType: "youtube", aspectRatio: "9/16"+ });autoLinkIn(editor, urlLeftAloneOnItsOwnLine(VIDEO_URL), VIDEO_URL);await flushFetch();@@ -131,6 +133,8 @@ describe("AutoLinkToMention", () => {expect(embed?.getAttribute("embedType")).toBe("youtube");expect(embed?.getAttribute("title")).toBe(META.title);expect(embed?.getAttribute("boxSize")).toBe("medium");+ expect(embed?.getAttribute("aspectRatio")).toBe("9/16");+ expect(embed?.getAttribute("customWidth")).toBe("11.3em");});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 7935876c05..4918dc82f5 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_autodetect.ts@@ -1,7 +1,7 @@import { chooseLinkPreviewKind, isUrlAloneInBlock, type BlockChildLike } from '@triliumnext/commons';import { Plugin } from 'ckeditor5';import {- createLinkPreview, EMBEDDABLE_URL_REGEX, getLinkEmbedHost+ createLinkPreview, EMBEDDABLE_URL_REGEX, getLinkEmbedHost, getMetadataAttributes} from './link_embed_commands.js';/**@@ -135,15 +135,7 @@ export default class AutoLinkToMention extends Plugin {caretLeftBlock: this._caretLeftBlock(parentEl)});- const attributes = {- url: metadata.url,- embedType: metadata.embedType,- title: metadata.title,- description: metadata.description,- favicon: metadata.favicon,- siteName: metadata.siteName,- image: metadata.image- };+ const attributes = getMetadataAttributes(metadata);if (kind === 'mention') {// The URL's own range is passed to insertContent rather than selecteddiff --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 735fad9238..7b7744e7c5 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,7 +11,6 @@ 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";@@ -333,11 +332,18 @@ describe("LinkEmbed commands", () => {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+ boxSize: "medium", hideTitle: true, customWidth: "35.6em"});expect(editor.model.document.selection.getSelectedElement()).toBe(embed);expect(findElement(editor, "linkMention")).toBeUndefined();+ setModelData(editor.model, `<paragraph>[<linkMention url="${url}" embedType="youtube"`+ + ` aspectRatio="9/16"></linkMention>]</paragraph>`);+ editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "embed" });+ const vertical = findElement(editor, "contentEmbed");+ expect([ vertical?.getAttribute("aspectRatio"), vertical?.getAttribute("customWidth") ])+ .toEqual([ "9/16", "11.3em" ]);+setModelData(editor.model, `<paragraph>[<linkMention url="https://youtube.com/watch"`+ ` embedType="youtube"></linkMention>]</paragraph>`);editor.execute(CHANGE_LINK_DISPLAY_COMMAND, { value: "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 fb22486c86..614d7b4be2 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_commands.ts@@ -1,4 +1,6 @@-import { getLinkPreviewVideoId, isHttpUrl } from '@triliumnext/commons';+import {+ getLinkPreviewVideoId, isHttpUrl, LINK_PREVIEW_DATA_ATTRIBUTES, type LinkPreviewData+} from '@triliumnext/commons';import {Command, type Editor, findAttributeRange, type ModelElement, ModelLiveRange, type ModelRange,type ModelWriter@@ -53,10 +55,15 @@ export function getLinkDisplayModeLabel(t: (message: string) => string, mode: Li*/export const EMBEDDABLE_URL_REGEX = /^https?:\/\/\S+$/;+export type MetaKey = keyof LinkPreviewData;+/** Every piece of fetched metadata a linkEmbed/linkMention element stores as a model attribute. */-export const META_KEYS = ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'] as const;+export const META_KEYS = Object.keys(LINK_PREVIEW_DATA_ATTRIBUTES) as MetaKey[];-export type MetaKey = (typeof META_KEYS)[number];+/** The model attributes of a link preview made from the fetched `metadata`. */+export function getMetadataAttributes(metadata: LinkEmbedMetadata): Record<string, unknown> {+ return Object.fromEntries(META_KEYS.map((key) => [ key, metadata[key] ]));+}/*** Puts a link to `url` at the selection, or in place of the link or the link preview the selection@@ -279,15 +286,12 @@ async function replaceLinkWithPreview(if (!linkStillThere) return;const element = createLinkPreview(writer, mode, {- url: metadata.url,+ ...getMetadataAttributes(metadata),embedType: mode === 'embed'? getLinkEmbedHost(editor).detectEmbedType(href): metadata.embedType,title: title || metadata.title,- description: description || metadata.description,- favicon: metadata.favicon,- siteName: metadata.siteName,- image: metadata.image+ description: description || metadata.description});model.insertContent(element, currentRange);diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.tsindex de6f2b6f81..260dfbcec9 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_editing.ts@@ -1,5 +1,7 @@import { LINK_PREVIEW_DATA_ATTRIBUTES } from '@triliumnext/commons';-import { Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget } from 'ckeditor5';+import {+ Plugin, toWidget, type ViewElement, viewToModelPositionOutsideModelElement, Widget+} from 'ckeditor5';import ContentEmbed from '../content_embed/content_embed.js';import { preventCKEditorHandling, restoreRendererFocusOnInput } from '../widget_utils.js';import {@@ -49,7 +51,7 @@ export default class LinkEmbedEditing extends Plugin {schema.register('linkEmbed', {isObject: true,isBlock: true,- allowAttributes: ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'],+ allowAttributes: META_KEYS,allowWhere: '$block'});@@ -57,7 +59,7 @@ export default class LinkEmbedEditing extends Plugin {isInline: true,isObject: true,// Stores all metadata so we can switch to card/embed without re-fetching.- allowAttributes: ['url', 'embedType', 'title', 'description', 'favicon', 'siteName', 'image'],+ allowAttributes: META_KEYS,allowWhere: '$text'});}@@ -70,15 +72,7 @@ export default class LinkEmbedEditing extends Plugin {conversion.for('upcast').elementToElement({model: (viewElement, { writer }) => {- return writer.createElement('linkEmbed', {- url: viewElement.getAttribute('data-url'),- embedType: viewElement.getAttribute('data-embed-type'),- title: viewElement.getAttribute('data-title'),- description: viewElement.getAttribute('data-description'),- favicon: viewElement.getAttribute('data-favicon'),- siteName: viewElement.getAttribute('data-site-name'),- image: viewElement.getAttribute('data-image')- });+ return writer.createElement('linkEmbed', metadataModelAttributes(viewElement));},view: { name: 'section', classes: 'link-embed' }});@@ -103,6 +97,7 @@ export default class LinkEmbedEditing extends Plugin {const favicon = modelElement.getAttribute('favicon') as string | undefined;const siteName = modelElement.getAttribute('siteName') as string | undefined;const image = modelElement.getAttribute('image') as string | undefined;+ const aspectRatio = modelElement.getAttribute('aspectRatio') as string | undefined;const section = writer.createContainerElement('section',@@ -114,7 +109,9 @@ export default class LinkEmbedEditing extends Plugin {'data-cke-ignore-events': 'true'}, function (domDocument) {const domElement = this.toDomElement(domDocument);- getLinkEmbedHost(editor).renderEmbed(domElement, { url, embedType, title, description, favicon, siteName, image }, true);+ getLinkEmbedHost(editor).renderEmbed(domElement, {+ url, embedType, title, description, favicon, siteName, image, aspectRatio+ }, true);preventCKEditorHandling(domElement, editor);return domElement;});@@ -134,15 +131,7 @@ export default class LinkEmbedEditing extends Plugin {conversion.for('upcast').elementToElement({model: (viewElement, { writer }) => {- return writer.createElement('linkMention', {- url: viewElement.getAttribute('data-url'),- embedType: viewElement.getAttribute('data-embed-type'),- title: viewElement.getAttribute('data-title'),- description: viewElement.getAttribute('data-description'),- favicon: viewElement.getAttribute('data-favicon'),- siteName: viewElement.getAttribute('data-site-name'),- image: viewElement.getAttribute('data-image')- });+ return writer.createElement('linkMention', metadataModelAttributes(viewElement));},view: { name: 'span', classes: 'link-mention' }});@@ -186,6 +175,13 @@ export default class LinkEmbedEditing extends Plugin {}}+/** The model attributes of a linkEmbed/linkMention element, read from its `data-*` attributes. */+function metadataModelAttributes(viewElement: ViewElement) {+ return Object.fromEntries(META_KEYS.map((key) => [+ key, viewElement.getAttribute(LINK_PREVIEW_DATA_ATTRIBUTES[key])+ ]));+}+/*** Builds the widget wrapper's class + `data-*` attributes from a linkEmbed/linkMention element.*diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.tsindex c432f81a3b..ea21a18610 100644--- a/packages/commons/src/lib/link_embed.ts+++ b/packages/commons/src/lib/link_embed.ts@@ -174,6 +174,8 @@ export interface LinkEmbedMetadata {favicon?: string;siteName?: string;embedType: "youtube" | "opengraph";+ /** The shape of a video, as its width and height in whole numbers, such as `9/16`. */+ aspectRatio?: string;/*** True when the page could not be read at all — a network error, a bot challenge (many sites* answer a server-side fetch with a Cloudflare interstitial), a non-HTML response, or a pagediff --git a/packages/commons/src/lib/link_embed_markup.spec.ts b/packages/commons/src/lib/link_embed_markup.spec.tsindex 02d2d93436..234d40e08c 100644--- a/packages/commons/src/lib/link_embed_markup.spec.ts+++ b/packages/commons/src/lib/link_embed_markup.spec.ts@@ -1,8 +1,9 @@import { describe, expect, it } from "vitest";import {- getLinkPreviewVideoId, LINK_EMBED_CARD_IMAGE_PLACEHOLDER, LINK_PREVIEW_DATA_ATTRIBUTES,- readLinkPreviewData, readVideoEmbedBox, renderLinkEmbedHtml, renderLinkMentionHtml+ getLinkPreviewVideoId, getVideoAspectRatio, LINK_EMBED_CARD_IMAGE_PLACEHOLDER,+ LINK_PREVIEW_DATA_ATTRIBUTES, readLinkPreviewData, readVideoEmbedBox, renderLinkEmbedHtml,+ renderLinkMentionHtml} from "./link_embed_markup.js";const OPTIONS = { playVideoLabel: "Play \"video\"" };@@ -61,6 +62,16 @@ describe("getLinkPreviewVideoId", () => {});});+describe("getVideoAspectRatio", () => {+ it("reads a width and a height in whole numbers, and nothing else", () => {+ expect([ "9/16", "16/9", "4/3" ].map((aspectRatio) => getVideoAspectRatio({ aspectRatio })))+ .toEqual([ 9 / 16, 16 / 9, 4 / 3 ]);+ expect([ undefined, null, "", "1.5", "0/9", "9/0", "9 / 16", "1/2/3", "12345/1", "-9/16" ]+ .map((aspectRatio) => getVideoAspectRatio({ aspectRatio })))+ .toEqual(Array(10).fill(null));+ });+});+describe("renderLinkMentionHtml", () => {it("links the favicon and title, escaped, in a new tab unless editable", () => {expect(renderLinkMentionHtml({@@ -108,6 +119,16 @@ describe("renderLinkEmbedHtml", () => {+ `</span></button></div>`);});+ it("gives the player the shape of its video, when the preview stores a valid one", () => {+ const render = (aspectRatio: string) => renderLinkEmbedHtml({+ url: VIDEO_URL, embedType: "youtube", aspectRatio+ }, OPTIONS);++ expect(render("9/16")).toMatch(+ /^<div class="link-embed-video" style="--video-aspect-ratio:0\.5625"><button /);+ expect(render("9/16\"><script>")).toMatch(/^<div class="link-embed-video"><button /);+ });+it("draws a card for a video URL stored as a card, and for an embed that is no video", () => {expect(renderLinkEmbedHtml({ url: VIDEO_URL, embedType: "opengraph" }, OPTIONS)).toContain(`<a class="link-embed-card"`);diff --git a/packages/commons/src/lib/link_embed_markup.ts b/packages/commons/src/lib/link_embed_markup.tsindex 52412b0e05..f556429b40 100644--- a/packages/commons/src/lib/link_embed_markup.ts+++ b/packages/commons/src/lib/link_embed_markup.ts@@ -13,6 +13,8 @@ export interface LinkPreviewData {image?: string | null;favicon?: string | null;siteName?: string | null;+ /** The shape of a video, as its width and height in whole numbers, such as `9/16`. */+ aspectRatio?: string | null;}export interface LinkPreviewMarkupOptions {@@ -30,9 +32,13 @@ export const LINK_PREVIEW_DATA_ATTRIBUTES = {description: "data-description",image: "data-image",favicon: "data-favicon",- siteName: "data-site-name"+ siteName: "data-site-name",+ aspectRatio: "data-aspect-ratio"} as const satisfies Record<keyof LinkPreviewData, string>;+/** The custom property that gives the player of a video, and its box, the shape of the video. */+export const VIDEO_ASPECT_RATIO_PROPERTY = "--video-aspect-ratio";+/*** 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`.@@ -51,10 +57,21 @@ export function readLinkPreviewData(getAttribute: (name: string) => string | nuldescription: getAttribute(attributes.description),image: getAttribute(attributes.image),favicon: getAttribute(attributes.favicon),- siteName: getAttribute(attributes.siteName)+ siteName: getAttribute(attributes.siteName),+ aspectRatio: getAttribute(attributes.aspectRatio)} satisfies LinkPreviewData;}+/**+ * The width of the video of `preview` divided by its height, or `null` when the preview stores+ * no valid shape, as a video inserted before Trilium read the shape does. Its player is 16:9.+ */+export function getVideoAspectRatio({ aspectRatio }: Pick<LinkPreviewData, "aspectRatio">) {+ const [ width, height ] = aspectRatio?.match(/^(\d{1,4})\/(\d{1,4})$/)?.slice(1).map(Number)+ ?? [];+ return width && height ? width / height : null;+}+/** The box sizes of a video embed. */export const VIDEO_EMBED_BOX_SIZES = [ "medium", "full" ] as const;@@ -102,7 +119,9 @@ export function renderLinkEmbedHtml(data: LinkPreviewData, options: LinkPreviewMconst videoId = getLinkPreviewVideoId(data);if (videoId) {const label = escapeHtml(options.playVideoLabel);- return `<div class="link-embed-video">`+ const aspectRatio = getVideoAspectRatio(data);+ const style = aspectRatio ? ` style="${VIDEO_ASPECT_RATIO_PROPERTY}:${aspectRatio}"` : "";+ return `<div class="link-embed-video"${style}>`+ `<button type="button" class="link-embed-video-facade"`+ ` data-video-id="${escapeHtml(videoId)}"`+ ` aria-label="${label}" title="${label}">`diff --git a/packages/share-theme/src/content/link_embed.css b/packages/share-theme/src/content/link_embed.cssindex d60ab2f5e3..125da9d3f2 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: var(--include-note-width, 640px);+ max-width: min(var(--include-note-width, 640px), 70vh * var(--video-aspect-ratio, 16 / 9));margin: auto;border-radius: 8px;overflow: hidden;@@ -84,7 +84,7 @@ html.theme-light .link-embed-favicon-light {.link-embed-video iframe {width: 100%;- aspect-ratio: 16 / 9;+ aspect-ratio: var(--video-aspect-ratio, 16 / 9);border: none;display: block;}@@ -97,7 +97,7 @@ html.theme-light .link-embed-favicon-light {position: relative;display: block;width: 100%;- aspect-ratio: 16 / 9;+ aspect-ratio: var(--video-aspect-ratio, 16 / 9);padding: 0;border: none;background: #000;diff --git a/packages/trilium-core/src/routes/api/link_embed.spec.ts b/packages/trilium-core/src/routes/api/link_embed.spec.tsindex 644cae8a70..e352194205 100644--- a/packages/trilium-core/src/routes/api/link_embed.spec.ts+++ b/packages/trilium-core/src/routes/api/link_embed.spec.ts@@ -233,6 +233,31 @@ describe("link-embed getMetadata", () => {expect(result.favicon).toMatch(/^api\/attachments\/att\d+\/image\/www\.youtube\.com\.ico$/);});+ it("reads the shape of the video from oEmbed for its /shorts/ address", async () => {+ const answers = [+ [ { width: 200, height: 113 }, "16/9" ],+ [ { width: 113, height: 200 }, "9/16" ],+ [ { width: 200, height: 150 }, "4/3" ],+ [ { width: 200, height: 83 }, "12/5" ],+ [ { width: 200 }, undefined ],+ [ { width: "200", height: "113" }, undefined ],+ [ { width: 200.5, height: 113 }, undefined ]+ ] as const;++ const shapes: unknown[] = [];+ for (const [ answer ] of answers) {+ safeFetch.mockImplementation(async (url: string) => url.includes("oembed")+ ? fakeResponse("", { json: { title: "A video", ...answer } })+ : fakeResponse("", { ok: false }));+ const result = await linkEmbedRoute.getMetadata(req("https://youtu.be/dQw4w9WgXcQ"));+ shapes.push(result.aspectRatio);+ }++ expect(shapes).toEqual(answers.map(([ , shape ]) => shape));+ expect(safeFetch).toHaveBeenCalledWith("https://www.youtube.com/oembed?url="+ + "https%3A%2F%2Fwww.youtube.com%2Fshorts%2FdQw4w9WgXcQ&format=json", expect.anything());+ });+describe("YouTube thumbnails", () => {type ThumbnailName = "maxresdefault" | "sddefault" | "hqdefault";diff --git a/packages/trilium-core/src/routes/api/link_embed.ts b/packages/trilium-core/src/routes/api/link_embed.tsindex a46b08b144..e0b9b8f559 100644--- a/packages/trilium-core/src/routes/api/link_embed.ts+++ b/packages/trilium-core/src/routes/api/link_embed.ts@@ -499,7 +499,7 @@ function rankFavicon(rel: string, href: string, type: string | undefined, sizes:*/async function fetchYouTubeMetadata(url: string, videoId: string): Promise<FetchedPreview> {const [ details, favicon, image ] = await Promise.all([- fetchYouTubeDetails(url),+ fetchYouTubeDetails(videoId),downloadFavicon("https://www.youtube.com/favicon.ico"),downloadYouTubeThumbnail(videoId)]);@@ -511,24 +511,57 @@ async function fetchYouTubeMetadata(url: string, videoId: string): Promise<Fetch};}-/** The video's title and channel name from oEmbed, or a generic title when oEmbed fails. */+/**+ * The video's title, channel name and shape from oEmbed, or a generic title when oEmbed fails.+ * oEmbed reads the `/shorts/` address of the video, which reports the shape of the video itself:+ * the watch address of a Short reports the 16:9 player of the watch page.+ */async function fetchYouTubeDetails(- url: string-): Promise<Pick<LinkEmbedMetadata, "title" | "description">> {+ videoId: string+): Promise<Pick<LinkEmbedMetadata, "title" | "description" | "aspectRatio">> {try {- const oembedUrl = `https://www.youtube.com/oembed?url=${encodeURIComponent(url)}`+ const videoUrl = `https://www.youtube.com/shorts/${videoId}`;+ const oembedUrl = `https://www.youtube.com/oembed?url=${encodeURIComponent(videoUrl)}`+ "&format=json";const response = await request.fetchResource(oembedUrl, { maxBytes: MAX_OEMBED_SIZE });if (!response.ok) throw new Error(`HTTP ${response.status}`);const data = JSON.parse(asText(response));- return { title: data.title || undefined, description: data.author_name || undefined };+ return {+ title: data.title || undefined,+ description: data.author_name || undefined,+ aspectRatio: toAspectRatio(data.width, data.height)+ };} catch {return { title: "YouTube Video" };}}+/**+ * The simplest ratio `<width>/<height>` that oEmbed's whole-pixel `width` and `height` can round+ * from, such as `16/9` for 200x113, or `undefined` when they are not whole numbers.+ */+function toAspectRatio(width: unknown, height: unknown) {+ if (!isPositiveInteger(width) || !isPositiveInteger(height)) {+ return undefined;+ }++ const min = (width - 0.5) / (height + 0.5);+ const max = (width + 0.5) / (height - 0.5);+ // Ends by `height` at the latest, where `width` itself is in range.+ for (let denominator = 1; ; denominator++) {+ const numerator = Math.ceil(min * denominator);+ if (numerator / denominator <= max) {+ return `${numerator}/${denominator}`;+ }+ }+}++function isPositiveInteger(value: unknown): value is number {+ return typeof value === "number" && Number.isInteger(value) && value > 0;+}+/*** Downloads the largest thumbnail YouTube has for the video, at most 1280x720. The JPEG is stored* as served, so no decoder is needed and every runtime keeps the same picture.