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
feat(text): keep a Mermaid diagram's source inline, as an embed of a code block
Elian Doran3a7fa98e8999
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.tsindex e33b887a6d..d581b59f5e 100644--- a/apps/client/src/menus/link_context_menu.ts+++ b/apps/client/src/menus/link_context_menu.ts@@ -59,6 +59,27 @@ async function openContextMenu(});}+/**+ * Opens the menu of the embed at `e` with its own commands only, for an embed that shows no note or+ * attachment, such as one that keeps its source in the note.+ */+async function openEmbedContextMenu(e: LinkMenuOrigin) {+ const request = ++lastMenuRequest;+ const editor = await getEditingTextEditor(getTarget(e));+ const embed = editor && getMenuEmbed(e, editor);+ if (!editor || !embed || request !== lastMenuRequest) {+ return;+ }++ contextMenu.show({+ x: e.pageX,+ y: e.pageY,+ items: getEmbedItems(embed),+ selectMenuItemHandler: () => {},+ ...keepEditorFocused(editor)+ });+}+/*** Menu options adding the menu to the focus tracker of `editor`, so that the editor stays focused* while the menu is up.@@ -430,5 +451,6 @@ export default {getOpenNoteItem,handleLinkContextMenuItem,openContextMenu,+ openEmbedContextMenu,setShareLinkResolver};diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex ab3a77d3ca..f93f6ac726 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -34,6 +34,7 @@ import { waitForPendingRenders } from "./pending_renders.js";import protectedSessionService from "./protected_session.js";import protectedSessionHolder from "./protected_session_holder.js";import server from "./server.js";+import { getSourceEmbedTypeByContentType } from "./source_embeds.js";import { applySingleBlockSyntaxHighlight } from "./syntax_highlight.js";import { getErrorMessage } from "./utils.js";@@ -209,8 +210,8 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNoawait renderIconPack(entity, $renderedContent, options);} else if (type === "canvasDrawing") {await renderCanvasDrawing(entity, $renderedContent, options);- } else if (type === "mermaidDiagram") {- await renderMermaidDiagram(entity, $renderedContent, options);+ } else if (getSourceEmbedTypeByContentType(type)) {+ await renderSourceEmbed(entity, type, $renderedContent, options);} else if (type === "image" && options.mediaEnvironment === "embedded") {await renderImageViewer(entity, $renderedContent);} else if (["image", "canvas", "mermaid", "mindMap", "spreadsheet"].includes(type)) {@@ -295,7 +296,7 @@ export const CONTENT_RENDERERS = {image: () => import("../widgets/react/ImageViewer"),file: {canvasDrawing: () => import("../widgets/type_widgets/canvas/CanvasDrawing"),- mermaidDiagram: () => import("../widgets/type_widgets/mermaid/MermaidDiagram"),+ sourceEmbed: () => import("../widgets/type_widgets/text/SourceEmbed"),pdf: () => import("../widgets/type_widgets/file/PdfViewer"),media: () => import("../widgets/type_widgets/file/MediaPreview")},@@ -591,22 +592,32 @@ async function renderCanvasDrawing(}/**- * Renders a Mermaid diagram kept in a file or an attachment, in a zoom/pan viewer. Interactive- * content of an attachment is edited beside the diagram while the Editable toggle of its embed is on.+ * Renders the source of a {@link SourceEmbedType} kept in a file or an attachment, such as a Mermaid+ * diagram. Interactive content of an attachment can be edited while the Editable toggle of its+ * embed is on.*/-async function renderMermaidDiagram(+async function renderSourceEmbed(entity: FNote | FAttachment,+ type: string,$renderedContent: JQuery<HTMLElement>,options: RenderOptions) {- const { default: MermaidDiagram } = await CONTENT_RENDERERS.file.mermaidDiagram();+ const sourceType = getSourceEmbedTypeByContentType(type);+ if (!sourceType) return;++ const [ { default: AttachmentSourceEmbed }, component ] = await Promise.all([+ CONTENT_RENDERERS.file.sourceEmbed(),+ sourceType.load()+ ]);const editor = options.interactive ? getContentEditor(entity, options) : undefined;const content = editor?.getUnsavedContent() ?? (await entity.getBlob())?.content ?? "";- const $container = $('<div class="mermaid-diagram-embed">');+ const $container = $('<div class="source-embed">');const container = $container.get(0);if (container) {- await mountInteractiveWidget(h(MermaidDiagram, { entity, editor, content }), container);+ await mountInteractiveWidget(+ h(AttachmentSourceEmbed, { entity, editor, content, component }), container+ );}$renderedContent.append($container);}diff --git a/apps/client/src/services/source_embeds.ts b/apps/client/src/services/source_embeds.tsnew file mode 100644index 0000000000..f873f68018--- /dev/null+++ b/apps/client/src/services/source_embeds.ts@@ -0,0 +1,59 @@+import { MERMAID_ATTACHMENT_MIME } from "@triliumnext/commons";+import type { ComponentType } from "preact";++import type { ContentEditor } from "./content_renderer";++/** What the component of a {@link SourceEmbedType} receives, wherever its source is stored. */+export interface SourceEmbedProps {+ /** The saved source. It changes when the source is saved elsewhere, or undone. */+ content: string;+ /** Saves the edited source. Without it the content is read-only. */+ editor?: ContentEditor;+}++/**+ * A kind of content that an embed in a text note shows from a source, such as a Mermaid diagram.+ * The source is stored in one of two ways, and its component works the same with both:+ *+ * - inline, as a `<pre><code class="language-…">` code block of the note, of {@link language};+ * - in an attachment of the note, of media type {@link mime}.+ */+export interface SourceEmbedType {+ /** The language of the code block that keeps the source inline. */+ language: string;+ /** The media type of an attachment that keeps the source. */+ mime: string;+ /** The content type that `getRenderedContent()` names the content, for its styles. */+ contentType: string;+ /** Loads the component that shows and edits the source. */+ load(): Promise<ComponentType<SourceEmbedProps>>;+ /** Renders `source` into `container` as a static picture, outside an embed. */+ renderPreview(source: string, container: HTMLElement): Promise<void>;+}++export const SOURCE_EMBED_TYPES: readonly SourceEmbedType[] = [+ {+ language: "mermaid",+ mime: MERMAID_ATTACHMENT_MIME,+ contentType: "mermaidDiagram",+ load: async () => (await import("../widgets/type_widgets/mermaid/MermaidDiagram")).default,+ async renderPreview(source, container) {+ const { renderMermaidSvg } = await import("./mermaid");+ try {+ container.innerHTML = await renderMermaidSvg(source);+ } catch (e) {+ container.textContent = (e as Error)?.message ?? String(e);+ }+ }+ }+];++/** The type of the source embeds whose code blocks are of `language`, or `undefined`. */+export function getSourceEmbedTypeByLanguage(language: string) {+ return SOURCE_EMBED_TYPES.find((type) => type.language === language);+}++/** The type of the source embeds whose content type is `contentType`, or `undefined`. */+export function getSourceEmbedTypeByContentType(contentType: string) {+ return SOURCE_EMBED_TYPES.find((type) => type.contentType === contentType);+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex fbb528f2bb..d3718287b4 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4455,9 +4455,7 @@"numbered-list": "Numbered list","outdent": "Outdent","plain-link": "Plain link",- "preview": "Preview","quote-a-passage-from-another-source": "Quote a passage from another source.",- "read-more-about-mermaid-diagram-syntax": "Read more about Mermaid diagram syntax","remove-anchor": "Remove anchor","result": "Result","right-click-or-press-0-to-change-state": "Right-click or press %0 to change state.",@@ -4465,8 +4463,6 @@"search-text-snippet": "Search text snippet","select-collapsible-block": "Select collapsible block","send": "Send",- "source-view": "Source view",- "split-view": "Split view","stop": "Stop","summary": "Summary","task-state": "Task state:",@@ -4526,8 +4522,6 @@"drawing-canvas": "Drawing canvas","editable": "Editable","insert-a-canvas-to-draw-on": "Insert a canvas to draw on.",- "mermaid-diagram-embedded": "Mermaid diagram (embedded)",- "insert-a-mermaid-diagram-stored-as-an-attachment": "Insert a Mermaid diagram stored as an attachment.","tabs": "Tabs","tab-title": "Tab title","tab-0": "Tab %0",diff --git a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsxindex 3011a4d695..6710793da9 100644--- a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx+++ b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx@@ -11,16 +11,13 @@ import { lazy, Suspense } from "preact/compat";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";-import type FAttachment from "../../../entities/fattachment";-import FNote from "../../../entities/fnote";-import type { ContentEditor } from "../../../services/content_renderer";import { t } from "../../../services/i18n";import { renderMermaidSvg } from "../../../services/mermaid";+import type { SourceEmbedProps } from "../../../services/source_embeds";import OverlayControlGroup, { ZoomControls } from "../../react/OverlayControlGroup";import { RawHtmlBlock } from "../../react/RawHtml";import { useZoomPanPinch, useZoomPanWheel } from "../../react/zoom_pan";import { useZoomPanKeyboard, ZOOM_PAN_VIEWPORT_CLASS } from "../../react/zoom_pan_keyboard";-import { useSavedContent } from "../code/CodeEmbed";import mermaidLinter from "../linters/mermaid";import {type ContentEmbedTool,@@ -32,23 +29,15 @@ import { useEditableEmbed } from "../text/editable_embed";const CodeEmbedEditor = lazy(() => import("../code/CodeEmbedEditor"));-interface MermaidDiagramProps {- entity: FNote | FAttachment;- /** Saves the changes. Without it the diagram is read-only. */- editor?: ContentEditor;- /** The source shown first. */- content: string;-}-/*** A Mermaid diagram in an embed, shown in a zoom/pan viewer, and edited in CodeMirror beside it* while the Editable toggle of its embed is on. The zoom and fullscreen are buttons of the toolbar- * of the embed.+ * of the embed. The source is kept inline or in an attachment, see `SOURCE_EMBED_TYPES`.*/-export default function MermaidDiagram({ entity, editor, content: initialContent }: MermaidDiagramProps) {+export default function MermaidDiagram({ content, editor }: SourceEmbedProps) {const rootRef = useRef<HTMLDivElement>(null);const [ previewEl, setPreviewEl ] = useState<HTMLDivElement | null>(null);- const [ source, setSource ] = useState(initialContent);+ const [ source, setSource ] = useState(content);const { svg, error } = useMermaidRender(source);const zoom = useZoomPanPinch({ minScale: MIN_ZOOM, maxScale: MAX_ZOOM });@@ -56,12 +45,17 @@ export default function MermaidDiagram({ entity, editor, content: initialContenttools.setZoom(zoom);const { canEdit, isEditing } = useEditableEmbed(rootRef, {editor,- note: entity instanceof FNote ? entity : null,+ note: null,tools,focusTarget: ".cm-content"});- useSavedContent(entity, editor, setSource);+ // A source saved elsewhere, or undone, replaces the shown one unless it has unsaved edits.+ useEffect(() => {+ if (editor?.getUnsavedContent() === undefined) {+ setSource(content);+ }+ }, [ content ]);useZoomPanKeyboard(zoom.ref, previewEl);useZoomPanWheel(zoom.ref, previewEl, true);diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsxindex d37aaa524c..3b986e0732 100644--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx@@ -30,13 +30,16 @@ export interface ContentEmbedAction {export interface ContentEmbedProps {boxSize?: string;- /** The link to the embedded note or attachment, shown as the title. */- title: HTMLElement;+ /**+ * The link to the embedded note or attachment, shown as the title. Content kept in the note+ * itself has none, and no title row.+ */+ title?: HTMLElement;/** The rendered note or attachment. */content: HTMLElement;contentType: string;/** The note opened by the buttons in the title row. */- notePath: string;+ notePath?: string;viewScope?: ViewScope;/** Whether the embed shows only some blocks of its note, from a block reference. */isExcerpt?: boolean;@@ -69,7 +72,7 @@ export default function ContentEmbed({useWindowShortcuts(contentRef);const [ isExpanded, setIsExpanded ] = useState(false);const focusContentAfterRender = useFocusAfterRender(contentRef);- const isExpandable = boxSize === "expandable";+ const isExpandable = boxSize === "expandable" && !!title && !!notePath;const hasFullscreen = !isExcerpt && (boxSize === "medium" || boxSize === "full");useLayoutEffect(() => {@@ -90,7 +93,7 @@ export default function ContentEmbed({return (<>- <div+ {title && notePath && <divclassName="include-note-title-row"onClick={(e) => {if (isExpandable && isTogglingClick(e)) {@@ -143,7 +146,7 @@ export default function ContentEmbed({/>)}<MoreActionsButton notePath={notePath} viewScope={viewScope} />- </div>+ </div>}<divref={bodyRef}className={clsx("include-note-body", isContentActive && "active")}diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex c77f8fea3c..ab12867a69 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -7,6 +7,7 @@ import {CKTextEditor,type FileUploadData,type FileUploadEvent,+ type InlineEmbedSource,SnippetDefinition} from "@triliumnext/ckeditor5";import { deferred, formatBlockRange, parseBlockRange } from "@triliumnext/commons";@@ -50,6 +51,7 @@ import {getAttachmentHref,loadEmbeddedAttachment,loadEmbeddedNote,+ loadInlineEmbed,openContentEmbedMenu,refreshEmbeddedNote,setupImageOpening,@@ -295,6 +297,14 @@ export default function EditableText({isFocused});},+ loadInlineEmbed(+ source: InlineEmbedSource,+ $el: JQuery<HTMLElement>,+ boxSize: string | undefined,+ options: { isFocused: boolean }+ ) {+ return loadInlineEmbed(source, $el, boxSize, options);+ },focusContentEmbed(attachmentId: string) {focusedAttachmentIdRef.current = attachmentId;},diff --git a/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsxnew file mode 100644index 0000000000..e46de1e637--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx@@ -0,0 +1,111 @@+import type { InlineEmbedSource } from "@triliumnext/ckeditor5";+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { SourceEmbedProps } from "../../../services/source_embeds";+import { createInlineSourceEditor, InlineSourceEmbed } from "./SourceEmbed";++/** An inline source as the text editor hands it over, which notifies its listeners on writes. */+function createSource(initial: string, isReadOnly = false): InlineEmbedSource {+ let source = initial;+ const listeners = new Set<() => void>();+ return {+ language: "mermaid",+ getSource: () => source,+ setSource: vi.fn((value: string) => {+ source = value;+ for (const listener of listeners) listener();+ }),+ subscribe: (callback) => {+ listeners.add(callback);+ return () => listeners.delete(callback);+ },+ isReadOnly: () => isReadOnly+ };+}++afterEach(() => {+ vi.useRealTimers();+});++describe("createInlineSourceEditor", () => {+ it("writes the latest content once it stops changing, and keeps it unsaved until then", () => {+ vi.useFakeTimers();+ const source = createSource("a");+ const editor = createInlineSourceEditor(source);+ const onSaved = vi.fn();++ expect(editor.canEdit()).toBe(true);+ expect(editor.getUnsavedContent()).toBeUndefined();++ editor.scheduleSave(() => "ab");+ editor.scheduleSave(() => "abc", onSaved);+ expect(editor.getUnsavedContent()).toBe("abc");+ expect(source.setSource).not.toHaveBeenCalled();++ vi.advanceTimersByTime(500);+ expect(source.setSource).toHaveBeenCalledExactlyOnceWith("abc");+ expect(onSaved).toHaveBeenCalledWith("abc");+ expect(editor.getUnsavedContent()).toBeUndefined();+ });++ it("writes pending content at once when released, and nothing when there is none", () => {+ vi.useFakeTimers();+ const source = createSource("a");+ const editor = createInlineSourceEditor(source);++ editor.release();+ expect(source.setSource).not.toHaveBeenCalled();++ editor.scheduleSave(() => "b");+ editor.release();+ expect(source.setSource).toHaveBeenCalledExactlyOnceWith("b");++ vi.advanceTimersByTime(500);+ expect(source.setSource).toHaveBeenCalledOnce();+ });++ it("cannot edit the source of a read-only text editor", () => {+ expect(createInlineSourceEditor(createSource("a", true)).canEdit()).toBe(false);+ });+});++describe("InlineSourceEmbed", () => {+ it("passes the source and its editor to the component, and the source again once it changes", () => {+ const container = document.createElement("div");+ const source = createSource("graph TD;");+ const shown: SourceEmbedProps[] = [];+ const Probe = (props: SourceEmbedProps) => {+ shown.push(props);+ return null;+ };++ act(() => render(<InlineSourceEmbed source={source} component={Probe} />, container));+ expect(shown.at(-1)?.content).toBe("graph TD;");+ expect(shown.at(-1)?.editor?.canEdit()).toBe(true);++ // As an undo in the text editor changes the source.+ act(() => source.setSource("graph LR;"));+ expect(shown.at(-1)?.content).toBe("graph LR;");++ act(() => render(null, container));+ });++ it("writes the unsaved content when it goes away", () => {+ vi.useFakeTimers();+ const container = document.createElement("div");+ const source = createSource("a");+ let editor: SourceEmbedProps["editor"];+ const Probe = (props: SourceEmbedProps) => {+ editor = props.editor;+ return null;+ };++ act(() => render(<InlineSourceEmbed source={source} component={Probe} />, container));+ editor?.scheduleSave(() => "b");+ act(() => render(null, container));++ expect(source.setSource).toHaveBeenCalledExactlyOnceWith("b");+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx b/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsxnew file mode 100644index 0000000000..21e05a7d6a--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx@@ -0,0 +1,78 @@+import type { InlineEmbedSource } from "@triliumnext/ckeditor5";+import type { ComponentType } from "preact";+import { useSyncExternalStore } from "preact/compat";+import { useEffect, useMemo, useState } from "preact/hooks";++import type FAttachment from "../../../entities/fattachment";+import type FNote from "../../../entities/fnote";+import type { ContentEditor } from "../../../services/content_renderer";+import type { SourceEmbedProps } from "../../../services/source_embeds";+import { useSavedContent } from "../code/CodeEmbed";++interface AttachmentSourceEmbedProps {+ entity: FNote | FAttachment;+ editor: ContentEditor | undefined;+ /** The source shown first. */+ content: string;+ component: ComponentType<SourceEmbedProps>;+}++/** The component of a source embed type, over a source kept in a note or an attachment. */+export default function AttachmentSourceEmbed({+ entity, editor, content: initialContent, component: Component+}: AttachmentSourceEmbedProps) {+ const [ content, setContent ] = useState(initialContent);+ useSavedContent(entity, editor, setContent);++ return <Component content={content} editor={editor} />;+}++interface InlineSourceEmbedProps {+ source: InlineEmbedSource;+ component: ComponentType<SourceEmbedProps>;+}++/** The component of a source embed type, over a source kept inline in the text note. */+export function InlineSourceEmbed({ source, component: Component }: InlineSourceEmbedProps) {+ const content = useSyncExternalStore(source.subscribe, source.getSource);+ const editor = useMemo(() => createInlineSourceEditor(source), [ source ]);+ useEffect(() => () => editor.release(), [ editor ]);++ return <Component content={content} editor={editor} />;+}++/**+ * The editor of a source kept inline, which writes the source into the text note a moment after+ * it stops changing, each write one step of the text editor's undo.+ */+export function createInlineSourceEditor(source: InlineEmbedSource): ContentEditor {+ let getPending: (() => string) | undefined;+ let timeout: ReturnType<typeof setTimeout> | undefined;++ const flush = () => {+ clearTimeout(timeout);+ timeout = undefined;+ const getContent = getPending;+ getPending = undefined;+ if (getContent) {+ source.setSource(getContent());+ }+ };++ return {+ canEdit: () => !source.isReadOnly(),+ getUnsavedContent: () => getPending?.(),+ scheduleSave(getContent, onSaved) {+ getPending = getContent;+ clearTimeout(timeout);+ timeout = setTimeout(() => {+ flush();+ onSaved?.(source.getSource());+ }, INLINE_SAVE_DELAY);+ },+ release: flush+ };+}++/** How long an inline source has to stay unchanged before it is written, in milliseconds. */+const INLINE_SAVE_DELAY = 500;diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex b4b2c164e3..7477fed099 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -84,7 +84,6 @@ vi.mock("../../../services/syntax_highlight.js", async (importOriginal) => ({}));// Heavy modules pulled in lazily by the editor config — replace with light stubs.-vi.mock("mermaid", () => ({ default: { name: "mermaid-stub" } }));vi.mock("@triliumnext/highlightjs", () => ({ default: { name: "hljs-stub" } }));vi.mock("../../../services/math.js", () => ({ default: { name: "katex-stub" } }));@@ -107,7 +106,7 @@ interface DynamicConfig {download(src: string): void;};math: { enableMathField: boolean; lazyLoad(): Promise<void> };- mermaid: { lazyLoad(): Promise<unknown> };+ contentEmbed: { inlineLanguages: string[] };syntaxHighlighting: { loadHighlightJs(): Promise<{ default: unknown }> };mention?: {feeds: unknown[];@@ -540,21 +539,25 @@ describe("CK config - image actions", () => {});describe("CK config - lazy loaders", () => {- it("lazy-loads KaTeX, Mermaid and highlight.js on demand", async () => {+ it("lazy-loads KaTeX and highlight.js on demand", async () => {const config = await buildDynamicConfig();await config.math.lazyLoad();expect((window as unknown as { katex: unknown }).katex).toEqual({ name: "katex-stub" });- const mermaid = await config.mermaid.lazyLoad();- expect(mermaid).toEqual({ name: "mermaid-stub" });-const hljs = await config.syntaxHighlighting.loadHighlightJs();expect(hljs.default).toEqual({ name: "hljs-stub" });expect(ensureMimeTypesForHighlighting).toHaveBeenCalled();});});+describe("CK config - inline embeds", () => {+ it("keeps the source of every source embed type inline, as a code block of its language", async () => {+ const config = await buildDynamicConfig();+ expect(config.contentEmbed.inlineLanguages).toEqual([ "mermaid" ]);+ });+});+describe("CK config - mention feed", () => {it("lists notes after @ as the note autocomplete does, only when note completion is enabled", async () => {const off = await buildDynamicConfig();diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex d31b3918f7..8396a413c6 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -7,13 +7,13 @@ import { copyHtmlWithToast, copyTextWithToast } from "../../../services/clipboarimport { t } from "../../../services/i18n.js";import imageService from "../../../services/image.js";import { getNoteImageSourceToLoad } from "../../../services/image_urls.js";-import { getMermaidConfig } from "../../../services/mermaid.js";import { default as mimeTypesService, getHighlightJsNameForMime } from "../../../services/mime_types.js";import options from "../../../services/options.js";import { sanitizeNoteContentHtml } from "../../../services/sanitize_content.js";+import { getSourceEmbedTypeByLanguage, SOURCE_EMBED_TYPES } from "../../../services/source_embeds.js";import { ensureMimeTypesForHighlighting, isSyntaxHighlightEnabled } from "../../../services/syntax_highlight.js";import { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../services/task_states.js";-import { isMac, isMobile, openInAppHelpFromUrl } from "../../../services/utils.js";+import { isMac, isMobile } from "../../../services/utils.js";import { resolveContentLanguage } from "../../../utils/formatters.js";import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";import buildAiAssistantStream, { type AiNoteLocationProvider, buildAiAssistantQuickActions } from "./ai_assistant_stream.js";@@ -69,10 +69,13 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfienableMathField: options.get("mathFieldEnabled") !== "false"},mermaid: {- lazyLoad: async () => (await import("mermaid")).default, // FIXME- config: getMermaidConfig(),- samples: SAMPLE_DIAGRAMS,- openHelp: () => openInAppHelpFromUrl("s1aBHPd79XYj")+ samples: SAMPLE_DIAGRAMS+ },+ contentEmbed: {+ inlineLanguages: SOURCE_EMBED_TYPES.map((type) => type.language),+ renderInlinePreview: (language, source, container) => {+ void getSourceEmbedTypeByLanguage(language)?.renderPreview(source, container);+ }},image: {styles: {@@ -205,10 +208,9 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConficopyHtml: copyHtmlWithToast},slashCommand: {- // Drop CKEditor's built-in slash commands whose title/icon the palette re-defines: the- // Mermaid one (generic icon) and the list ones (Title Case titles, normalized to- // sentence case).- removeCommands: ["insertMermaidCommand", "bulletedList", "numberedList"],+ // Drop CKEditor's built-in list slash commands, whose Title Case titles the palette+ // re-defines in sentence case.+ removeCommands: ["bulletedList", "numberedList"],list: createSlashCommandList},snippets: {diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts b/apps/client/src/widgets/type_widgets/text/toolbar.spec.tsindex 0d67131cac..78c851bc84 100644--- a/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/toolbar.spec.ts@@ -54,7 +54,7 @@ describe("CKEditor config", () => {});describe("the Insert group", () => {- it("offers the drawing canvas and the embedded Mermaid diagram above the Mermaid diagram, on both toolbars", () => {+ it("offers the drawing canvas above the Mermaid diagram, on both toolbars", () => {const toolbars = [buildClassicToolbar(false, true).toolbar.items,buildFloatingToolbar(true).blockToolbar@@ -64,8 +64,7 @@ describe("the Insert group", () => {&& "label" in item && item.label === "text-editor.toolbar-groups.insert");const groupItems = (group as { items: string[] } | undefined)?.items ?? [];const index = groupItems.indexOf("drawingCanvas");- expect(groupItems.slice(index, index + 3))- .toEqual([ "drawingCanvas", "mermaidDiagram", "mermaid" ]);+ expect(groupItems.slice(index, index + 2)).toEqual([ "drawingCanvas", "mermaid" ]);expect(items).not.toContain("drawingCanvas");}});diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.tsindex 842efb85c1..470d0941a2 100644--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts@@ -106,7 +106,7 @@ export function buildClassicToolbar(multilineToolbar: boolean, aiAssistant: bool"footnote",{...buildInsertGroup(),- items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaidDiagram", "mermaid", "horizontalLine", "pageBreak", "|", "dateTime", "specialCharacters", "emoji", "insertIcon"]+ items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "|", "dateTime", "specialCharacters", "emoji", "insertIcon"]},"|",buildAlignmentToolbar(),@@ -177,7 +177,7 @@ export function buildFloatingToolbar(aiAssistant: boolean) {"footnote",{...buildInsertGroup(),- items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaidDiagram", "mermaid", "horizontalLine", "pageBreak", "dateTime"]+ items: ["link", "linkEmbed", "bookmark", "internallink", "contentEmbed", "|", "collapsible", "tabs", "multicolumnLayout", "math", "drawingCanvas", "mermaid", "horizontalLine", "pageBreak", "dateTime"]},"|",buildAlignmentToolbar(),diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex 184e7216e0..b9ae90b812 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -1,15 +1,16 @@-import type { CKTextEditor } from "@triliumnext/ckeditor5";+import type { CKTextEditor, InlineEmbedSource } from "@triliumnext/ckeditor5";import { attachmentIcon } from "@triliumnext/commons";import { h, type JSX } from "preact";import appContext from "../../../components/app_context";import linkContextMenu from "../../../menus/link_context_menu";import content_renderer, {- type AttachmentEditor, type NoteEditor+ type AttachmentEditor, CONTENT_RENDERERS, type NoteEditor} from "../../../services/content_renderer";import { getEmbedCaption } from "../../../services/content_renderer_text";import froca from "../../../services/froca";import link, { ViewScope } from "../../../services/link";+import { getSourceEmbedTypeByLanguage } from "../../../services/source_embeds";import utils from "../../../services/utils";import { watchContentEmbedTools } from "./content_embed_tools";import ContentEmbed, { getNoteActions, TinyContentEmbed } from "./ContentEmbed";@@ -149,6 +150,37 @@ export async function loadEmbeddedAttachment(await mountEmbedBox(el, box, $renderedContent);}+/**+ * Fills an embed box with what an embed that keeps its source in the note shows, through the+ * component of the `SourceEmbedType` of its language. The box has no title row.+ */+export async function loadInlineEmbed(+ source: InlineEmbedSource,+ $el: JQuery<HTMLElement>,+ boxSize: string | undefined,+ { isFocused }: { isFocused: boolean }+) {+ const type = getSourceEmbedTypeByLanguage(source.language);+ if (!type) return;++ const el = $el[0];+ const [ component, { InlineSourceEmbed } ] = await Promise.all([+ type.load(),+ CONTENT_RENDERERS.file.sourceEmbed()+ ]);+ const $renderedContent = $('<div class="rendered-content">');+ const container = $('<div class="source-embed">').appendTo($renderedContent)[0];+ await content_renderer.mountInteractiveWidget(h(InlineSourceEmbed, { source, component }), container);++ const box = h(ContentEmbed, {+ boxSize: boxSize ?? getEmbedBoxSize(el),+ content: $renderedContent[0],+ contentType: type.contentType,+ ...(isFocused ? { isFocusedOnMount: true } : {})+ });+ await mountEmbedBox(el, box, $renderedContent);+}+/*** Mounts `box` in the embed `el`. An embed that left the page while it loaded gets no box,* and `content` rendered for it is disposed: `watchContentEmbeds()` has already passed it.@@ -206,9 +238,14 @@ function getWrapper(el: HTMLElement) {* opens from the embed, so that the text editor that contains it stays focused.*/export async function openContentEmbedMenu(embed: HTMLElement, anchor: HTMLElement) {- const { noteId, attachmentId, block } = embed.dataset;+ const { noteId, attachmentId, block, language } = embed.dataset;const origin = linkContextMenu.getOriginBelow(anchor, embed);+ if (language) {+ await linkContextMenu.openEmbedContextMenu(origin);+ return;+ }+if (attachmentId) {const attachment = await froca.getAttachment(attachmentId, true);if (attachment) {diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex 665f513b8e..cd5f4ff3d7 100644--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@ -135,7 +135,7 @@"_help_VRoP0g1uHHc2": "<figure class=\"image image-style-align-center image_resized\" style=\"width:76.29%;\"><img style=\"aspect-ratio:1479/865;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/In-editor%20AI%20assistant_image.png\" width=\"1479\" height=\"865\"></figure><p>The AI assistant works on the text you are already writing: select a passage and have it rewritten, translated or turned into a table, or ask for new content at the cursor. Unlike the <a href=\"#root/_help_LrKznOtw9cQD\">AI chat</a>, it does not open a conversation window, the result is previewed in place and only enters the note when you accept it.</p><h2>Requirements</h2><p>The assistant is only available once at least one provider is configured in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>AI / LLM</em>, with at least one model selected for it. Until then the toolbar entry is not shown at all.</p><h2>Accessing the AI assistant</h2><p>To access the AI assistant:</p><ul><li>Look for the <span class=\"tn-icon cke cke-trilium-ai\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. Press the button itself to enter the <em>Ask AI</em> mode or press the arrow key next to it to access the quick commands and the model selection.</li><li>Look for <em>AI assistant</em> or any of the <em>AI</em>-prefixed quick commands in <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</li><li>Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd>.</li><li>Select a text and choose the <em>AI assistant</em> option in the <a class=\"reference-link\" href=\"#root/_help_jcQVxzYybYgz\">Note contextual menu</a>.</li></ul><h2>What the assistant works on</h2><figure class=\"table\"><table><thead><tr><th>Situation</th><th>What is sent</th></tr></thead><tbody><tr><td>Text is selected</td><td>The selection.</td></tr><tr><td>Nothing is selected, and you pick a quick action</td><td>The paragraph the cursor is in.</td></tr><tr><td>Nothing is selected, and you type your own prompt</td><td>Nothing, the response is new content written at the cursor.</td></tr></tbody></table></figure><p>In all cases the assistant also sends the text before and after the target, so that the model can tell what it is writing into: asked to <em>Continue writing</em> or to summarize, a model that can only see the selected words is guessing at the document around them. This surrounding text is context only, it is never rewritten.</p><aside class=\"admonition important\"><p>That means a single run sends more than the passage you highlighted. See <a class=\"reference-link\" href=\"#root/_help_cRRrdZjgyhNc\">Privacy</a> for exactly what leaves your machine.</p></aside><h2>Quick actions</h2><p>The arrow beside the toolbar button opens a menu of ready-made instructions, grouped by what they do.</p><ul><li>The <em>Reformat</em> actions produce real Trilium content rather than plain text: <em>Diagram</em> inserts a Mermaid diagram, <em>Callout</em> an admonition, and <em>Collapsible</em> a collapsible block.</li><li>The <em>Translate</em> group lists the <a href=\"#root/_help_veGu4faJErEM\">content languages</a> you have enabled, or a predefined list if no content languages are set. It can be filled from within the editor, the last entry of the submenu opens the language configuration directly.</li></ul><p>Actions that need something to work on are greyed out when there is nothing to work on (for example an empty paragraph with no selection).</p><h2>Asking for something specific</h2><p>Choosing <em>Ask AI…</em> (<span class=\"tn-icon bx bx-message-square-dots\"></span>) opens a prompt where you can describe the change in your own words, for example: \"make this less formal\", \"add a row for 2024\", \"write an intro paragraph for this section\". Press <kbd>Enter</kbd> or the <span class=\"tn-icon cke cke-arrow-up\"></span> send button to run it.</p><p>Once a response arrives you can keep going in the same prompt, and the assistant treats it as a conversation rather than as a fresh request: after <em>Translate this to German</em>, asking for <em>make it shorter</em> shortens the German, not the original.</p><h2>Reviewing the result</h2><p>The response streams in as it is generated, and can be interrupted at any point by pressing the <em>Stop</em> (<span class=\"tn-icon cke cke-stop\"></span>) button; whatever arrived before that stays usable.</p><p>Nothing is written into the note until you say so. The review offers:</p><ul><li><em>Result</em>, which displays the response as it will be inserted.</li><li><em>Changes</em>, which displays an inline diff against the original, with insertions and deletions marked. When the model rewrote the passage rather than editing it, the review opens on <em>Result</em> instead: a diff of two texts with little in common is harder to read than the answer itself.</li><li><em>Try again</em> (<span class=\"tn-icon cke cke-refresh\"></span>), to re-run the same instruction.</li><li><em>Replace</em>, which substitutes the original passage</li><li><em>Insert below</em>, which keeps the original and adds the response after it.</li></ul><p>Trilium also reports the model that produced it, the tokens consumed and, for providers that report it, the price.</p><p>If you ask for a correction and there is nothing to correct, the assistant will indicate it instead of showing a blank diff.</p><h2>Choosing the model</h2><p>The bottom of the quick actions menu shows which model the assistant runs on, and lets you pick another from the models you selected in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>AI / LLM</em>, grouped by provider.</p><p>The model can also be changed while asking for something specific, or after the assistant has generated its response (i.e. if the response needs a better model).</p><p>This choice is separate from the model used by the chat, and is remembered across notes and devices. Left unset, the assistant follows the first configured provider.</p>","_help_mVEYwt20exhO": "<p><em>Quick actions</em> are a feature of the <a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a> for <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> notes which automatically triggers an LLM suggestion based on a defined prompt. The built-in quick actions come with a predefined prompt, but it is also possible to define your own quick actions.</p><h2>Creating a custom quick action</h2><p>In the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right-click the note where you want to place the quick action.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>AI Quick Action</em>. The entry appears only when AI is enabled.</li></ol><p>Afterwards, simply type in the content of the note the desired prompt. The text can be formatted in the same manner as a normal text note and it will be passed to the LLM as Markdown.</p><p>The title of the note will become the title of the quick action.</p><p>Of note:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> notes work too.</li><li>An empty note is ignored.</li><li><a class=\"reference-link\" href=\"#root/_help_MKmLg5x6xkor\">Archived Notes</a> are also excluded.</li></ul><h2>Using a quick action</h2><p>Once a quick action is defined, the action will appear under the <em>Quick Actions</em> dropdown in a group called <em>Custom</em>.</p>","_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts & \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the <span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.</p><p>In a note being edited, the menu also has the commands of the include's toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>, each checked while it is in effect, and <em>Convert to link</em> at the end. A drawing canvas, an included text or code note and an embedded code file also have <em>Editable</em>, above <em>Size</em>. For an embedded attachment they follow its first group of actions; for an included note they end the menu.</p><p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen, press the <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button at the end of its title. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in <a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a> (e.g. <a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a> will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a> provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></ul><p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.</p><h2>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. A code note or file is shown with syntax highlighting until then.</p><ul><li>To edit, select the include and turn on the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or check <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. Turn <em>Editable</em> off to return to the preview.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</li></ul><h2>Drawing canvases</h2><p>A drawing canvas is an Excalidraw canvas, like the one of a <a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",- "_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>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>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.</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><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_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>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>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 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>A new diagram starts editable: the Mermaid source is on the left, and the diagram next to it updates a moment after you stop typing. If the source has an error, the last diagram that worked stays, dimmed, under the error.</li><li>To show only the diagram, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <em>More actions</em> menu. Turn <em>Editable</em> back on to change the source.</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. 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>Undo in the text note also undoes the changes made to the source of a diagram.</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>Starting with v0.106.0, diagrams created in earlier versions open with <em>Editable</em> turned off.</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</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↑</td><td>⌥+↑</td><td></td></tr><tr><td>Move blocks (lists, paragraphs, etc.) down</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↓</td><td>⌥+↓</td><td></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.</li></ul></li></ul><div class=\"trilium-multicolumn-layout\" data-trilium-column-ratios=\"1-1-1\"><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:251/42;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Link%20Previews_image.png\" width=\"251\" height=\"42\"><figcaption><em>Inline</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:1217/196;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Link%20Previews_image.png\" width=\"1217\" height=\"196\"><figcaption><em>Card</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:994/563;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Link%20Previews_image.png\" width=\"994\" height=\"563\"><figcaption><em>Embed</em> link preview</figcaption></figure></div></div><h2>Inserting a link preview</h2><p>There are three ways to create one:</p><h3>1. By pasting a URL</h3><p>A link preview is automatically created:</p><ul><li>By pasting the URL and pressing <kbd>Space</kbd>. This will create an <em>inline</em> link preview.</li><li>When at the start of a new paragraph, pressing <kbd>Enter</kbd> will create a <em>card</em> or an <em>embed</em> for YouTube URLs.</li></ul><p>To undo an automatic link preview, press <kbd>Ctrl</kbd>+<kbd>Z</kbd> immediately afterwards which keeps it as a plain link instead. Alternatively, once a link preview was created, click on the link and select <em>Plain link</em> from the link preview toolbar.</p><p>This automatic conversion can be disabled by going to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> and unchecking <em>Autogenerate link previews</em> from the <em>Features</em> section.</p><p>If the link is not accessible to the Trilium server (or the network request fails for any other reason), it will not be converted to a link preview.</p><aside class=\"admonition note\"><p>A URL is only auto-converted when the pasted text <em>is</em> the URL. Links with a display name (e.g. <a href=\"https://triliumnotes.org\">Trilium Notes website</a>) are left as plain links.</p></aside><h3>2. By using the \"Link preview\" toolbar button</h3><p>Click <em>Link preview</em> (<span class=\"tn-icon cke cke-trilium-link-preview\"></span>) in the formatting toolbar to open the <em>Link preview</em> popup. Paste the URL and choose the type of preview.</p><h3>3. By saving browser tabs from the Web Clipper</h3><p>When the <a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a> saves the tabs of a window, each tab becomes an <em>inline</em> link preview showing the title and favicon the browser displays for it. Because this data comes from the browser, pages behind a login keep their real title, and the Trilium server does not contact the saved pages.</p><p>When <em>Autogenerate link previews</em> is turned off, the tabs are saved as a list of plain links instead.</p><h2>Altering an existing link preview</h2><p>Click on an inserted link preview to select it, and a small toolbar will appear with the following options:</p><ul><li>The normal link operations (opening in a new tab, copying the link, unlinking).</li><li>A button to edit the title of the link preview. This is especially useful if the title is hidden behind a login screen.</li><li>A way to switch between the link preview modes (Inline, Card or Embed) as well as to convert it to a normal link instead.<ul><li>The Embed option is only enabled when the URL points to a supported service (YouTube today).</li></ul></li></ul><h2>Where the preview data comes from</h2><p>When you insert a link preview, Trilium fetches metadata once and stores it inside the note's HTML:</p><ul><li><strong>YouTube URLs</strong> — title, channel name, and thumbnail are fetched via YouTube's public oEmbed endpoint.</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 is downloaded and inlined.</li></ul><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>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>",diff --git a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.mdindex a60de4c255..97ecf94012 100644--- a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md+++ b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md@@ -43,12 +43,23 @@ Choose <span class="tn-icon bx bx-pen"></span> _Drawing canvas_ to draw on an Ex## Mermaid diagram-Press the <span class="tn-icon cke cke-trilium-mermaid-insert"></span> button to create an inline Mermaid diagram.+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 _Mermaid diagram_ in the <a class="reference-link" href="Slash%20Commands.md">Slash Commands</a>.This feature is quite similar to the <a class="reference-link" href="../Mermaid%20Diagrams.md">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="Include%20Note.md">Include Note</a> feature for a dedicated Mermaid note.<figure class="image"><img style="aspect-ratio:1174/358;" src="2_Insert buttons_image.png" width="1174" height="358"></figure>+A diagram shows in a box like the one of an included note, so it can be resized, given another box size from its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu or shown in fullscreen, as described in <a class="reference-link" href="Include%20Note.md">Include Note</a>.++* A new diagram starts editable: the Mermaid source is on the left, and the diagram next to it updates a moment after you stop typing. If the source has an error, the last diagram that worked stays, dimmed, under the error.+* To show only the diagram, select it and turn off the <span class="tn-icon bx bx-edit-alt"></span> _Editable_ button at the start of its toolbar, or uncheck _Editable_ in its _More actions_ menu. Turn _Editable_ back on to change the source.+* 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. 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.+* Undo in the text note also undoes the changes made to the source of a diagram.++The source of the diagram stays in the note as a Mermaid code block, so the diagram is exported to Markdown as a `mermaid` code block that other applications can show.++Starting with v0.106.0, diagrams created in earlier versions open with _Editable_ turned off.+## Horizontal rulerThis 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="Formatting%20toolbar.md">Formatting toolbar</a>.diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex c0c26524bb..d2cbac07e1 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -1,5 +1,7 @@import "ckeditor5";+import type { InlineEmbedSource } from "./plugins/content_embed/inline_source.js";+declare global {interface Component {componentId: string;@@ -111,6 +113,16 @@ declare global {$el: JQuery<HTMLElement>,boxSize?: string): void;+ /**+ * Fills an embed box with what `source` shows, for an embed that keeps its content in the+ * note. Hosts without such embeds leave it out.+ */+ loadInlineEmbed?(+ source: InlineEmbedSource,+ $el: JQuery<HTMLElement>,+ boxSize: string | undefined,+ options: { isFocused: boolean }+ ): void;/** The href of a reference link to the attachment, or `null` once it is deleted. */getAttachmentHref(attachmentId: string): Promise<string | null>;/** The note the editor holds. Hosts without a note of their own leave it out. */diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 66aabfefeb..b0bae8e3cc 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -19,6 +19,7 @@ export type { ImageEditingSourceConfig } from "./plugins/image_editing_source.jsexport type { FileUploadData, FileUploadEvent } from "./plugins/file_upload/fileuploadediting.js";export type { PasteTarget } from "./plugins/cuttonote.js";export type { ContentEmbedState } from "./plugins/content_embed/content_embed.js";+export type { InlineEmbedSource } from "./plugins/content_embed/inline_source.js";export type { AttachmentLinkChange } from "./plugins/referencelink.js";export type { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.js";export type { default as TriliumSlashCommands, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem } from "./plugins/mention/slash_commands.js";diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.tsindex f18b8f1db5..51a29ce2f3 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.spec.ts@@ -2,12 +2,10 @@ import { BlockQuote, _getModelData as getModelData, _setModelData as setModelDatimport { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";-// Both glue plugins are imported for their type augmentations alone (`config.math`,-// `config.mermaid`). Only Mermaid's editing half is loaded as a plugin, being where its renderer-// lives; the maths pass calls `renderEquation` directly, so the feature itself is not needed.+// Imported for their type augmentations alone (`config.math`, `config.contentEmbed`): the maths+// pass calls `renderEquation` directly, and diagrams render through `contentEmbed.renderInlinePreview`.+import type {} from "../content_embed/inline_source.js";import type {} from "../math/math.js";-import type {} from "../mermaid/mermaid.js";-import MermaidEditing from "../mermaid/mermaid_editing.js";import TriliumAiAssistant from "./ai_assistant.js";import { AI_TARGET_MARKER } from "./ai_assistant_editing.js";import type { AiCompletionRequest, AiCompletionUsage, AiDiffFunction, AiQuickActionGroup, AiStreamCallback, AiStreamFunction } from "./ai_assistant_config.js";@@ -969,18 +967,25 @@ describe("AiAssistantUI toolbar entry", () => {actions: [{ id: "diagram", label: "Diagram", prompt: "Draw it.", reviewView: "result" }]}];- /** Stands in for the mermaid library the host lazy-loads, one SVG per source. */+ /** Stands in for the host's renderer of inline languages, one SVG per source. */function createMermaidStub() {return {- initialize: vi.fn(),- render: vi.fn(async (_id: string, source: string) => ({ svg: `<svg data-source="${source}"></svg>` }))+ render: vi.fn((_language: string, source: string, container: HTMLElement) => {+ container.innerHTML = `<svg data-source="${source}"></svg>`;+ })};}+ function getDiagramConfig(mermaid: ReturnType<typeof createMermaidStub>) {+ return { inlineLanguages: [ "mermaid" ], renderInlinePreview: mermaid.render };+ }+async function createDiagramEditor(mermaid: ReturnType<typeof createMermaidStub>, stream: AiStreamFunction) {- return createTestEditor([Essentials, Paragraph, CodeBlockEditing, MermaidEditing, TriliumAiAssistant], {+ return createTestEditor([Essentials, Paragraph, CodeBlockEditing, TriliumAiAssistant], {aiAssistant: { sanitizeHtml, quickActions: DIAGRAM_ACTION, stream },- mermaid: { lazyLoad: () => mermaid, config: {} }+ contentEmbed: getDiagramConfig(mermaid),+ // Keeps the committed block a `language-mermaid` one without the embed plugins.+ codeBlock: { languages: [ { language: "mermaid", label: "Mermaid" } ] }});}@@ -993,7 +998,7 @@ describe("AiAssistantUI toolbar entry", () => {quickActionButtons(createComponent(editor))[0].fire("execute");await vi.waitFor(() => expect(previewHtml(editor)).toContain("<svg"));- expect(mermaid.render).toHaveBeenCalledWith(expect.any(String), DIAGRAM);+ expect(mermaid.render).toHaveBeenCalledWith("mermaid", DIAGRAM, expect.any(HTMLElement));// The `<pre>` goes with the `<code>`: what is left is the diagram, not a framed one.expect(previewHtml(editor)).toContain(`<div class="ck-ai-assistant-form__diagram"><svg data-source="graph TD; A-->B;">`);@@ -1021,12 +1026,11 @@ describe("AiAssistantUI toolbar entry", () => {expect(mermaid.render).not.toHaveBeenCalled();});- // The library is the host's to supply (`config.mermaid.lazyLoad`), so the feature can be- // loaded with nothing behind it. Emptying the block for a diagram that will never arrive- // would lose the response; the source is at least what a commit would produce.- it("leaves the source standing when the host supplies no diagram library", async () => {+ // The renderer is the host's to supply (`contentEmbed.renderInlinePreview`). Emptying the+ // block for a diagram that will never arrive would lose the response.+ it("leaves the source standing when the host supplies no renderer", async () => {const stub = createStreamStub(DIAGRAM_HTML);- const editor = await createTestEditor([Essentials, Paragraph, CodeBlockEditing, MermaidEditing, TriliumAiAssistant], {+ const editor = await createTestEditor([Essentials, Paragraph, CodeBlockEditing, TriliumAiAssistant], {aiAssistant: { sanitizeHtml, quickActions: DIAGRAM_ACTION, stream: stub.stream }});@@ -1040,7 +1044,7 @@ describe("AiAssistantUI toolbar entry", () => {it("leaves the code block alone in the diff, whose text is two responses at once", async () => {const mermaid = createMermaidStub();const stub = createStreamStub(DIAGRAM_HTML);- const editor = await createTestEditor([Essentials, Paragraph, CodeBlockEditing, MermaidEditing, TriliumAiAssistant], {+ const editor = await createTestEditor([Essentials, Paragraph, CodeBlockEditing, TriliumAiAssistant], {aiAssistant: {sanitizeHtml,quickActions: DIAGRAM_ACTION,@@ -1048,7 +1052,7 @@ describe("AiAssistantUI toolbar entry", () => {// Opens on the diff, since the action asking for the result is not the one run.diff: () => `<pre><code class="language-mermaid">graph <del>LR</del><ins>TD</ins></code></pre>`},- mermaid: { lazyLoad: () => mermaid, config: {} }+ contentEmbed: getDiagramConfig(mermaid)});setModelData(editor.model, "<paragraph>[foo]</paragraph>");diff --git a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.tsindex 61687f5b8b..a03ca94928 100644--- a/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts+++ b/packages/ckeditor5/src/plugins/ai_assistant/ai_assistant_ui.ts@@ -850,31 +850,30 @@ export default class AiAssistantUI extends Plugin {}/**- * Turns the `language-mermaid` code blocks of a finished response into rendered diagrams, so- * the review shows what committing it will show. The response is Markdown rendered to note- * HTML, in which a diagram is a code block — the editor only makes one a diagram when the- * content is upcast into the model, which the assistant deliberately postpones until commit.- *- * Soft-coupled to the Mermaid feature by name: a build without it — or one whose host supplies- * no diagram library — leaves the source standing, which is also all a commit could produce- * there, rather than emptying the block in favour of a diagram that will never arrive.+ * Turns the code blocks of a finished response in an inline embed language, such as+ * `language-mermaid`, into what they render, so the review shows what committing it will+ * show. The response is Markdown rendered to note HTML; the editor only makes such a block an+ * embed when the content is upcast into the model, which the assistant postpones until commit.+ * Without `contentEmbed.renderInlinePreview`, the blocks stay as source.*/private _renderPreviewDiagrams(preview: HTMLElement): void {- const editor = this.editor;- if (!editor.plugins.has("MermaidEditing") || !editor.config.get("mermaid")?.lazyLoad) {+ const config = this.editor.config.get("contentEmbed");+ const render = config?.renderInlinePreview;+ if (!render) {return;}- const mermaid = editor.plugins.get("MermaidEditing");- // The `<pre>` is replaced along with the `<code>` it holds: a diagram left inside one is- // framed as a code block in the preview and nowhere else.- for (const pre of preview.querySelectorAll("pre:has(> code.language-mermaid)")) {- /* v8 ignore next -- defensive fallback: textContent on an element is always a string */- const source = pre.textContent ?? "";- const diagram = preview.ownerDocument.createElement("div");- diagram.className = "ck-ai-assistant-form__diagram";- pre.replaceWith(diagram);- void mermaid.renderMermaid(diagram, source);+ for (const language of config.inlineLanguages ?? []) {+ // The `<pre>` is replaced along with its `<code>`: a diagram left inside one is framed+ // as a code block.+ for (const pre of preview.querySelectorAll(`pre:has(> code.language-${language})`)) {+ /* v8 ignore next -- defensive fallback: textContent on an element is always a string */+ const source = pre.textContent ?? "";+ const diagram = preview.ownerDocument.createElement("div");+ diagram.className = "ck-ai-assistant-form__diagram";+ pre.replaceWith(diagram);+ render(language, source, diagram);+ }}}diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex 4589a5ebe8..97824b341c 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -27,6 +27,7 @@ import noteIcon from '../../icons/note.svg?raw';import { encodeBlockParameter, parseBlockRange } from '@triliumnext/commons';import { getAttachmentId, getNoteId } from '../referencelink.js';import ResizableWidgets, { SIZE_ATTRIBUTES } from '../resizable_widgets/resizable_widgets.js';+import ContentEmbedInlineSource, { isInlineSourceEmbed } from './inline_source.js';import './nested_editor_events.js';export const COMMAND_NAME = 'insertContentEmbed';@@ -104,7 +105,7 @@ export default class ContentEmbed extends Plugin {declare public selectedEmbedTools: ContentEmbedToolProvider | null;static get requires() {- return [ ContentEmbedEditing, ContentEmbedUI ];+ return [ ContentEmbedEditing, ContentEmbedUI, ContentEmbedInlineSource ];}static get pluginName() {@@ -943,7 +944,7 @@ function isContentEmbed( node: ModelNode | ModelDocumentFragment | null ): node/** Whether the title of `embed` can be hidden: a Tiny or an Expandable one always shows it. */function isEmbedTitleToggleable( embed: ModelElement ) {const boxSize = embed.getAttribute( 'boxSize' );- return boxSize !== 'tiny' && boxSize !== 'expandable';+ return boxSize !== 'tiny' && boxSize !== 'expandable' && !isInlineSourceEmbed( embed );}/** Whether the content of `embed` has an editable mode, which its content type opts in to. */@@ -953,7 +954,7 @@ function isEmbedEditableToggleable( editor: Editor, embed: ModelElement ) {/** Whether `embed` can have a caption. A Tiny embed has none. */function isEmbedCaptionToggleable( editor: Editor, embed: ModelElement ) {- return embed.getAttribute( 'boxSize' ) !== 'tiny'+ return embed.getAttribute( 'boxSize' ) !== 'tiny' && !isInlineSourceEmbed( embed )&& editor.model.schema.checkChild( embed, 'caption' );}@@ -1001,6 +1002,10 @@ function addContentEmbeds(* it. An embed whose upload has not ended names nothing.*/function getEmbeddedEntityAttributes( element: ModelElement ): Record<string, string> {+ const language = element.getAttribute( 'language' ) as string | undefined;+ if ( language ) {+ return { 'data-language': language };+ }const attachmentId = element.getAttribute( 'attachmentId' ) as string | undefined;const noteId = element.getAttribute( 'noteId' ) as string | undefined;const block = element.getAttribute( 'block' ) as string | undefined;@@ -1171,6 +1176,11 @@ function loadEmbeddedContent(wrapper: HTMLElement,boxSize: string | undefined) {+ if ( isInlineSourceEmbed( element ) ) {+ editor.plugins.get( ContentEmbedInlineSource ).load( element, wrapper, boxSize );+ return;+ }+const $wrapper = $( wrapper );const editorEl = editor.editing.view.getDomRoot();const component = glob.getComponentByEl<EditorComponent>( editorEl );diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.tsnew file mode 100644index 0000000000..567ec0fcb7--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts@@ -0,0 +1,155 @@+import {+ _getModelData as getModelData,+ _setModelData as setModelData,+ ClassicEditor,+ Essentials,+ type ModelElement,+ Paragraph,+ Undo,+ Widget+} from "ckeditor5";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../../../test/editor-kit.js";+import { installGlobMock } from "../../../test/globals-test-kit.js";+import { SIZE_ATTRIBUTES } from "../resizable_widgets/resizable_widgets.js";+import ContentEmbed, {+ CONVERT_EMBED_TO_LINK_COMMAND,+ TOGGLE_CAPTION_COMMAND_NAME,+ TOGGLE_TITLE_COMMAND_NAME+} from "./content_embed.js";+import { INSERT_INLINE_EMBED_COMMAND, type InlineEmbedSource } from "./inline_source.js";++describe("ContentEmbedInlineSource", () => {+ let editor: ClassicEditor;+ let loadInlineEmbed: ReturnType<typeof vi.fn>;++ beforeEach(async () => {+ loadInlineEmbed = vi.fn();+ installGlobMock({+ getComponentByEl: () => ({ triggerCommand: vi.fn(), loadInlineEmbed })+ });++ editor = await createTestEditor([ Essentials, Paragraph, Undo, Widget, ContentEmbed ], {+ contentEmbed: { inlineLanguages: [ "mermaid" ] }+ });+ });++ function getEmbed() {+ const embed = editor.model.document.getRoot()?.getChild(0);+ expect(embed?.is("element", "contentEmbed")).toBe(true);+ return embed as ModelElement;+ }++ function getLoadedSource(call = 0) {+ return loadInlineEmbed.mock.calls[call][0] as InlineEmbedSource;+ }++ it("loads a code block of an inline language as an embed of its source, and saves it back", () => {+ editor.setData(+ `<pre spellcheck="false"><code class="language-mermaid" data-trilium-display-mode="split">`+ + `graph TD;\n A-->B</code></pre>`+ );++ const embed = getEmbed();+ expect(embed.getAttribute("language")).toBe("mermaid");+ expect(embed.getAttribute("source")).toBe("graph TD;\n A-->B");+ expect(embed.getAttribute("boxSize")).toBe("medium");+ expect(embed.getAttribute("hideTitle")).toBe(true);+ expect(embed.getAttribute("editable")).toBeUndefined();+ expect(editor.getData()).toBe(+ `<pre data-box-size="medium" data-hide-title="true"><code class="language-mermaid">`+ + `graph TD;\n A-->B</code></pre>`+ );+ });++ it("keeps the box size, the flags and the size of the embed on the <pre>", () => {+ const html = `<pre style="--include-note-height:12em;" data-box-size="small"`+ + ` data-editable="true" data-hide-title="true"><code class="language-mermaid">x</code></pre>`;+ editor.setData(html);++ const embed = getEmbed();+ expect(embed.getAttribute("boxSize")).toBe("small");+ expect(embed.getAttribute("editable")).toBe(true);+ expect(embed.getAttribute(SIZE_ATTRIBUTES.height)).toBe("12em");+ expect(editor.getData()).toContain(`data-box-size="small"`);+ expect(editor.getData()).toContain(`data-editable="true"`);+ expect(editor.getData()).toContain("--include-note-height:12em");+ });++ it("leaves a code block of another language alone", () => {+ editor.setData(+ `<pre><code class="language-javascript">let a;</code></pre>`+ + `<pre><code class="language-mermaid">graph TD;</code></pre>`+ );++ const model = getModelData(editor.model, { withoutSelection: true });+ expect(model.match(/<contentEmbed /g)).toHaveLength(1);+ expect(model).toContain(`language="mermaid"`);+ expect(model).not.toContain("javascript");+ });++ it("has the host render the source, and writes its changes as steps of the undo", () => {+ editor.setData(`<pre><code class="language-mermaid">graph TD;</code></pre>`);++ expect(loadInlineEmbed).toHaveBeenCalledOnce();+ const [ source, $el, boxSize, options ] = loadInlineEmbed.mock.calls[0];+ expect(source.language).toBe("mermaid");+ expect(source.getSource()).toBe("graph TD;");+ expect(source.isReadOnly()).toBe(false);+ // `test/setup.ts` stubs jQuery as the identity, so the wrapper arrives as is.+ expect(($el as HTMLElement).classList.contains("include-note-wrapper")).toBe(true);+ expect(boxSize).toBe("medium");+ expect(options).toEqual({ isFocused: false });++ const listener = vi.fn();+ source.subscribe(listener);+ source.setSource("graph LR;");+ expect(getEmbed().getAttribute("source")).toBe("graph LR;");+ expect(listener).toHaveBeenCalledOnce();++ editor.execute("undo");+ expect(getEmbed().getAttribute("source")).toBe("graph TD;");+ expect(source.getSource()).toBe("graph TD;");+ expect(listener).toHaveBeenCalledTimes(2);+ // Writing the source does not draw the embed again, which would remount its editor.+ expect(loadInlineEmbed).toHaveBeenCalledOnce();+ });++ it("ignores a write of the same source, and stops calling a listener that unsubscribed", () => {+ editor.setData(`<pre><code class="language-mermaid">a</code></pre>`);+ const source = getLoadedSource();+ const listener = vi.fn();+ const unsubscribe = source.subscribe(listener);++ source.setSource("a");+ expect(listener).not.toHaveBeenCalled();++ unsubscribe();+ source.setSource("b");+ expect(listener).not.toHaveBeenCalled();+ });++ it("inserts a new embed editable and untitled, and has its content take the focus", () => {+ setModelData(editor.model, "<paragraph>[]</paragraph>");++ editor.execute(INSERT_INLINE_EMBED_COMMAND, { language: "mermaid", source: "graph TD;" });++ const embed = editor.model.document.selection.getSelectedElement();+ expect(embed?.getAttribute("language")).toBe("mermaid");+ expect(embed?.getAttribute("source")).toBe("graph TD;");+ expect(embed?.getAttribute("boxSize")).toBe("medium");+ expect(embed?.getAttribute("hideTitle")).toBe(true);+ expect(embed?.getAttribute("editable")).toBe(true);+ expect(loadInlineEmbed.mock.calls[0][3]).toEqual({ isFocused: true });+ });++ it("offers no title, caption or link for an embed that shows no note", () => {+ editor.setData(`<pre><code class="language-mermaid">a</code></pre>`);+ editor.model.change((writer) => writer.setSelection(getEmbed(), "on"));++ expect(editor.commands.get(TOGGLE_TITLE_COMMAND_NAME)?.isEnabled).toBe(false);+ expect(editor.commands.get(TOGGLE_CAPTION_COMMAND_NAME)?.isEnabled).toBe(false);+ expect(editor.commands.get(CONVERT_EMBED_TO_LINK_COMMAND)?.isEnabled).toBe(false);+ });+});diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.tsnew file mode 100644index 0000000000..ebfb36b9ba--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.ts@@ -0,0 +1,268 @@+import {+ Command,+ type DowncastConversionApi,+ type DowncastInsertEvent,+ type Editor,+ findOptimalInsertionRange,+ type Model,+ type ModelElement,+ Plugin,+ type UpcastConversionApi,+ type UpcastElementEvent,+ type ViewElement+} from 'ckeditor5';++import { SIZE_ATTRIBUTES } from '../resizable_widgets/resizable_widgets.js';++export const INSERT_INLINE_EMBED_COMMAND = 'insertInlineEmbed';++/**+ * The source of an embed that keeps its content in the note, as the host reads and changes it.+ * The editor's undo and other changes to the source reach the host through `subscribe()`.+ */+export interface InlineEmbedSource {+ /** The language that the source is written in, such as `mermaid`. */+ readonly language: string;+ getSource(): string;+ /** Replaces the source, as one step of the editor's undo. */+ setSource( source: string ): void;+ /** Calls `callback` when the source changes, until the returned function is called. */+ subscribe( callback: () => void ): () => void;+ isReadOnly(): boolean;+}++export interface InsertInlineEmbedOptions {+ language: string;+ source: string;+}++/** The flags of an embed and the `data-*` attributes they are saved as on the `<pre>`. */+const FLAG_ATTRIBUTES = [+ [ 'hideTitle', 'data-hide-title' ],+ [ 'editable', 'data-editable' ]+] as const;++/** The size attributes of an embed and the style properties they are saved as on the `<pre>`. */+const SIZE_PROPERTIES = [+ [ SIZE_ATTRIBUTES.width, '--include-note-width' ],+ [ SIZE_ATTRIBUTES.height, '--include-note-height' ]+] as const;++/**+ * Embeds whose content lives in the note, as `<pre><code class="language-…">` code blocks of the+ * languages in `contentEmbed.inlineLanguages`. The embed keeps the language and the source as+ * attributes, and is saved as the code block, with its box size, flags and size on the `<pre>`,+ * so that anything reading the note sees a plain code block.+ *+ * The content renders through the host's `loadInlineEmbed()`, which receives an+ * {@link InlineEmbedSource} rather than an ID.+ */+export default class ContentEmbedInlineSource extends Plugin {+ /** The listeners of each embed's source, by embed. */+ private readonly listeners = new WeakMap<ModelElement, Set<() => void>>();+ /** The embeds inserted by {@link INSERT_INLINE_EMBED_COMMAND}, whose content takes the focus. */+ private readonly focusedEmbeds = new WeakSet<ModelElement>();++ static get pluginName() {+ return 'ContentEmbedInlineSource' as const;+ }++ init() {+ const editor = this.editor;++ editor.commands.add( INSERT_INLINE_EMBED_COMMAND, new InsertInlineEmbedCommand( editor ) );++ editor.data.upcastDispatcher.on<UpcastElementEvent>(+ 'element:code', ( _evt, data, api ) => this.upcast( data, api ), { priority: 'high' } );+ editor.data.downcastDispatcher.on<DowncastInsertEvent<ModelElement>>(+ 'insert:contentEmbed', ( _evt, data, api ) => downcastData( editor.model, data.item, api ),+ { priority: 'high' } );+ editor.editing.downcastDispatcher.on( 'attribute:source:contentEmbed', ( _evt, data ) => {+ for ( const listener of this.listeners.get( data.item as ModelElement ) ?? [] ) {+ listener();+ }+ } );+ }++ afterInit() {+ this.editor.model.schema.extend( 'contentEmbed', { allowAttributes: [ 'language', 'source' ] } );+ }++ /** Has the host render the source of `embed` into `wrapper`. */+ load( embed: ModelElement, wrapper: HTMLElement, boxSize: string | undefined ) {+ const editor = this.editor;+ const component = glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() );+ const isFocused = this.focusedEmbeds.delete( embed );+ component.loadInlineEmbed?.( this.getSource( embed ), $( wrapper ), boxSize, { isFocused } );+ }++ /** Marks `embed` for its content to take the focus once it renders. */+ focusOnLoad( embed: ModelElement ) {+ this.focusedEmbeds.add( embed );+ }++ private getSource( embed: ModelElement ): InlineEmbedSource {+ const editor = this.editor;+ const listeners = this.listeners;++ return {+ language: embed.getAttribute( 'language' ) as string,+ getSource: () => embed.getAttribute( 'source' ) as string | undefined ?? '',+ setSource: source => {+ const root = embed.root;+ if ( editor.state === 'destroyed' || !root.is( 'rootElement' )+ || root.rootName === '$graveyard' || embed.getAttribute( 'source' ) === source ) {+ return;+ }+ editor.model.change( writer => writer.setAttribute( 'source', source, embed ) );+ },+ subscribe: callback => {+ let callbacks = listeners.get( embed );+ if ( !callbacks ) {+ callbacks = new Set();+ listeners.set( embed, callbacks );+ }+ callbacks.add( callback );+ return () => {+ callbacks.delete( callback );+ };+ },+ isReadOnly: () => editor.isReadOnly+ };+ }++ /** Turns a `<pre><code>` of an inline language into an embed of its source. */+ private upcast( data: UpcastElementEvent[ 'args' ][ 0 ], api: UpcastConversionApi ) {+ const code = data.viewItem;+ const pre = code.parent;+ const language = getInlineLanguage( this.editor, code );+ if ( !language || !pre?.is( 'element', 'pre' ) || !api.consumable.test( code, { name: true } ) ) {+ return;+ }++ const source = Array.from( code.getChildren() )+ .map( child => child.is( '$text' ) ? child.data : '' )+ .join( '' );+ const embed = api.writer.createElement( 'contentEmbed', {+ language,+ source,+ boxSize: pre.getAttribute( 'data-box-size' ) ?? 'medium',+ hideTitle: true,+ ...getFlagsOfView( pre ),+ ...getSizesOfView( pre )+ } );+ if ( !api.safeInsert( embed, data.modelCursor ) ) {+ return;+ }++ api.consumable.consume( code, { name: true } );+ api.consumable.consume( pre, { name: true } );+ api.updateConversionResult( embed, data );+ }+}++/** Inserts an embed of a new source beside the block of the selection, editable, and focuses it. */+class InsertInlineEmbedCommand extends Command {+ override refresh() {+ const model = this.editor.model;+ const position = model.document.selection.getFirstPosition();+ this.isEnabled = !!position && model.schema.findAllowedParent( position, 'contentEmbed' ) !== null;+ }++ override execute( { language, source }: InsertInlineEmbedOptions ) {+ const editor = this.editor;+ const model = editor.model;++ model.change( writer => {+ const embed = writer.createElement( 'contentEmbed', {+ language,+ source,+ boxSize: 'medium',+ hideTitle: true,+ editable: true+ } );+ editor.plugins.get( ContentEmbedInlineSource ).focusOnLoad( embed );+ const selection = model.document.selection;+ model.insertObject( embed, findOptimalInsertionRange( selection, model ) );+ writer.setSelection( embed, 'on' );+ } );+ }+}++/** Whether `embed` keeps its content in the note rather than showing a note or attachment. */+export function isInlineSourceEmbed( embed: ModelElement ) {+ return !!embed.getAttribute( 'language' );+}++/** Saves an embed of a source as `<pre><code class="language-…">`. */+function downcastData( model: Model, embed: ModelElement, api: DowncastConversionApi ) {+ if ( !isInlineSourceEmbed( embed ) || !api.consumable.consume( embed, 'insert' ) ) {+ return;+ }++ const { writer, mapper } = api;+ const preAttributes: Record<string, string> = {+ 'data-box-size': embed.getAttribute( 'boxSize' ) as string+ };+ for ( const [ flag, dataAttribute ] of FLAG_ATTRIBUTES ) {+ if ( embed.getAttribute( flag ) ) {+ preAttributes[ dataAttribute ] = 'true';+ }+ }++ const pre = writer.createContainerElement( 'pre', preAttributes );+ const code = writer.createContainerElement( 'code', {+ class: `language-${ embed.getAttribute( 'language' ) as string }`+ } );+ writer.insert( writer.createPositionAt( code, 0 ),+ writer.createText( embed.getAttribute( 'source' ) as string | undefined ?? '' ) );+ writer.insert( writer.createPositionAt( pre, 0 ), code );+ writer.insert( mapper.toViewPosition( model.createPositionBefore( embed ) ), pre );+ // `ResizableWidgets` writes the size attributes on the `<pre>` through this mapping.+ mapper.bindElements( embed, pre );+}++/** The inline language of `code`, when it is one in `contentEmbed.inlineLanguages`. */+function getInlineLanguage( editor: Editor, code: ViewElement ) {+ const languages = editor.config.get( 'contentEmbed.inlineLanguages' ) ?? [];+ for ( const className of code.getClassNames() ) {+ const language = className.startsWith( 'language-' ) && className.slice( 'language-'.length );+ if ( language && languages.includes( language ) ) {+ return language;+ }+ }+ return null;+}++function getFlagsOfView( pre: ViewElement ) {+ return Object.fromEntries( FLAG_ATTRIBUTES+ .filter( ( [ , dataAttribute ] ) => pre.getAttribute( dataAttribute ) === 'true' )+ .map( ( [ flag ] ) => [ flag, true ] ) );+}++function getSizesOfView( pre: ViewElement ) {+ return Object.fromEntries( SIZE_PROPERTIES+ .map( ( [ attribute, property ] ) => [ attribute, pre.getStyle( property ) ] )+ .filter( ( [ , value ] ) => value ) );+}++declare module 'ckeditor5' {+ interface PluginsMap {+ [ ContentEmbedInlineSource.pluginName ]: ContentEmbedInlineSource;+ }++ interface EditorConfig {+ contentEmbed?: {+ /**+ * The languages whose `<pre><code class="language-…">` code blocks show as embeds of+ * their source, rendered by the host's `loadInlineEmbed()`.+ */+ inlineLanguages?: string[];+ /**+ * Renders the `source` of an inline language into `container`, outside an embed, as+ * the AI assistant previews a response.+ */+ renderInlinePreview?: ( language: string, source: string, container: HTMLElement ) => void;+ };+ }+}diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.tsindex 6d4b61857a..e3823fe514 100644--- a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts@@ -1,10 +1,7 @@import {CANVAS_ATTACHMENT_MIME,CANVAS_ATTACHMENT_TITLE,- EMPTY_CANVAS_CONTENT,- MERMAID_ATTACHMENT_MIME,- MERMAID_ATTACHMENT_TITLE,- NEW_MERMAID_CONTENT+ EMPTY_CANVAS_CONTENT} from "@triliumnext/commons";import {ButtonView,@@ -21,7 +18,6 @@ import {type Locale} from "ckeditor5";import bxLink from "boxicons/svg/regular/bx-link.svg?raw";-import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";import bxPen from "boxicons/svg/regular/bx-pen.svg?raw";import bxShapeSquare from "boxicons/svg/regular/bx-shape-square.svg?raw";@@ -32,7 +28,7 @@ import type { FileUploadOptions } from "./fileuploadcommand.js";* the list also offers to link them. In an editor without embeds, the button links them.** Also registers the `drawingCanvas` button, which attaches an empty canvas drawing and embeds it,- * editable, and the `mermaidDiagram` button, which does the same with a new Mermaid diagram.+ * editable.*/export default class FileUploadUI extends Plugin {static get pluginName() {@@ -98,19 +94,17 @@ export default class FileUploadUI extends Plugin {editor.ui.componentFactory.add("drawingCanvas", (locale) => {const button = new ButtonView(locale);button.set({ label: t("Drawing canvas"), icon: bxPen, tooltip: true });- bindToEmbedUpload(editor, button);- button.on("execute", () => insertDrawingCanvas(editor));- return button;- });+ const uploadCommand = editor.commands.get("fileUpload");+ const embedCommand = editor.commands.get("insertContentEmbed");+ if (uploadCommand && embedCommand) {+ button.bind("isEnabled").to(uploadCommand, "isEnabled", embedCommand, "isEnabled",+ (canUpload, canEmbed) => canUpload && canEmbed);+ } else {+ button.isEnabled = false;+ }- editor.ui.componentFactory.add("mermaidDiagram", (locale) => {- const button = new ButtonView(locale);- button.set({- label: t("Mermaid diagram (embedded)"), icon: bxNetworkChart, tooltip: true- });- bindToEmbedUpload(editor, button);- button.on("execute", () => insertMermaidDiagram(editor));+ button.on("execute", () => insertDrawingCanvas(editor));return button;});@@ -148,35 +142,9 @@ export default class FileUploadUI extends Plugin {* the `drawingCanvas` button does.*/export function insertDrawingCanvas(editor: Editor) {- insertEditableEmbed(editor, new File([ EMPTY_CANVAS_CONTENT ], CANVAS_ATTACHMENT_TITLE, {+ const file = new File([ EMPTY_CANVAS_CONTENT ], CANVAS_ATTACHMENT_TITLE, {type: CANVAS_ATTACHMENT_MIME- }));-}--/**- * Attaches a new Mermaid diagram and embeds it, editable and untitled, with the focus in it, as the- * `mermaidDiagram` button does.- */-export function insertMermaidDiagram(editor: Editor) {- insertEditableEmbed(editor, new File([ NEW_MERMAID_CONTENT ], MERMAID_ATTACHMENT_TITLE, {- type: MERMAID_ATTACHMENT_MIME- }));-}--/** Enables `button` while a file can be attached and embedded at the selection. */-function bindToEmbedUpload(editor: Editor, button: ButtonView) {- const uploadCommand = editor.commands.get("fileUpload");- const embedCommand = editor.commands.get("insertContentEmbed");- if (uploadCommand && embedCommand) {- button.bind("isEnabled").to(uploadCommand, "isEnabled", embedCommand, "isEnabled",- (canUpload, canEmbed) => canUpload && canEmbed);- } else {- button.isEnabled = false;- }-}--/** Attaches `file` and embeds it, editable and untitled, with the focus in it. */-function insertEditableEmbed(editor: Editor, file: File) {+ });editor.execute("fileUpload", {file: [ file ],asEmbed: true,diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.tsindex aad6ac442a..7d5f0a3042 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts@@ -25,7 +25,7 @@ import InsertDateTimePlugin, { COMMAND_NAME as INSERT_DATE_TIME_COMMAND, DATE_TIimport { COMMAND_NAME as INTERNAL_LINK_COMMAND } from "../internallink.js";import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";import MathUI from "../math/math_ui.js";-import { INSERT_MERMAID_COMMAND } from "../mermaid/insert_mermaid_command.js";+import { INSERT_INLINE_EMBED_COMMAND } from "../content_embed/inline_source.js";import { BUTTON_ICON_SIZE, createLayoutFigure } from "../multicolumn/multicolumn_ui.js";import TriliumSnippets from "../snippets/snippets.js";import type { SnippetDefinition } from "../snippets/snippetsconfig.js";@@ -596,7 +596,7 @@ describe("buildTriliumSlashCommands", () => {[ "bulletedList", "Bulleted list", "bulletedList" ],[ "numberedList", "Numbered list", "numberedList" ],[ "todoList", "To-do list", "todoList" ],- [ "mermaid", "Mermaid diagram", INSERT_MERMAID_COMMAND ]+ [ "mermaid", "Mermaid diagram", INSERT_INLINE_EMBED_COMMAND ]])("defines %s, running its command with an icon and a description", (id, title, commandName) => {const entry = definition(id);@@ -849,15 +849,17 @@ describe("buildTriliumSlashCommands", () => {// The samples come from `mermaid.samples`, which the editor already carries for the Mermaid UI —// it was passed to the builder separately back when the host built these definitions.it("builds one entry per Mermaid sample, inserting that sample's source", () => {- const { fake, executeSpy } = makeFakeEditor();+ const execute = vi.spyOn(editor, "execute").mockReturnValue(undefined);const sample = definition("mermaid-sample-0");expect(sample.title).toBe("Mermaid diagram: Flowchart");expect(sample.description).toBe("Insert a \"Flowchart\" Mermaid diagram template");expect(sample.aliases).toContain("Flowchart");- sample.execute?.(fake);- expect(executeSpy).toHaveBeenCalledWith(INSERT_MERMAID_COMMAND, { source: "graph TD;" });+ sample.execute?.(editor);+ expect(execute).toHaveBeenCalledWith(+ INSERT_INLINE_EMBED_COMMAND, { language: "mermaid", source: "graph TD;" }+ );});it("carries no sample entries when the editor configures none", async () => {diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.tsindex 3f1ab28642..c9cf2a2ab5 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts@@ -46,15 +46,15 @@ import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "../admonition/admoniimport { getAdmonitionTitle } from "../admonition/admonition_ui.js";import aiIcon from "../ai_assistant/theme/icons/ai.svg?raw";import { COMMAND_NAME as CONTENT_EMBED_COMMAND } from "../content_embed/content_embed.js";-import { insertDrawingCanvas, insertMermaidDiagram } from "../file_upload/file_upload_ui.js";+import { insertDrawingCanvas } from "../file_upload/file_upload_ui.js";import { INSERT_ICON_COMMAND } from "../inline_icon/inline_icon_editing.js";import InlineIconUI from "../inline_icon/inline_icon_ui.js";import InsertDateTimePlugin, { COMMAND_NAME as INSERT_DATE_TIME_COMMAND, getDateTimeFormatOptions } from "../insert_date_time.js";import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from "../internallink.js";import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";import MathUI from "../math/math_ui.js";-import { INSERT_MERMAID_COMMAND } from "../mermaid/insert_mermaid_command.js";-import type { MermaidSample } from "../mermaid/mermaid_ui.js";+import { INSERT_INLINE_EMBED_COMMAND } from "../content_embed/inline_source.js";+import { insertMermaidDiagram, type MermaidSample } from "../mermaid/mermaid_ui.js";import { getDefaultRatios, MAX_COLUMNS, MIN_COLUMNS } from "../multicolumn/constants.js";import { BUTTON_ICON_SIZE, createLayoutFigure } from "../multicolumn/multicolumn_ui.js";import SnippetsEditing from "../snippets/snippetsediting.js";@@ -345,16 +345,6 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitioisEnabled: canEmbedFiles,execute: insertDrawingCanvas},- {- id: "mermaid-diagram-embed",- title: t("Mermaid diagram (embedded)"),- description: t("Insert a Mermaid diagram stored as an attachment."),- aliases: [ "mermaid", "diagram", "flowchart" ],- icon: bxNetworkChart,- commandName: "fileUpload",- isEnabled: canEmbedFiles,- execute: insertMermaidDiagram- },...buildMermaidSlashCommands(editor),{id: "ai-assistant",@@ -562,15 +552,14 @@ function buildMermaidSlashCommands(editor: Editor): SlashCommandDefinition[] {const t = editor.locale.t;const samples = (editor.config.get("mermaid.samples") ?? []) as MermaidSample[];- // The blank diagram. Replaces CKEditor's built-in `insertMermaidCommand` slash command (removed- // via `removeCommands`), which uses a generic icon.const blank: SlashCommandDefinition = {id: "mermaid",title: t("Mermaid diagram"),description: t("Insert an empty Mermaid diagram"),aliases: [ "mermaid", "diagram", "flowchart" ],icon: bxNetworkChart,- commandName: INSERT_MERMAID_COMMAND+ commandName: INSERT_INLINE_EMBED_COMMAND,+ execute: insertMermaidDiagram};const templates = samples.map((sample, index) => ({@@ -581,8 +570,8 @@ function buildMermaidSlashCommands(editor: Editor): SlashCommandDefinition[] {description: t("Insert a \"%0\" Mermaid diagram template", sample.name),aliases: [ "mermaid", "diagram", sample.name ],icon: bxNetworkChart,- // Inserts a mermaid block pre-filled with the sample source (see insertMermaidCommand).- execute: (target: Editor) => target.execute(INSERT_MERMAID_COMMAND, { source: sample.content })+ commandName: INSERT_INLINE_EMBED_COMMAND,+ execute: (target: Editor) => insertMermaidDiagram(target, sample.content)}));return [ blank, ...templates ];diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid.tsindex 18d4ed04a7..e827fe070d 100644--- a/packages/ckeditor5/src/plugins/mermaid/mermaid.ts+++ b/packages/ckeditor5/src/plugins/mermaid/mermaid.ts@@ -1,65 +1,32 @@import { Plugin } from 'ckeditor5';-import "../../theme/mermaid.css";-import MermaidEditing from './mermaid_editing.js';-import MermaidToolbar from './mermaid_toolbar.js';import MermaidUI, { type MermaidSample } from './mermaid_ui.js';/**- * The Mermaid diagram feature: a `<mermaid>` block widget with a source textarea and a rendered- * preview, switchable between source / split / preview modes.- *- * This is a "glue" plugin which loads {@link MermaidEditing}, {@link MermaidToolbar} and- * {@link MermaidUI}.- *- * The mermaid library itself is not a dependency — the host supplies it through- * `config.mermaid.lazyLoad`, so the diagram renderer is only fetched when a diagram is shown.- *- * Derived from CKSource's `@ckeditor/ckeditor5-mermaid`; see `LICENSE.md` and `README.md` next to- * this file.+ * The Mermaid diagram feature: the button and the slash commands that insert a diagram. A diagram+ * is an embed of its source, which `ContentEmbedInlineSource` keeps as a `language-mermaid` code+ * block and the host renders, so `mermaid` must be one of `contentEmbed.inlineLanguages`.*/export default class Mermaid extends Plugin {-static get requires() {- return [ MermaidEditing, MermaidToolbar, MermaidUI ];+ return [ MermaidUI ];}public static get pluginName() {return 'Mermaid' as const;}--}--declare global {- interface MermaidInstance {- initialize( config: MermaidConfig ): void;- render( id: string, source: string ): Promise<{ svg: string }>;- }-- interface MermaidConfig {-- }-- var mermaid: Mermaid | null | undefined;}declare module 'ckeditor5' {interface PluginsMap {[ Mermaid.pluginName ]: Mermaid;- [ MermaidEditing.pluginName ]: MermaidEditing;- [ MermaidToolbar.pluginName ]: MermaidToolbar;[ MermaidUI.pluginName ]: MermaidUI;}interface EditorConfig {- "mermaid"?: {- lazyLoad?: () => Promise<MermaidInstance> | MermaidInstance;- config: MermaidConfig;+ mermaid?: {/** Diagram templates listed in the insert-diagram split button's dropdown. */samples?: MermaidSample[];- /** Opens the Mermaid help, called by the `mermaidInfo` balloon toolbar button. */- openHelp?: () => void;- }+ };}-}diff --git a/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.ts b/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.tsindex fbe4147948..21674600d9 100644--- a/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.ts+++ b/packages/ckeditor5/src/plugins/mermaid/mermaid_ui.ts@@ -2,13 +2,11 @@* @module mermaid/mermaid_ui*/+import { NEW_MERMAID_CONTENT } from '@triliumnext/commons';+import { addListToDropdown, Collection, createDropdown, type Editor, type ListDropdownItemDefinition, type Locale, Plugin, SplitButtonView, ViewModel } from 'ckeditor5';+import insertMermaidIcon from '../../icons/mermaid-insert.svg?raw';-import previewModeIcon from '../../icons/mermaid-preview-mode.svg?raw';-import splitModeIcon from '../../icons/mermaid-split-mode.svg?raw';-import sourceModeIcon from '../../icons/mermaid-source-mode.svg?raw';-import infoIcon from '../../icons/mermaid-info.svg?raw';-import { addListToDropdown, ButtonView, Collection, createDropdown, Editor, ListDropdownItemDefinition, Locale, ModelElement, Observable, Plugin, SplitButtonView, ViewModel } from 'ckeditor5';-import InsertMermaidCommand, { INSERT_MERMAID_COMMAND } from './insert_mermaid_command.js';+import { INSERT_INLINE_EMBED_COMMAND } from '../content_embed/inline_source.js';/*** A selectable Mermaid diagram template (a localized name and its source@@ -19,193 +17,70 @@ export interface MermaidSample {content: string;}+/**+ * The `mermaid` split button, which inserts a Mermaid diagram as an embed of its source. The main+ * action inserts a new diagram, while the dropdown lists the diagram templates of the+ * `mermaid.samples` config.+ */export default class MermaidUI extends Plugin {- /**- * @inheritDoc- */static get pluginName() {return 'MermaidUI' as const;}- /**- * @inheritDoc- */init() {- this._addButtons();- }-- /**- * Adds all mermaid-related buttons.- *- * @private- */- _addButtons() {- const editor = this.editor;- const t = editor.t;-- this._addInsertMermaidButton();- this._addMermaidInfoButton();- // Translated here rather than inside the helper: each label has to be a literal argument of- // a `t()` call for the message registry to find it (see `messages.ts`).- this._createToolbarButton( editor, 'mermaidPreview', t( 'Preview' ), previewModeIcon );- this._createToolbarButton( editor, 'mermaidSourceView', t( 'Source view' ), sourceModeIcon );- this._createToolbarButton( editor, 'mermaidSplitView', t( 'Split view' ), splitModeIcon );- }-- /**- * Adds the split button for inserting mermaid.- *- * The main action inserts a blank diagram, while the dropdown lists the- * configured diagram templates (see the `mermaid.samples` config). Picking- * a template inserts a diagram pre-filled with its source.- *- * @private- */- _addInsertMermaidButton() {const editor = this.editor;const t = editor.t;- const command = editor.commands.get( INSERT_MERMAID_COMMAND ) as InsertMermaidCommand;- if (!command) {- throw new Error("Missing command.");- }-const samples = editor.config.get( 'mermaid.samples' ) ?? [];- editor.ui.componentFactory.add( 'mermaid', (locale: Locale) => {+ editor.ui.componentFactory.add( 'mermaid', ( locale: Locale ) => {const dropdownView = createDropdown( locale, SplitButtonView );const splitButtonView = dropdownView.buttonView;-splitButtonView.set( {label: t( 'Mermaid diagram' ),icon: insertMermaidIcon,tooltip: true} );+ splitButtonView.on( 'execute', () => insertMermaidDiagram( editor ) );- // Main action: insert a blank diagram.- splitButtonView.on( 'execute', () => this._insertDiagram() );-- // Dropdown: insert a diagram pre-filled with the picked template.- // Reuse the shared scrollable dropdown style so the long list of- // templates doesn't overflow the viewport.- // `createDropdown` already binds the split button's `isEnabled` to the- // dropdown, so binding the dropdown alone disables both parts.+ // `createDropdown` binds the split button's `isEnabled` to the dropdown, so binding the+ // dropdown alone disables both parts.dropdownView.class = 'ck-tn-dropdown';- addListToDropdown( dropdownView, this._getSampleDropdownItems( samples ) );- dropdownView.bind( 'isEnabled' ).to( command, 'isEnabled' );+ addListToDropdown( dropdownView, getSampleDropdownItems( samples ) );+ const command = editor.commands.get( INSERT_INLINE_EMBED_COMMAND );+ if ( command ) {+ dropdownView.bind( 'isEnabled' ).to( command, 'isEnabled' );+ }dropdownView.on( 'execute', evt => {- const source = (evt.source as { commandParam?: string } | undefined)?.commandParam;- this._insertDiagram( { source } );+ const source = ( evt.source as { commandParam?: string } | undefined )?.commandParam;+ insertMermaidDiagram( editor, source );} );return dropdownView;} );}+}- /**- * Inserts a mermaid diagram — blank by default, or pre-filled with the given- * template source — and moves the focus into its editing view.- *- * @private- */- _insertDiagram( options: { source?: string } = {} ) {- const editor = this.editor;- const view = editor.editing.view;-- const mermaidItem = editor.execute( INSERT_MERMAID_COMMAND, options ) as ModelElement;- const mermaidItemViewElement = editor.editing.mapper.toViewElement( mermaidItem );-- view.scrollToTheSelection();- view.focus();-- if ( mermaidItemViewElement ) {- // A view element that is attached always has a DOM counterpart — the editor could not- // have rendered the widget otherwise — so this lookup is not guarded separately.- const mermaidItemDomElement = view.domConverter.viewToDom( mermaidItemViewElement ) as HTMLElement;-- mermaidItemDomElement.querySelector<HTMLElement>( '.ck-mermaid__editing-view' )?.focus();- }- }-- /**- * Builds the dropdown list of diagram templates.- *- * @private- */- _getSampleDropdownItems( samples: MermaidSample[] ) {- const itemDefinitions = new Collection<ListDropdownItemDefinition>();-- for ( const sample of samples ) {- itemDefinitions.add( {- type: 'button',- model: new ViewModel( {- commandParam: sample.content,- label: sample.name,- role: 'menuitem',- withText: true- } )- } );- }-- return itemDefinitions;- }-- /**- * Adds the button that opens the Mermaid help through the `mermaid.openHelp` config callback.- *- * @private- */- _addMermaidInfoButton() {- const editor = this.editor;- const t = editor.t;-- editor.ui.componentFactory.add( 'mermaidInfo', locale => {- const buttonView = new ButtonView( locale );-- buttonView.set( {- label: t( 'Read more about Mermaid diagram syntax' ),- icon: infoIcon,- tooltip: true- } );-- buttonView.on( 'execute', () => {- editor.config.get( 'mermaid.openHelp' )?.();- } );+/** Inserts a Mermaid diagram of `source`, a new one by default, and gives it the focus. */+export function insertMermaidDiagram( editor: Editor, source = NEW_MERMAID_CONTENT ) {+ editor.execute( INSERT_INLINE_EMBED_COMMAND, { language: 'mermaid', source } );+ editor.editing.view.scrollToTheSelection();+ editor.editing.view.focus();+}- return buttonView;+function getSampleDropdownItems( samples: MermaidSample[] ) {+ const itemDefinitions = new Collection<ListDropdownItemDefinition>();++ for ( const sample of samples ) {+ itemDefinitions.add( {+ type: 'button',+ model: new ViewModel( {+ commandParam: sample.content,+ label: sample.name,+ role: 'menuitem',+ withText: true+ } )} );}- /**- * Adds the mermaid balloon toolbar button.- *- * `label` arrives already translated — see `_addButtons()`.- *- * @private- */- _createToolbarButton( editor: Editor, name: string, label: string, icon: string ) {- editor.ui.componentFactory.add( name, locale => {- const buttonView = new ButtonView( locale );- const command = editor.commands.get( `${ name }Command` );- if (!command) {- throw new Error("Missing command.");- }-- buttonView.set( {- label,- icon,- tooltip: true- } );-- buttonView.bind( 'isOn', 'isEnabled' ).to( command as (Observable & { value: boolean; } & { isEnabled: boolean; }), 'value', 'isEnabled' );-- // Execute the command when the button is clicked.- command.listenTo( buttonView, 'execute', () => {- editor.execute( `${ name }Command` );- editor.editing.view.scrollToTheSelection();- editor.editing.view.focus();- } );-- return buttonView;- } );- }+ return itemDefinitions;}diff --git a/packages/trilium-core/src/services/sanitizer.spec.ts b/packages/trilium-core/src/services/sanitizer.spec.tsindex 0aa902290d..6f010fe25b 100644--- a/packages/trilium-core/src/services/sanitizer.spec.ts+++ b/packages/trilium-core/src/services/sanitizer.spec.ts@@ -58,6 +58,10 @@ describe("sanitize", () => {const dirty = `<figure class="include-note" style="--include-note-height:calc(100vh);--other:1em" data-note-id="abc"></figure>`;expect(sanitizeHtml(dirty)).toBe(`<figure class="include-note" data-note-id="abc"></figure>`);++ // An embed that keeps its source in the note is saved as a code block.+ const inline = `<pre style="--include-note-width:30em;--include-note-height:12.5em" data-box-size="medium"><code class="language-mermaid">graph TD;</code></pre>`;+ expect(sanitizeHtml(inline)).toBe(inline);});it("keeps the hidden-border style on table header cells", () => {diff --git a/packages/trilium-core/src/services/sanitizer.ts b/packages/trilium-core/src/services/sanitizer.tsindex 15fca05028..13c29286c3 100644--- a/packages/trilium-core/src/services/sanitizer.ts+++ b/packages/trilium-core/src/services/sanitizer.ts@@ -89,6 +89,11 @@ export function sanitizeHtml(dirtyHtml: string) {"--include-note-width": sizeRegex,"--include-note-height": sizeRegex},+ // The size of a resized embed that keeps its source in the note, as a code block.+ pre: {+ "--include-note-width": sizeRegex,+ "--include-note-height": sizeRegex+ },img: {// Allow fractional ratios too (e.g. OneNote reports 577.5×277.5 screen clippings)."aspect-ratio": [ /^\d+(\.\d+)?\/\d+(\.\d+)?$/ ],