Build your personal knowledge base with Trilium Notes
name: developing-content-embeds
description: >-
Use when building or changing an embed in a text note — an included note, an attachment embed such as a canvas drawing (CanvasDrawing), a source embed such as a Mermaid diagram (MermaidDiagram, SOURCE_EMBED_TYPES), or a YouTube video (ContentEmbedVideo) — or adding an embed kind. Covers the storage forms (data-note-id, data-attachment-id, inline <pre><code class="language-…">), the editor plugin (packages/ckeditor5/src/plugins/content_embed/: content_embed.ts, inline_source.ts, toolbar, box-size dropdown), the host contract (contentEmbed.loadAttachment(), contentEmbed.loadInline()), the client box (ContentEmbed, text/utils.ts), the content component contract (useEditableEmbed(), ContentEmbedToolProvider, Editable, display modes, fullscreen), reusing the note type's component as canvas and Mermaid do, the read-only paths (AI chat, Markdown preview, print, share), and traps hit (detached content, CodeMirror read-only fixed at creation, the CKEditor :first-child separator rule, untitled box sizes, class clashes).
Developing content embeds
An embed is a box in a text note that shows content other than text: another note, an attachment of the note, or a source kept in the note itself. The box (title row, size, caption, fullscreen, toolbar, menu) is shared; what it shows is a content component chosen by the kind of content. Two components show what a fully featured embed looks like:
- Canvas drawing —
apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx. Excalidraw scene in an attachment (CANVAS_ATTACHMENT_MIME). A picture while not edited, Excalidraw while Editable is on. Its own tools in the embed toolbar (CanvasEmbedTools.tsx). - Mermaid diagram —
apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx. A source embed: the source sits inline as a code block, or in an attachment (MERMAID_ATTACHMENT_MIME); one component serves both. Source, split or preview view; zoom and syntax-help tools.
The rule both follow: the embed is built from the note type's own component, not beside it.
CanvasDrawing renders CanvasEditor from the canvas note (canvas/Canvas.tsx); MermaidDiagram
renders SplitLayout from helpers/SplitEditor.tsx and SvgPreview / SvgZoomControls /
useSvgRender() / useSvgZoom() from helpers/SvgSplitEditor.tsx, the same parts the Mermaid
note uses. A first version of the Mermaid embed reimplemented its panes, viewer and error box and
drifted at once (a raw error box instead of the note's error card, no divider). When the note
type's component is bound to a note (labels, noteContext, EditableCode), extract the
note-independent part into an exported component in the same module and have the note type use
it too — SplitEditor → SplitLayout + useMountedPanes() is the worked example. Only the parts
that are about storage stay separate (the embed's source pane is CodeEmbedEditor bound to a
ContentEditor, the note's is EditableCode bound to the note).
The storage forms
What the text note saves, and what the editor model holds (contentEmbed element):
| Form | Saved HTML | Model attributes |
|---|---|---|
| Included note | <figure class="include-note" data-note-id="…" [data-block="…"]> |
noteId, block |
| Attachment | <figure class="include-note" data-attachment-id="…"> |
attachmentId |
| Inline source | <pre data-box-size=… [data-display-mode=…] data-hide-title data-editable><code class="language-mermaid">…</code></pre> |
language, source |
| Video | <section class="link-embed" data-url=… data-embed-type="youtube" … [data-position=…]> |
the link preview fields: url, embedType, title, image, … |
| Later kind | <section data-trilium-embed="<kind>" …>fallback</section> |
unknownContentEmbed: embedAttributes, embedContent |
All three carry boxSize, hideTitle, editable, displayMode (data-box-size,
data-hide-title, data-editable, data-display-mode) and the resized size as
--include-note-width / --include-note-height in style. The figure keeps an optional
<figcaption>.
Captions of an embed whose element is not a <figure> (_defineCaptionedEmbedConverters()
in content_embed.ts). While such an embed has a caption, the note saves its element in a
<figure class="captioned-content-embed"> (CAPTIONED_CONTENT_EMBED_CLASS), followed by the
<figcaption>, and without a caption it saves the bare element again. Every kind gets this
without code of its own: a low data downcast listener wraps whatever element the kind's
converter bound, a data mapper hook puts the caption after that element, and an upcast at
high converts the element and turns the <figcaption> into the caption of the embed
(isEmbedCaptionToggleable()), or into text after content that takes none. The figure is bound
to the embed as well, view to model only, so the mapper counts it as one node; the embed still
maps to its element, where the attribute converters (width, position) write. A kind opts in
through hasCaptionSupport(); only inline source embeds stay out. Read-only views replace the
figure with the box and move the caption into it (replaceWithEmbedBox() in
content_renderer_text.ts); share pages move style, data-box-size and data-position from
the element to the figure (moveBoxToCaptionedFigure()), which the share CSS places; Markdown
export keeps the figure as raw HTML.
An embed whose caption has the selection looks selected, as one whose player or editor has
the focus (which selects it): markEmbedOfSelectedCaption() adds ck-widget_selected after
Widget marks the selection and takes it away on cleanSelection. Widget itself marks only
widgets inside the selection.
Inline source (
inline_source.ts,ContentEmbedInlineSource) keeps the document readable elsewhere: the note exports to Markdown as a fencedmermaidblock, other apps render it, and undo in the note undoes source edits through the shared undo history (see Undo history below).setSource()writes outside the undo stack and does not redraw the embed, which would remount its editor. The plugin hands out oneInlineEmbedSourceper embed element, which keys its history. It is converted only for languages incontentEmbed.inlineLanguages(fromSOURCE_EMBED_TYPESintext/config.ts); a code block of another language stays a code block.Video (
video_embed.ts,ContentEmbedVideo) is the Embed display mode of a link preview whose URL has a video (getLinkPreviewVideoId()in commons). It keeps the saved form of the link preview, so released versions still play it, and addsdata-box-size,data-hide-title,data-positionand--include-note-width. Its sizes are Medium and Full (VIDEO_EMBED_BOX_SIZES);readVideoEmbedBox()reads a video saved before as Full and untitled, andcreateVideoEmbed()makes a new one Medium atgetVideoMediumWidth()(20em high), which the box size command sets again. Height follows width (isHeightResizableis per element). A size change only restyles the figure: theattribute:boxSizeconverter skipsreloadEmbeddedContent()for a video, since a new player stops the playback. A caption is saved in the captioned figure (above). The video toolbar also shows while the caret is in the caption (findRelatedVideo()), and its Copy URL and Display act on the video throughChangeLinkDisplayCommand._getTarget(): the selected preview, else, unless the caret is on a link, the video of the caption (getCaptionedEmbed()).getSelectedLinkWidget()itself reads only the selected element, as the link balloon shares the command and Ctrl+K in a caption must edit the caption's own link.rebuildLinkWidget()copies the caption into a preview that keeps its shape; a Card, Inline or Plain link has no caption, sokeepCaptionText()moves its content into a paragraph after the video. The shape is the link preview fieldaspectRatio(data-aspect-ratio="9/16"), which the server reads from oEmbed for the video's/shorts/address (the watch address of a Short answers 16:9).getVideoAspectRatio()validates it; every box that draws a player (the editing figure,applyVideoEmbeds(),renderLinkEmbedHtml(), the share renderer'ssetVideoBox()) writes it as--video-aspect-ratio, which the player'saspect-ratioand the 70vh cap of Full read. Only Full is capped; Medium keeps its saved width.setVideoBox()also writesdata-box-sizeon the shared section, Full for a video saved before box sizes. A preview without one is 16:9. A new link preview field goes intoLINK_PREVIEW_DATA_ATTRIBUTESandreadLinkPreviewData(), bothLinkEmbedMetadatatypes (commons and the editor'saugmentation.ts) and the client'sfetchMetadata();META_KEYS, the schemas and the converters follow the map. It renders throughcontentEmbed.loadVideo()(loadVideoEmbed(), whose title row opens the embed menu only in the editor) and has a toolbar of its own (videoEmbedincontent_embed_toolbar.ts): Copy URL, the link preview's Display dropdown and ⋮. The caption is toggled from ⋮ only. Its ⋮ menu (getVideoItems(), picked by theurlofContentEmbedState) puts Open externally (openUrlExternally()inservices/open.ts) above the embed's commands and Delete below.ReadOnlyText'sapplyVideoEmbeds()swaps the section for the same box. The box has no backdrop (DIRECT_CONTENT_TYPES), so one click plays and selects. The facade takes the focus on click andplayVideo()hands it to the player once loaded: Chromium blurs the editor when a focused element is removed. A click into a frame fires no focus event in the page, sofireFrameFocusEvents()incontent_embed.tsfiresfocusat a frame in an embed that a windowblurleaves focused, andbluron the next windowfocus; the embed's ownfocuslistener andFocusTrackerdo the rest. A click from one frame into another fires no window event either, so after a windowblurone shared interval (watchFrameFocus(), 200 ms, for every editor's check inframeFocusChecks) readsdocument.activeElementuntil no frame has the focus or the window has it back. These synthetic events neither bubble nor firefocusin/focusout, so the box'suseFocusWithin(), which draws the.include-note-body.activeoutline, also listens tofocus/blurin the capture phase.createLinkPreview()inlink_embed_commands.tsis the one place that pickslinkMention,linkEmbedor a video embed for a display mode. The YouTube video prompt (youtube_video.ts) inserts the player only oncefetchMetadata()has returned, with no link meanwhile: itsonInsert()rejects on unresolved metadata, and the host's prompt keeps Insert disabled while it waits and shows an error toast when it rejects.Legacy blocks — a
<pre>withoutdata-box-sizepredates the embed (the old Mermaid plugin).getModeOfSavedView()loads it editable, in the view of itsdata-trilium-display-modeor split, at Medium. A saved embed keeps exactly what it has.Later kind (
CONTENT_EMBED_KIND_ATTRIBUTEinpackages/commons/src/lib/content_embeds.ts) is the form for any new kind that is neither a note/attachment reference nor a code block, so that an older version keeps it instead of dropping it on save, without a sync version bump.UnknownContentEmbed(unknown_embed.ts) keeps the section raw throughregisterRawContentMatcher(), renders it as an.include-notebox that the host fills throughcontentEmbed.loadUnknown()(ContentEmbedError, the box of a missing note, with thebx-erroricon), and writes it back with itsclassanddata-*attributes (anything else,styleincluded, is dropped) and its content, sanitized by the host'scontentEmbed.sanitizeHtml. Its upcast runs athigh, before General HTML Support. A new kind must follow the contract older versions rely on:- Settings go in
data-*attributes on the section, never instyle(the import sanitizer allows--include-note-*only onfigureandpre). - A note reference is
data-note-idon the section itself, whichfindIncludeNoteLinks()turns into theincludeNoteLinkbacklink. - An attachment reference is
data-attachment-idon any element (or anapi/attachments/<id>/imageURL), whichcheckImageAttachments()keeps from erasure and rewrites when the attachment is copied. - The content is a static fallback (a link, a picture, the source in a
<pre>): old read-only views, share pages and Markdown export show it.
Read-only views never show the fallback either:
emptyUnknownEmbeds()(content_renderer_text.ts) empties each section into an.include-notebox, keeping only the kind,data-box-sizeand the block ID.ReadOnlyTextthen mounts the same error box (loadUnknownEmbed()), andpostProcessRichContent()leaves the box empty, as it leaves a missing note's. Share pages replace the section, and an include of a missing or unshared note or attachment, with<div class="include-note-unavailable">and a generic message (replaceWithUnavailable()in core'sshare/content_renderer.ts), as the page is public.The version that adds a kind registers its converter above
high. If that converter needs the section's children, narrowENVELOPEinunknown_embed.tsto leave the kind out: the raw matcher removes the children before any converter runs.- Settings go in
Attachment suits large or binary content and content with its own save cycle (Excalidraw). The attachment's content type comes from
getFileContentType()inpackages/commons/src/lib/notes.ts(canvasDrawing,mermaidDiagram), whichgetRenderedContent()dispatches on.
How a box gets its content
- Editor plugin (
packages/ckeditor5/src/plugins/content_embed/).content_embed.tsowns the model, the converters, the commands (contentEmbedBoxSize,toggleContentEmbedTitle,toggleContentEmbedCaption,toggleContentEmbedEditable,contentEmbedDisplayMode,convertEmbedToLink,deleteContentEmbed), the box-size rules and observables such asisSelectedEmbedInline.deleteContentEmbedserves any kind:getDeleteEmbedGroup()inmenus/link_context_menu.tsends the ⋮ menu of a note, an attachment, a video and an extended code block with it. Other inline sources (Mermaid) do not offer it.content_embed_toolbar.tslists the toolbar items;content_embed_tools.tsturns the content's tools into buttons;content_embed_box_size_dropdown.tsthe size menu. The editing view renders an.include-note-wrapperand asks the host to fill it. - Host contract (
ContentEmbedHostincontent_embed.ts, read from the editor config ascontentEmbed):loadNote(),loadAttachment(),loadInline(source, wrapper, boxSize, { isFocused }),loadUnknown(),focusAttachment(),openMenu(),getTools(),enter()andgetAttachmentHref().EditableText.tsximplements them ascontentEmbedHandlers, whichCKEditor.tsxhands tobuildConfig()through a getter.sanitizeHtml()is set inbuildConfig()itself. The plugin never imports client code. - Box (
text/utils.ts).loadEmbeddedAttachment()/loadInlineEmbed()render the content withcontent_renderer, wrap it inContentEmbed(text/ContentEmbed.tsx: title row, fullscreen, exit-fullscreen overlay) andmountEmbedBox(). Content that left the page while it loaded is disposed;watchContentEmbeds()disposes boxes removed later. - Content (
services/content_renderer.ts).renderCanvasDrawing()andrenderSourceEmbed()mount the component throughmountInteractiveWidget()whenoptions.interactive, withgetContentEditor()as itsContentEditor; otherwise a static rendering (the drawing's picture). Lazy modules are listed inCONTENT_RENDERERS.fileso read-only pages and the share theme never load the editors.
The content component contract
A content component receives the content and an optional ContentEditor
(canEdit(), getUnsavedContent(), scheduleSave(), release(); no editor = read-only). Source
embeds receive SourceEmbedProps (content, editor) whichever storage the source has:
InlineSourceEmbed and AttachmentSourceEmbed in text/SourceEmbed.tsx adapt the two.
useEditableEmbed(rootRef, { editor, note, tools, focusTarget })(text/editable_embed.tsx) returnscanEdit(an editor that can save, no#readOnly, database writable) andisEditing(canEditand the embed's Editable toggle on). It registerstoolswhilecanEditand moves the focus tofocusTargetwhen the box takes it. Nested embeds stay read-only (NestedEmbedContext).- Toolbar tools — a
ContentEmbedToolProvider(text/content_embed_tools.ts):getTools(),execute(id),subscribe(), plushasEditableFlag— shows the Editable toggle; the embed carriesdata-editable="true".hasDisplayModes— shows Source/Split/Preview; the embed carriesdata-display-mode.hasPositions— gives an inline source the Position submenu of the ⋮ menu and the toolbar's position dropdown; the embed carriesdata-position. A note, attachment or video embed has the submenu without it (hasEmbedPositions()), and the dropdown only with it.hiddenToolbarItems— moves box size, title, convert-to-link or Editable from the toolbar to the ⋮ menu (an extended code block hides box size and Editable).boxSizeIcon— an SVG the box size dropdown shows in place of the size name, which moves to its tooltip (Box size: %0). Code and Markdown embeds set it even while read-only (hasEditableFlag: false), so every one of them shows the icon; code embeds throughuseContentEmbedMenus().getMenuItems()— items of the ⋮ menu after Editable, in a group of their own (useContentEmbedMenus(rootRef, menus, menuItems)passes them through).
- A CodeMirror pane in an embed (code, Markdown, Mermaid) takes its line wrapping and line
numbers from
useEmbedLines(rootRef, note)(code/CodeEmbed.tsx): passwrapLines/hasLineNumberstoEmbedSourcePaneorCodeEmbedEditor, andmenuItems(the Word wrap and Line numbers submenus) togetMenuItems()while the content can be edited. A note keeps the wrapping in#wrapLines; everything else lives indata-code-wrap-lines/data-code-line-numbers, on the<pre>for inline source (the code view command sets only line numbers on a note embed).ReadOnlyTextcopies them from the<pre>to its box. - The
/list of a CodeMirror pane is the note's own:CodeEditorcallsuseEditorCompletions()(code/editor_completions.tsx) with itscompletionsprop, whichCodeEmbedEditorpasses while it has aneditor. For any language other than Markdown it only loads the snippets of the pane's MIME type and hands them toCodeMirror'sgetSnippets, whichcodeCompletions()(code/code_completions.tsx) lists with the TypeScript completions. For Markdown it registers its own list instead: the commands and snippets,@and[[, which needownerNote(the note an attachment belongs to) for uploads and new notes.getEdgeLeftBy()holds the caret in the embed while either list is open. Specs that mount an editable Markdown pane mockservices/task_states; specs that mount any of them keepservices/i18npartial (importOriginal), asNoteAutocompletereads it.groupon a tool — a separator goes between groups. Notify listeners only when the tools really changed (MermaidDiagramTools.update()compares a JSON snapshot) and after the render (queueMicrotask), as a listener updates the editor's toolbar.
- Reading the embed's state from the content:
useIsContentEmbedEditable(ref),useContentEmbedDisplayMode(ref)(saved mode ornull; resolve withresolveDisplayMode(mode, !isEditing)fromhelpers/split_editor_mode.ts),useContentEmbedEvent(ref, name, cb)forfullscreenChangeStart/enterFullscreen/leaveFullscreen, andshowContentEmbedFullscreen(element). - Fullscreen hides the editor's toolbar (only the content box goes fullscreen). Content whose
controls live in the toolbar must show them over itself meanwhile —
MermaidDiagramshowsSvgZoomControlswhile!canEdit || isFullscreen. The box already has an exit button. - Fullscreen without a title row. The title row holds the box's fullscreen button, so an
untitled Medium or Full box (
needsFullscreenButton()/useNeedsFullscreenButton()) needs the content to offer one: a toolbar tool while it can be edited, anOverlayFullscreenButtonafter the zoom buttons while read-only (no toolbar then). A read-only drawing still has none.
Undo history
The edits made in an embed's CodeMirror (code, Markdown, Mermaid, inline or not) and in a drawing canvas's Excalidraw are steps of the text editor's undo stack, in order with the text's own changes. Three layers, with one recorder per editor in the middle:
EmbedHistory(packages/ckeditor5/src/plugins/content_embed/embed_history.ts, required byContentEmbed) is editor-agnostic.push({ undo, redo })adds a batch that only adds or removes theembedHistoryStepmarker (affectsData: false): it fireschange, which resets the typing buffer, but notchange:data. Therevertevents ofundo/redorun the step; a step that returnsfalseis skipped and the command runs again.isLatest()tells the content whether its step can still grow.undo()/redo()are for keys pressed inside an embed: they focus the text editor when the reverted change was its own.SharedHistory(packages/codemirror/src/shared_history.ts) records the transactions of every view of one document, grouped ashistory()groups them, and applies a step to the view whose document matches, else throughwritewhile no view shows it (a remount in progress). A step whose document changed since does not apply.view.setSharedHistory()replaces the view's ownhistory()and routes Mod-Z/Mod-Y/Mod-Shift-Z, thehistoryUndo/historyRedoinput events and Vim'su/Ctrl-Rto the host.DrawingHistory(canvas/drawing_history.tsx) does the same for Excalidraw, whose 0.18 history is private.useCanvasDrawingPersistence()takes aDrawingMountwhen it reads the content, attaches it once the scene shows, callsrecord()on eachonChangeanddetach()in a layout cleanup. A step is an element delta (before/after clones and the changed keys, neverversion/versionNonce/updated/status) plus the background, recorded onceisInteracting()is false (pointer up, text submitted, line finished). A change with no input inside the root since the last record (an image that finished loading) joins the last step while itisLatest().api.registerAction()replaces Excalidraw'sundo/redoby name, so its keys, its footer buttons andCanvasTools(which clicksbutton-undo) reach the host; the replacement button copies Excalidraw'sToolButtonmarkup. Without a mounted Excalidraw, a step reads the drawing through theDrawingStoreit attached with (the unsaved content, else the blob, so a save made elsewhere since stays), patches it and writes it back; the steps queue one after another and count inrevisiononce written; a step on a live canvas waits behind them. They also patch an Excalidraw that attached during the read (patches are idempotent), and a mount that loaded before a written step (an undone Editable toggle remounts) reads the drawing again at attach. Undo sorts by fractional index when a step setsindex, as Excalidraw renumbers an out-of-order array instead of reordering it.excalidraw_contract.spec.tspins the Excalidraw internals this relies on.EmbedHistories(text/embed_history.ts, one perEditableText) gives aContentHistory(host+write) per note ID, attachment ID orInlineEmbedSource, asContentEditor.history. Itshostalso tells whether the note can undo or redo (isEnabled(),subscribe()), for the drawing's buttons. It imports no CodeMirror or Excalidraw at runtime:CodeEmbedEditorcreates theSharedHistoryon it andgetDrawingHistory()theDrawingHistory, each attached while mounted, read-only included.
Content loaded from elsewhere goes through view.loadText(), which stays out of the history; a
setText() (re-indent) is a step. The content prop of CodeEmbedEditor loads, so a change made
while read-only (the re-indent stand-in in CodeEmbed.tsx) calls setText() on the read-only view,
after loading the unsaved content of the other embeds into it, or Undo skips it or reverts their
edits. Another editor joins by pushing its own steps to EmbedHistory through the same host.
Included text notes keep their own history. Testing it live: open the note in one tab only, as
editors of one note in several tabs reload each other's saves and mix up the result.
Recipe: a new source embed (a diagram language)
- Add a
SourceEmbedTypetoSOURCE_EMBED_TYPESinapps/client/src/services/source_embeds.ts:language,mime(a*_ATTACHMENT_MIMEinpackages/commons/src/lib/notes.ts),contentType,load()(lazy import of the component),renderPreview()(static rendering, used by the AI assistant's inline previews throughcontentEmbed.renderInlinePreview). - Map the MIME to the content type in
getFileContentType()and give it an icon in the attachment icon map next to it; add the content type to the list incontent_renderer.ts. - Write the component on the note type's parts (see the rule above). For a split source/preview
view,
SplitLayout+useMountedPanes()+EmbedSourcePane(incode/CodeEmbedEditor.tsx) give the layout, the divider, the error card, the stale badge and a source pane that stays mounted behind the preview and shares the note's undo history. Delay re-rendering withuseDebouncedValue(). Give the root theinclude-note-box-heightclass for the 10/20/50em heights per box size and full height in fullscreen, and round it with--_include-note-content-*-radius(edge to edge) or--_include-note-framed-*-radius(inside the 2px frame), all instyle.css. Content that draws the frame as padding of the content box sets--_include-note-frame-heightthere (MermaidDiagram.css), which.include-note-box-heightsubtracts. - An insert command:
INSERT_INLINE_EMBED_COMMANDwith{ language, source }(seemermaid_ui.tsandslash_commands.ts). New embeds are editable, untitled and Medium. - Read-only rendering needs nothing more:
applySourceEmbeds()inReadOnlyText.tsxpicks up any language ofSOURCE_EMBED_TYPES.
Recipe: a new attachment embed with its own editor (like canvas)
- A MIME constant and content type (
getFileContentType()), aCONTENT_RENDERERS.fileentry and arender…()branch ingetRenderedContent()that mounts the component when interactive and renders a static picture otherwise. - Insert by uploading an empty file as an embed (
insertDrawingCanvas()infile_upload/file_upload_ui.ts:fileUploadwithasEmbed,boxSize,hideTitle,editable,focusEmbed). - Persistence through the
ContentEditor(useAttachmentEditor()/bindAttachmentEditor()intext/attachment_saves.tsbatch and retry the saves, and flush them before leaving). If other places need a picture without loading the editor (share pages, previews), save one as an image attachment beside the content, aspersistence.tsdoes undergetDrawingPictureTitle(). - An attachment detail view reusing the same editor (
CanvasDrawingDetailinAttachment.tsx). - Share pages render on the server (
renderAttachmentEmbed()inpackages/trilium-core/src/share/content_renderer.ts): add a branch there, or the attachment falls back to a link.
Read-only paths
| Where | Path | What an embed gets |
|---|---|---|
| Read-only note, AI chat replies, tool results | ReadOnlyTextContent (text/ReadOnlyText.tsx) |
applyContentEmbeds() → loadEmbedded*(); applySourceEmbeds() → loadInlineEmbed() (text/utils.ts) with a fixed read-only source. Same box and component as the editor. |
| Markdown note preview, a chat reply while streaming | ReadOnlyTextContent with isChanging |
Diagrams drawn in place (rewriteMermaidDiagramsInContainer() + applyInlineMermaid()), which keep the last drawing while the next renders; a box would remount on every update. |
Print (glob.device === "print"), included notes, previews |
postProcessRichContent() in services/content_renderer_text.ts |
Drawn in place; printing snapshots before a box would draw. |
| Share pages | server share/content_renderer.ts, share theme content/mermaid.ts |
Static: the drawing's picture as <img>, Mermaid drawn over its code block. No box. |
isChanging flips when a chat reply finishes: RawHtmlBlock is keyed on the choice, because the
in-place drawings replaced the code blocks the boxes need.
Traps already hit
A write held back is part of the note.
InlineSourceEmbedwrites the source 500 ms after the last change. Until then the text note's model does not have it, so a note switch saved the old source andsetData()then dropped the embed, whose later write went to the graveyard. The editor hands each held write toInlineSourceSaves(text/attachment_saves.ts), which marks the note changed, andgetData()inEditableTextflushes it first — asAttachmentSavesdoes for attachments. The write is outside the undo stack, so it can land after an undo without clearing Redo; the undo step itself is recorded when the source changes (see Undo history).Non-interactive rendering must be finished when it returns. A presentation slide snapshots
getRenderedContent()and disposes it at once, so a mounted component that draws in an effect leaves it blank. Withoutoptions.interactive, draw a picture before returning (SourceEmbedType.renderPreview(),renderCanvasDrawingPicture()).Draw a level's diagrams before its embeds render.
applyInlineMermaid()reads the source from the text of each.rendered-mermaid-diagram, so a pass over a container whose embeds are already drawn renders their SVG text and replaces the drawing with an error.postProcessRichContent()draws its own diagrams beforerenderContentEmbeds(), and printing adds no pass of its own.trimkeeps the<style>inside each SVG.Keep the block ID. A read-only view that swaps the saved element for a box copies
data-trilium-block-idonto it (on the<pre>, or the<code>of older diagrams), or links to the block stop resolving.Content renders detached.
loadInlineEmbed()renders into a detacheddivbefore the box mounts it, so a hook that looks up.closest(".include-note")once finds nothing. Use the helpers (useEmbedState()/whenInPage()insidecontent_embed_tools.ts) that wait for the element to join the page.registerContentEmbedTools()likewise notifies the toolbar only once the content is in the page — otherwise an embed auto-selected on load shows the toolbar of an included note.Switch editability in place, never by remounting.
CodeMirror.tsxfollows itsreadOnlyprop throughsetReadOnly(), which keeps the view, its scroll and selection, and starts a new undo history unless the view has a shared one. Akeythat remountedCodeEmbedEditoron the toggle painted an empty<pre>(a Full box collapsed) and then CodeMirror's light default untilsetTheme()loaded the theme. An embed renders read-only before it finds its figure, so this runs on every editable load too.CodeMirrorkeeps theonContentChangedit was created with, soCodeEmbedEditorreads the currenteditorthrough a ref, and releases it in a layout cleanup aseditorgoes away. Test withEditorView.state.readOnly, notcontenteditable, which CodeMirror leavestrue, and assert the view is the same one after the toggle. A read-onlyCodeEmbedEditorcarries theread-onlyclass, which hides the active-line highlight.A parent render can run effects ahead of CodeMirror's. Preact runs a component's pending effects when it renders again before they flush, which once ran
CodeEmbedEditor's effects beforeCodeMirrorcreated the view: no find target, noonReady. Its effects wait for theviewstate thatonInitializedsets; the content loads in a layout effect, so it paints with the editor.Box sizes need a title row. Tiny and Expandable show only the title, so an untitled inline embed was invisible at Tiny.
INLINE_BOX_SIZES(Small, Medium, Full) limits the dropdown, the command and the ⋮ menu (getBoxSizes(domElement)), and other sizes load as Medium. Give each size a height in the component's CSS ([data-box-size="small"],"full") and100%under.include-note-content:fullscreen, and size the wrapper too (.source-embed), or fullscreen fills only part of the screen.Embeds nest, so scope box rules with
>..include-note[data-box-size="full"] .xor.include-note-content:not(:fullscreen) .xalso matches the content of an embed inside that box: a nested Medium box took the Full height, and a nested box in fullscreen lost its height. Chain the embed's own elements, asMarkdownEmbed.cssdoes:.include-note > .include-note-wrapper > .include-note-body > .include-note-content > .rendered-content.CKEditor hides a toolbar separator that is
:first-child. The leading separator of the content tools needs an override inpackages/ckeditor5/src/theme/content_embed_tools.css.CONTENT_EMBED_DISPLAY_MODE_SEPARATORseparates Editable from the view buttons.Toggling Editable keeps the size of the box, at every box size but Full. Measure both modes in a browser (happy-dom has no layout), and sample every frame of the switch, not only the result: four causes were found so far.
- An editor that loads its content after it mounts (
TextEmbedEditor) collapses a box sized by its content until then.EditableEmbedContentkeeps the preview in place and loads the editor out of sight until the editor callsEmbedEditorShownContext(EditableText'sonContentShown), the wayCanvasDrawingkeeps the picture until Excalidraw draws. - A frame drawn as padding adds to a root of the box height unless it sets
--_include-note-frame-height(above); a resized content box also needsheight: autothen, or it keeps the resized height and adds the frame. - Content whose preview fits its text and whose editor takes the box height (Markdown) gives
the content box itself the box height while it can be edited, in both modes: the
fills-boxrules inMarkdownEmbed.css, the way a resized box behaves. - The editor themes give the last block of an editable root a bottom margin the preview does
not have;
style.csszeroes the last block of.ck-contentin an embed for both. CKEditor still adds room above a leading widget for its selection handle, on purpose.
- An editor that loads its content after it mounts (
Keep the Editable flag and the view separate. Switching the view never touches
editable(contentEmbedDisplayModecommand), and a mode left unset resolves from Editable (split while editable, preview otherwise).Class clashes. The read-only in-place drawing is
.rendered-mermaid-diagram, not.mermaid-diagram, the root of the embed component; one name matched both stylesheets.Inline embeds have no note: hide the caption and title commands, and show the ⋮ menu (
isSelectedEmbedInline);link_context_menu.tsoffers the display modes and the inline sizes.Stacking. The split editor's error card and overlay controls use
z-index: 10; the box's exit-fullscreen group sits above them (11,style.css).Shortcut hints (
useContextualShortcutHints) do not work inside an embed: its content is a standalone Preact root hosted byappContext, so leave the hints button out.
Testing
- Editor plugin: browser-mode specs beside the plugin (
inline_source.spec.ts,content_embed*.spec.ts), run withpnpm --filter @triliumnext/ckeditor5 test <name>; see theckeditor5-testingskill. - Client:
MermaidDiagram.spec.tsx,CanvasDrawing.spec.tsx,content_embed_tools.spec.tsx,editable_embed.spec.tsx,SourceEmbed.spec.tsx,ReadOnlyText.spec.tsx,SvgSplitEditor.spec.tsx. Mount the component in afigure.include-note>.include-note-contentto give it an embed; setdata-editable/data-display-modeon the figure to drive it; dispatchenterFullscreenon the content box for fullscreen. react-zoom-pan-pinchmeasures layout happy-dom lacks: mockTransformWrapper/TransformComponent(the mock dropswrapperClass, so assert on.svg-preview-root).- Translations do not resolve in client specs: count buttons or use ids rather than
aria-labeltext. Andexpect(x?.querySelector(…)).not.toBeNull()passes whenxisundefined— assertxfirst.
Documentation
User-facing changes go in docs/User Guide/User Guide/Note Types/Text/Insert buttons.md (sections
Drawing canvas, Mermaid diagram) and Include Note.md for the box itself; then
node .claude/skills/writing-documentation/docs.mjs sync and check.
Related
- ckeditor5-plugin-development / ckeditor5-testing — editor plugin conventions and specs.
- building-client-ui —
OverlayControlGroup,ZoomControlsand the other overlay controls. - developing-mermaid-highlighting — the CodeMirror Mermaid language the source pane uses.
- developing-share-pages — the share theme's own rendering of embeds and diagrams.