Editing, rendering, and presentation packages
These packages provide shared browser behavior for editing note content, converting it between forms, displaying code and documents, and arranging panes. They keep content rules consistent across editors, previews, exports, PDF views, and published pages. See also Shared foundations, Core domain and common contracts, and Client note editing and navigation.
System map
Note content moves through an editing surface, a conversion boundary, or a presentation path. The host application owns note state and services. These packages provide the user-facing behavior around that state.
flowchart LR
N[Note content] --> E{Editing surface}
E -->|Rich text| CK[CKEditor]
E -->|Code or Markdown| CM[CodeMirror]
CK --> S[Saved content]
CM --> S
S --> P{Presentation path}
P -->|Rich content| ST[Share theme]
P -->|Code| HJ[Highlight.js]
P -->|PDF| PDF[PDF viewer]
S -->|HTML to Markdown| TD[Turndown GFM]
E --> L[Split.js layout]
P --> L
Content editing
CKEditor editor profiles
CKEditor is the structured text surface for notes, attributes, relations, chat input, and memos. Fixed-toolbar and floating-toolbar profiles share the same content rules, while smaller profiles carry only the features their host surface needs. The host supplies links, uploads, icons, drawings, media prompts, dialogs, and other services through callbacks.
Trilium owns the GPL replacements for the premium editing features it needs. Slash commands, format painting, snippets, assistant actions, and Vim mode therefore use the same editor boundary as the rest of the editing system. Vim mode is optional and can add modal editing without changing the note model or undo history. The core profile also includes caret and view safeguards for widgets, hidden roots, drag moves, browser drag selection, and schema cleanup. Undo and redo keep the restored selection in view after the model changes.
References: packages/…/index.ts• L5-16 packages/…/index.ts• L98-138 packages/…/plugins.ts• L112-195 packages/…/plugins.ts• L214-239 packages/…/plugins.ts• L282-357 packages/…/keep_drag_selection.ts• L3-35 packages/…/scroll_on_undo_redo.ts• L3-18 packages/…/package.json• L15-25
Editor and read-only styles
The CKEditor style bundle is the visual contract for rich content in both the editing surface and the client’s read-only view. The client can load the ordered styles without loading the editor code, so headings, widgets, tabs, columns, embeds, and other content keep the same visual rules after editing ends.
References: packages/…/styles.ts• L1-5 packages/…/styles.ts• L7-41 packages/…/mention.css• L1-7
Editor boundary behavior
Editor boundary behavior keeps content and editor controls stable when browser focus or host visibility changes. It also preserves the top-level heading boundary: an existing h1 remains a heading, while normal heading controls do not offer a second top-level heading because the note title fills that role.
- Dragging selected text to another editable field lets the browser insert the text there while the editor removes the selection through its model.
- During a desktop Firefox drag, the browser keeps the live DOM selection until the drag ends. This prevents a widget selection from moving the drag range to the end of the note.
- When an editor root is hidden, contextual and host-rendered balloons stay hidden. They become visible and reposition when the root returns.
- Balloon reposition requests without a usable target are ignored, so a widget toolbar cannot retain a stale position while the selection moves away.
- Attributes that are not valid for a newly inserted or renamed model element are removed, so a command cannot carry old state into an incompatible element.
- Arrow keys can leave a table on the adjacent insertion side instead of selecting the whole table.
- Up and Down can cross lines that contain only inline widgets. The editor places the caret beside the widget instead of letting each browser choose a different edge or leaving the note.
- Undo and redo scroll to the restored selection on the next animation frame. A destroyed editor does not run the delayed scroll.
References: packages/…/drag_out_of_editor.ts• L3-29 packages/…/keep_drag_selection.ts• L3-35 packages/…/heading_level_one.ts• L3-34 packages/…/hidden_editor_balloons.ts• L3-61 packages/…/keep_balloon_positions.ts• L1-30 packages/…/drop_disallowed_attributes.ts• L3-31 packages/…/table_exit_caret.ts• L7-49 packages/…/inline_widget_caret.ts• L8-14 packages/…/inline_widget_caret.ts• L58-167 packages/…/keep_view_mappings.ts• L3-29 packages/…/scroll_on_undo_redo.ts• L7-17
Clipboard indentation
Clipboard indentation keeps visual block indentation usable when content crosses the plain-text clipboard boundary. Copy writes one tab per indent level, and a plain-text paste reads shared leading tabs back as block indentation while leaving rich HTML and code-block tabs to their normal paths.
References: packages/…/clipboard_plain_text_indent.ts• L4-17 packages/…/clipboard_plain_text_indent.ts• L27-55 packages/…/clipboard_plain_text_indent.ts• L59-80 packages/…/clipboard_plain_text_indent.ts• L83-132
Editor localization
Editor localization joins CKEditor’s catalog with the host message catalog. The locale service maps application locale IDs to the language CKEditor resolves, loads catalogs on demand, and registers shared catalogs for small editors that cannot wait for a full editor configuration.
This keeps host wording and editor wording aligned across full editors, chat inputs, memos, and menus. Locales without a CKEditor catalog still receive host wording and use the editor’s English fallback where no translation exists.
References: packages/…/i18n.ts• L11-27 packages/…/i18n.ts• L109-167 packages/…/i18n.ts• L170-216
Editor assistance and host menus
Editor assistance gives users one way to reach commands across desktop, mobile, and embedded content. Context toolbars, mobile menus, the slash palette, icon picker, Markdown import, date insertion, media prompts, and link dialogs open host-owned surfaces without taking ownership of note state.
Hosted balloons are the shared boundary for dialogs and pickers. CKEditor places the balloon at the caret and manages its lifetime, while the host paints content into it or uses a separate surface on small screens. The boundary keeps focus, Escape handling, outside clicks, and repositioning consistent when host content changes size.
Toolbar groups can also hand their entries to a host menu. The editor reports current labels, states, enabled actions, nested groups, and focus behavior so the host can use one menu style across fixed, floating, block, widget, and mobile toolbars.
The slash palette builds its catalog from the active editor. It hides commands that are not loaded or not valid for the current selection, ranks title and alias matches, and checks enablement again when an item is committed. AI quick actions and snippets join the catalog when their editor services are available.
Mention feeds use the same host-list boundary for note, attribute, relation, and slash completion. The editor reports the typed query and caret position, forwards list keys, and commits the host choice. Escape dismisses the list without changing the document. A list can remain open for a follow-up query after a note link.
References: packages/…/hosted_balloon.ts• L6-105 packages/…/hosted_balloon.ts• L107-209 packages/…/trilium_mention_ui.ts• L48-77 packages/…/trilium_mention_ui.ts• L100-169 packages/…/trilium_mention_ui.ts• L172-242 packages/…/trilium_mention_ui.ts• L244-303 packages/…/trilium_mention_ui.ts• L365-525 packages/…/types.ts• L21-112 packages/…/slash_commands.ts• L118-180 packages/…/toolbar_group_menu.ts• L21-82
Vim editing mode
Vim editing mode provides modal editing for rich-text notes while CKEditor remains the source of truth for content, widgets, selection, and undo. It loads only when enabled and presents its mode, messages, command line, key hints, and host actions through a small host interface.
The mode treats note blocks as lines for motions and operators, then maps each edit back to rich content. It can reveal collapsed content for movement or search, enter an embedded editor or caption, preserve rich formatting in registers, and call the host for save, close, link, and clipboard actions.
References: packages/…/vim.ts• L9-90 packages/…/vim_adapter.ts• L101-121 packages/…/vim_adapter.ts• L416-485 packages/…/vim_commands.ts• L129-148
Structured block editing
Structured block features let notes use containers and widgets instead of plain paragraphs. Users can move blocks, reference selected blocks, switch tabs, arrange columns, collapse heading sections and nested list items, use admonitions, add footnotes, and manage richer task-list behavior.
The block handle moves the complete selected structure. It widens a range over covered containers and hidden sections, keeps the selection with the moved content, and provides related copy and delete actions. Keyboard and toolbar move commands use the same logical block unit, while table selections move as table rows when that capability is present. Table paste can insert clipboard content as rows above or below the selected row.
Collapsible headings define a section as the blocks below a heading up to the next heading of the same or a higher level. Their saved state is data-trilium-collapsed="true", while temporary reveal state used by search or navigation does not change the note. The editor and read-only view both let users toggle a section with the heading arrow or keyboard. Collapsible list items use the same saved-state idea for nested items.
Tabs provide an ordered set of titled panels. Users can add, remove, reorder, align titles at the top or bottom, and move panel content. A tab can carry a block reference so navigation can target it like any other block. Outside the editor, tab titles move into a keyboard-accessible scrollable bar. The first panel shows by default, while print order places each title above its panel. Searches, fragment links, and block jumps reveal nested tabs before they move to the target.
The same structures keep a readable shape in narrow editors and print views. Multicolumn layouts stack their columns when space is limited, while tabs expose one panel on screen and place all panels in order for print.
References: packages/…/block_drag_handle.ts• L13-20 packages/…/block_drag_handle.ts• L441-464 packages/…/delete_blocks.ts• L17-31 packages/…/move_block_updown.ts• L25-43 packages/…/table_paste_rows.ts• L7-27 packages/…/collapsible_headings.ts• L8-24 packages/…/collapsible_headings_editing.ts• L14-41 packages/…/collapsible_headings_editing.ts• L62-89 packages/…/collapsible_headings_read_only.ts• L8-38 packages/…/collapsible_headings_read_only.ts• L91-110 packages/…/collapsible_headings_ui.ts• L13-18 packages/…/constants.ts• L1-24 packages/…/collapsible_list_items.ts• L32-45 packages/…/todo_list_multistate_editing.ts• L15-40 packages/…/constants.ts• L1-39 packages/…/tabs_editing.ts• L31-79 packages/…/tabs_editing.ts• L276-335 packages/…/tabs_read_only.ts• L18-79 packages/…/tabs_read_only.ts• L137-235 packages/…/multicolumn.css• L10-49 packages/…/tabs.css• L6-15
Aside blocks
Aside blocks place a box of block content beside the main text or on its own line. Users can position, resize, color, remove, and edit the box as one widget, while narrow views stack it with the text instead of forcing an unusable wrap.
An aside keeps its content as normal blocks inside a bounded editing area. The editor repairs pasted or imported content so each aside has valid content and so an aside cannot be nested in another aside. Saved position and color data drive the same layout in the editor, read-only views, and shared pages.
References: packages/…/aside.ts• L11-47 packages/…/aside_editing.ts• L32-75 packages/…/aside_editing.ts• L206-313 packages/…/aside_ui.ts• L21-63
Equation editing
Equation editing gives rich-text notes a focused way to create and change mathematical expressions. The editor opens a form with a live preview at the current selection, keeps the target stable while the form is open, and returns control to the document after save or cancel.
The form supports inline and display equations and can use a math field or a text input. Its rendering engine can load on demand, so equation editing stays separate from the normal text-editing path until a user opens it.
References: packages/…/math_ui.ts• L11-39 packages/…/math_ui.ts• L57-72 packages/…/math_ui.ts• L217-269 packages/…/math_ui.ts• L285-349
Block references
Block references give stable identity to selected blocks so another view can point to one block or a range. The editor keeps IDs unique during paste, split, and move operations. Read-only pages and Markdown notes use the IDs to reveal, scroll to, and briefly highlight the target.
Block jumps reveal enclosing details, tabs, and collapsed heading sections before scrolling. A broken range still shows the block that exists. The same boundary supports linked updates: after editing pauses, the editor reports changed block IDs to the host, or reports that any block may have changed when a larger container changed.
References: packages/…/block_reference_editing.ts• L23-37 packages/…/block_reference_editing.ts• L40-129 packages/…/block_reference_read_only.ts• L21-48 packages/…/block_reference_read_only.ts• L50-73 packages/…/block_reference_read_only.ts• L130-139 packages/…/markdown_shapes.spec.ts• L29-61
Child-note creation
Child-note creation turns the current caret into a link to a new child note. The host creates and opens the note. The editor preserves the insertion position and skips the link if the note changed before creation finished.
References: packages/…/child_note.ts• L7-41 packages/…/child_note.ts• L45-93
Content embeds
Content embeds place a note, block range, attachment, drawing, source-backed item, or media resource inside another note. The saved element keeps identity and display choices. The host renders the current content and can expose tools for editable mode, source/preview/split modes, position, captions, titles, and size.
Media embeds reuse link-preview data to play a YouTube video or an audio or video file. They keep a link-preview-compatible saved shape, while the host supplies the player. Video files can also receive a captured thumbnail and aspect ratio so their display shape remains stable before playback.
Source-backed embeds keep their language and source in the note as a code block. Mermaid uses this contract. Extended code blocks use it to give ordinary code notes a CodeMirror-backed editing surface, with optional language detection when the host can provide it. CKEditor stores the source while the host supplies the nested editor or renderer. The source object reports changes and lets the host flush delayed edits before copy or drag actions.
Known embeds expose a common toolbar. Embed content can add its own tools and can opt into editing, display modes, position controls, and toolbar items. Resizable embeds preview their size during a pointer gesture and save the final width or height as content state. Unknown future embeds remain safe placeholders: they keep their class and data attributes plus sanitized inner content, so an older editor can round-trip content from a newer editor without activating or dropping it.
References: packages/…/index.ts• L14-26 packages/…/content_embed.ts• L80-170 packages/…/content_embed.ts• L518-584 packages/…/content_embed.ts• L608-731 packages/…/inline_source.ts• L35-49 packages/…/inline_source.ts• L140-192 packages/…/extended_code_block.ts• L60-159 packages/…/media_embed.ts• L27-42 packages/…/media_embed.ts• L76-133 packages/…/unknown_embed.ts• L16-24 packages/…/unknown_embed.ts• L44-87
Links and references
References are inline note or attachment links whose visible title comes from host data. Web previews add inline mentions, block cards, and playable media embeds. Each preview stores fetched metadata so a user can change its display without another fetch.
Automatic conversion only acts on a bare HTTP or HTTPS URL. A URL left alone in its own top-level paragraph becomes a block card or player after metadata resolves. A URL in surrounding text or a nested block stays an inline mention. The host can disable this automatic path while keeping manual preview insertion available, and unresolved metadata leaves the original link intact.
The display controls provide an exit from previews. Users can switch among inline, card, player, and plain-link forms, edit a preview through the host link dialog, or remove it and keep its URL as plain text. URL checks stop unsafe stored data from reaching open-link, copy, or plain-link actions. Video and audio players use the same saved preview metadata as cards, which lets old link-preview markup and newer media widgets remain compatible.
References: packages/…/augmentation.ts• L3-20 packages/…/referencelink.ts• L12-83 packages/…/referencelink.ts• L92-148 packages/…/internallink.ts• L41-55 packages/…/internallink.ts• L87-173 packages/…/link_embed_commands.ts• L19-28 packages/…/link_embed_commands.ts• L55-87 packages/…/link_embed_autodetect.ts• L29-88 packages/…/link_embed_editing.ts• L195-242 packages/…/media_embed.ts• L136-155
Files, images, and visual helpers
File editing turns picked, pasted, or dropped files into note attachments. Upload placeholders show the pending item during the async upload, then resolve to the attachment or remove themselves after failure. Images keep stored source separate from the URL used by the editing view and can become drawing embeds through a host conversion service.
Image and embed position controls use one grouped view for in-line, break-text, and wrap-text choices. A small renderer helper also narrows CKEditor’s inline filler behavior so browser spellcheck stops treating text across a formatting boundary as one word.
References: packages/…/fileuploadcommand.ts• L15-31 packages/…/fileuploadediting.ts• L14-21 packages/…/uploadimage.ts• L62-79 packages/…/clipboard_bare_image.ts• L1-61 packages/…/image_position.ts• L7-54 packages/…/image_to_drawing.ts• L47-59
Code editing
CodeMirror source editing
CodeMirror is the source editor for code and Markdown notes. It provides language display, search, folding, diagnostics, completions, and editable or read-only modes while the host keeps ownership of note state. Its MIME map loads language support on demand for code, Markdown, Mermaid, logs, search expressions, and script notes.
The editor can load named light or dark color themes on demand. The same theme data can describe both the live editor and a static code preview, which keeps token colors and editor colors aligned across editing and display.
Script notes receive a type-aware service for completion, hover text, and diagnostics. The visible API changes with the script kind and context. Ordinary code notes receive syntax support without the script language service. Source editors can also join history owned by the host, so nested source changes participate in the surrounding undo flow.
CodeMirror also supplies feedback tools for search queries and safe templates. They color the same tokens that the related parsers read, mark invalid operators or expressions, and can offer a direct fix without taking ownership of the query or template.
References: packages/…/index.ts• L21-31 packages/…/index.ts• L76-98 packages/…/index.ts• L116-207 packages/…/index.ts• L245-276 packages/…/index.ts• L648-755 packages/…/color_themes.ts• L3-10 packages/…/color_themes.ts• L12-235 packages/…/syntax_highlighting.ts• L1-38 packages/…/index.ts• L19-49 packages/…/shared_history.ts• L41-124 packages/…/package.json• L11-75
Markdown block markers
Markdown block markers are atomic editor chips for block IDs. They make reference markers visible without letting ordinary typing split a marker, and they keep the marker with the first part when a line is split. Pasted duplicate IDs are removed outside code, while markers inside code remain ordinary text.
The marker extension also records changes from a loaded base, tracks positions through edits, and can flash a line range after navigation. A delayed read tells the editor which markers identify rendered blocks, so an unresolved marker can remain visible without being treated as an active block link.
References: packages/…/block_markers.ts• L13-60 packages/…/block_markers.ts• L63-125 packages/…/block_markers.ts• L141-224 packages/…/block_markers.ts• L351-477 packages/…/block_markers.ts• L523-601
Search and text tools
CodeMirror supplies shared behavior for search fields, log views, hosted completions, and selection-aware text changes. The host draws result lists and validation messages while CodeMirror keeps caret, keyboard, selection, and edit timing consistent.
Supported transformations keep selected ranges stable and can form one isolated undo step. This lets source editors embedded inside larger note widgets behave as one user action without joining unrelated typing. Search validation also ignores a reply that no longer describes the current query, so delayed checks do not mark newer text with stale errors.
References: packages/…/trilium_search_highlighter.ts• L4-20 packages/…/trilium_log_highlighter.ts• L9-35 packages/…/hosted_completion.ts• L55-81 packages/…/trilium_search_lint.ts• L51-83 packages/…/text_tools.ts• L21-114 packages/…/shared_history.ts• L41-124
Log presentation
The CodeMirror log highlighter turns backend log text into a readable diagnostic view. It marks request status and URLs, slow requests, SQL statements, search expressions, and error, warning, or info blocks with their continuation lines.
The highlighter scans only the newest part of a large log. This keeps the editor responsive while preserving the part users normally inspect. SQL receives the active code theme when a SQL language is available.
References: packages/…/trilium_log_highlighter.ts• L9-18 packages/…/trilium_log_highlighter.ts• L20-68 packages/…/trilium_log_highlighter.ts• L151-195
Markdown editing and preview
Markdown notes connect editable source to a rendered preview. The source remains the user's text. The preview uses the shared content display path for links, diagrams, math, included notes, and code. Shared note context keeps headings, highlights, block markers, and scroll position related across the two views.
References: apps/…/Markdown.tsx• L30-49 apps/…/Markdown.tsx• L79-137 packages/…/block_markers.ts• L34-60
Code preview and syntax highlighting
CodeMirror can produce static code previews with language-aware parsing and a reduced editor theme. It normalizes line endings, renders one element per source line, and highlights only the safe head of very large input. If no language exists or parsing reaches its time limit, the preview remains escaped plain text for the rest of the input.
Highlight.js decorates code that already exists in rendered HTML and uses the shared normalized MIME contract with optional language loaders. CodeMirror serves editing and parser-backed previews, while Highlight.js serves already-rendered code. Preview CSS can carry the selected CodeMirror token and surface colors into the static view.
References: packages/…/code_preview.ts• L15-26 packages/…/code_preview.ts• L41-67 packages/…/code_preview.ts• L82-125 packages/…/preview_theme.ts• L1-80 packages/…/color_themes.ts• L225-235 packages/…/index.ts• L11-37 packages/…/index.ts• L39-108 packages/…/syntax_highlighting.ts• L181-187
Content conversion
Turndown GFM conversion
Turndown converts rich HTML into Markdown for export and selected-content features. Its GitHub Flavored Markdown rules preserve tables, task lists, strikethrough, and highlighted code. Structures with no direct Markdown form remain readable as raw HTML.
The conversion boundary preserves meaning rather than reproducing the editor. Structural HTML, direct text, blank lines, and whitespace-sensitive code need stable handling so exported Markdown can be read or imported again without losing content.
References: packages/…/gfm.ts• L9-18 packages/…/serialize-structural-html.ts• L1-57 packages/…/markdown.ts• L89-93 packages/…/markdown.ts• L1-4
Document viewing
PDF viewing and annotation
The PDF viewer presents a PDF inside the client and can switch between read-only viewing and editing. In editable mode, annotations become note changes and the viewer returns updated PDF data to its parent. The client can use the document structure for pages, outlines, attachments, layers, and annotations.
Saved annotations and current-session changes form one view. The annotation list includes edits that are not yet written to the file, including new drawings and text boxes. Live updates are debounced so sidebar state follows drawing, deletion, color, and comment changes without repeated full-document work. The viewer supports page and annotation navigation through a same-origin message boundary. View history and the reusable signature library remain under host control.
The viewer reports page count and current page, creates on-demand page thumbnails, exposes attachment metadata, and downloads attachment bytes only when the parent requests them. Optional-content layers are reported with their resolved visibility and can be toggled through the same viewer state. All parent messages carry the note and load context so a late frame cannot update another PDF.
Navigation waits for the document and its initial view before applying the newest request. Heading links use the PDF outline and saved revision tags; annotation links use the current annotation position when it exists. The viewer can report a stable reading position and page rotations back to the parent. Document identity uses a protected or unprotected SHA-512 blob ID, computed once per loaded document and shared by the requests that need it.
References: packages/…/bootstrap.ts• L11-83 packages/…/bootstrap.ts• L153-287 packages/…/annotations.ts• L29-68 packages/…/annotations.ts• L70-113 packages/…/annotations.ts• L135-204 packages/…/attachments.ts• L1-38 packages/…/attachments.ts• L40-89 packages/…/layers.ts• L1-15 packages/…/layers.ts• L18-132 packages/…/pages.ts• L1-51 packages/…/pages.ts• L54-91 packages/…/navigation.ts• L34-99 packages/…/navigation.ts• L102-139 packages/…/digest.ts• L12-57 packages/…/position.ts• L19-60 packages/…/toc.ts• L13-20 packages/…/toc.ts• L24-85 packages/…/package.json• L1-19
Layout and presentation
Split pane layout
Split.js supplies shared resizable-pane behavior for the main application layout, multi-note views, and source-preview editors. It manages the gutter and size limits, then reports pane sizes to the host.
Source-preview editors treat pane state as view state rather than note content. They keep both panes mounted when possible and replace old split instances when the mode or view changes. Switching between source, preview, and split views does not discard editor state or scroll position.
References: packages/…/split.js• L104-180 apps/…/resizer.ts• L17-90 apps/…/SplitEditor.tsx• L33-47 apps/…/SplitEditor.tsx• L120-151
Shared published-note presentation
The share-theme package gives published and exported notes a consistent reading surface. Its page model and template assemble metadata, navigation, note content, child links, snippets, a theme selector, and a table of contents before the browser adds optional behavior.
The browser entry point starts layout, navigation, search, theme, and content enhancements as separate guarded tasks. Text pages receive math, diagrams, link previews, tabs, scrollable tables, sticky headers, list alignment, linked-block navigation, and code-copy controls. Shared content styles also carry editor structures such as headings, tables, embeds, code, media, asides, and collapsible content into the published view. Tab styles use the page theme and add contrast for nested tab blocks.
The share view can replace a server-rendered fallback with a read-only widget for image, canvas, mind-map, Mermaid, note-map, relation-map, and other note types. Large diagrams and images use a labeled viewer with bounded zoom. Video and audio previews use click-to-play facades, so a shared page does not contact a media provider or load a file until the visitor asks to play it.
Mermaid pages keep the source or saved image in place until the diagram is ready. A theme change redraws the diagram, and a block ID stays on the rendered element so links still reach the source block.
Link presentation uses the same saved preview data for inline mentions, cards, and media facades. Shared styles keep these forms readable in light and dark themes while allowing long inline links to wrap with their visual treatment intact.
References: packages/…/index.ts• L1-36 packages/…/index.ts• L48-109 packages/…/page.ts• L135-185 packages/…/page.ts• L312-368 packages/…/content.css• L351-400 packages/…/content.css• L520-533 packages/…/link_embed.css• L5-22 packages/…/mermaid.ts• L5-95 packages/…/note_view.tsx• L17-125
Published-page navigation
The table of contents is generated before client scripts run, so a page has usable navigation without JavaScript and avoids a layout shift. Client code adds smooth scrolling, active-section tracking, hidden-tab reveal, and heading-link copying.
In-page links use the same block and anchor jump behavior as the editor. Same-page block links update the address and reveal the target. Fragment links take priority over block parameters. Anchor lookup prefers the content scope of the note that contains the link, while missing or external targets remain normal browser links.
The page model also builds the visible child list and navigation tree. It keeps the active page in context when a subtree is hidden and derives previous and next links from the same site tree. Page metadata and language settings come from the note and site root, so published pages can carry descriptions, social cards, direction, and content language without a client-only pass.
References: packages/…/toc.ts• L6-115 packages/…/page.ts• L112-129 packages/…/page.ts• L141-216 packages/…/page.ts• L411-435 packages/…/page.ts• L483-517 packages/…/page.ts• L541-560 packages/…/in_page_links.ts• L5-25 packages/…/in_page_links.ts• L35-79 packages/…/page.ejs• L137-148
Package relationships
Shared content contract
Editing packages produce content that display and conversion packages must understand. Rich widgets, source blocks, tabs, columns, asides, block references, diagrams, tables, list alignment, link previews, media players, equations, task states, images, collapsible sections, colored widgets, and unknown embeds therefore need matching rules in previews, exports, and shared pages.
Block IDs are one example of this contract. CKEditor preserves them in rich content, Markdown rendering writes them on the blocks it renders, CodeMirror presents their source as atomic markers, and shared pages use them for in-page jumps. Collapsed sections and tabs follow the same pattern: the saved shape stays stable while each view supplies its own interaction. Tab alignment and theme variables must also remain understood by the editor, read-only pages, print output, and shared styles.
References: packages/…/plugins.ts• L79-155 packages/…/plugins.ts• L238-307 packages/…/constants.ts• L9-39 packages/…/markdown_shapes.spec.ts• L29-61 packages/…/block_markers.ts• L34-60 packages/…/gfm.ts• L9-18 packages/…/in_page_links.ts• L35-55 packages/…/content.css• L520-533 packages/…/index.ts• L21-46
Browser-facing boundaries
These packages provide reusable browser behavior rather than a note store. The host owns note state and save timing. The packages own editor behavior, conversion rules, PDF runtime behavior, pane sizing, code display, and page presentation through callbacks, MIME maps, host-rendered menus, PDF messages, split lifecycles, shared history, and service hooks.
The PDF frame is a clear example of this boundary. It receives context in its URL, accepts same-origin commands, and returns document, annotation, position, page, layer, attachment, and save events with note and load context. The parent decides how those events affect note state.
References: packages/…/index.ts• L101-179 packages/…/augmentation.ts• L21-87 packages/…/index.ts• L245-276 packages/…/index.ts• L737-755 packages/…/bootstrap.ts• L15-23 packages/…/bootstrap.ts• L219-241 packages/…/attachments.ts• L40-58 packages/…/layers.ts• L85-91 packages/…/pages.ts• L44-51 apps/…/Pdf.tsx• L104-151 apps/…/SplitEditor.tsx• L138-151
Change checklist
When these files or sections are changed, remember to consider these:
- When a rich structure changes, update its editor, read-only, shared-theme, Markdown preview, and Markdown export paths together.
- When an aside changes, keep its saved content shape, position, width, color, responsive layout, and read-only page styles aligned.
- When a block or toolbar action changes, keep saved data, commands, context menus, mobile menus, slash entries, and shared-page styles aligned.
- When editor profiles change, keep full, field, chat, and memo plugin sets aligned with the commands and menus each host surface expects.
- When Vim mode changes, keep line mapping, rich-content registers, widget entry, hidden-content reveal, host save/close actions, and shared undo behavior aligned.
- When editor focus or visibility behavior changes, keep drag-out model moves, desktop Firefox drag selection, hidden-root balloon state, targetless-position guards, view mappings, inline-widget caret placement, table exit behavior, undo/redo scrolling, and the note-title
h1boundary aligned with browser focus and heading controls. - When host dialogs or pickers change, preserve balloon placement, release callbacks, outside-click rules, focus return, and mobile fallback behavior.
- When mention feeds or slash entries change, keep marker matching, host list state, keyboard ownership, Escape dismissal, follow-up commits, command enablement, and accessibility state aligned.
- When block references change, keep ID validity, uniqueness, range edges, linked-change reports, Markdown marker meaning, read-only jumps, tab reveal, and copy-link formats aligned.
- When embeds change, keep saved identity, display modes, position, size, captions, toolbar tools, nested focus, source history, and unknown-embed fallback aligned.
- When source embeds change, keep the saved code-block shape, language normalization, source subscriptions, copy flush, host loaders, and CodeMirror or renderer modes aligned.
- When link preview or media behavior changes, keep metadata, display modes, URL safety checks, automatic placement rules, plain-link exit, player loading, thumbnails, colors, and host renderers aligned.
- When collapsible headings or list items change, keep the saved collapse attribute, hidden-section rules, temporary reveal behavior, keyboard and pointer controls, block movement, and read-only presentation aligned.
- When tab behavior changes, keep the saved alignment, editor activation, nested reveal, title-bar keyboard behavior, fragment jumps, block references, accessible title-panel links, and print ordering aligned.
- When task states change, keep configured state names, native checkbox states, custom attributes, split-row behavior, tooltips, and shared-page titles aligned.
- When a MIME type changes, update CodeMirror editing, CodeMirror preview, Highlight.js, client MIME selection, and light and dark token colors.
- When a CodeMirror theme changes, keep its ID, light or dark variant, lazy package load, editor application, preview CSS, and published code colors aligned.
- When a script API changes, update the MIME-specific language service, runtime globals, completion, hover, and diagnostics together.
- When search or template syntax changes, keep token coloring, diagnostics, fix ranges, parser rules, and delayed-result freshness checks aligned.
- When text tools change, preserve selection direction and isolated undo behavior for multi-range operations.
- When block-marker rules change, keep renderer block assignment, atomic editing, duplicate-ID handling, split-line behavior, change records, and jump flashes aligned.
- When editor locale handling changes, keep application locale IDs, CKEditor language IDs, upstream catalogs, host messages, global small-editor registration, and plural handling aligned.
- When math editing changes, keep the equation model, toolbar command, preview engine, display mode, and Markdown or shared-page renderers aligned.
- When PDF messages or saves change, update viewer and client ends. Keep note, load, and protection context aligned, and commit active annotation edits before serialization.
- When PDF annotations change, keep stored annotations, editor overrides, unsaved editor entries, debounce triggers, type names, and sidebar navigation compatible.
- When PDF attachments change, keep metadata extraction, attachment IDs, demand reads, filenames, byte sizes, same-origin requests, and load context compatible.
- When PDF layers change, preserve recursive order flattening, named-layer filtering, shared optional-content state, event announcements, and visibility reports.
- When PDF pages change, keep page-init timing, current-page events, parent page commands, thumbnail geometry, error behavior, and load context aligned.
- When PDF heading or annotation navigation changes, keep outline lookup, saved revision tags, current annotation geometry, request ordering, and initial-view timing aligned.
- When PDF identity changes, keep protected and unprotected digest forms compatible with blob tags, cached revisions, and table-of-contents requests.
- When split modes change, destroy old pane instances before creating replacements and keep editor state separate from pane state.
- When headings or block links change, generate one slug or block-range contract and reuse it for content anchors, table-of-contents links, and in-page jumps.
- When share-page startup changes, keep optional enhancements isolated so one rejected task does not stop the page.
- When shared note views change, keep the server-rendered fallback in place until the replacement widget is ready and keep late async drawing from updating an unmounted view.
- When Mermaid presentation changes, keep source placeholders, saved images, block IDs, theme changes, and async replacement behavior aligned.
- When shared tab styles change, keep the theme variables, nested-tab contrast, title overflow, and editor/read-only class names compatible.
- When structural HTML export changes, keep leaf text, direct text, blank lines, and reimport as one stable raw-HTML block.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A new rich structure has no display or export rule | Content looks wrong in a read-only page or loses meaning in Markdown | Treat editor, renderer, and conversion forms as one content contract |
| A block marker is split, duplicated, or treated as code syntax | A Markdown block loses its identity or a marker becomes unsafely editable | Keep markers atomic, preserve them on split, drop duplicates outside code, and use the renderer's block read |
| A hidden section or tab is not revealed before a jump | Search, a block link, or a fragment reaches content that remains invisible | Reveal enclosing details, tabs, and collapsed sections before measuring and scrolling |
| An aside is saved with invalid children or no usable width | Text can disappear inside the box or the page layout can collapse | Repair aside content in the editor and keep its position and width rules shared with read-only styles |
| A host dialog or picker does not release its balloon content | Stale host UI remains attached to a destroyed editor | Pair every hosted render with a release callback and hide the balloon on teardown |
| A widget toolbar receives a position without a target | Repositioning can throw or leave a toolbar tied to the wrong widget | Ignore targetless position requests and preserve the last usable position |
| The browser deletes a dragged range before the editor updates its model | Text is lost or the next render cannot map the selection | Cancel deleteByDrag and let the editor own the move |
| Firefox moves the DOM selection into a fake widget selection during a drag | The browser extends the drag to the end of the note | Keep the DOM selection during desktop Firefox drags and render it after the drag ends |
| A hidden editor stays eligible for balloon display | A toolbar or host popup remains over a different tab or pane | Track root visibility and hide or reposition the balloon when visibility changes |
| Up or Down enters an inline widget-only line | The caret skips content, enters the widget, or jumps to a note edge depending on the browser | Add a usable filler and move the model selection to the widget edge |
| A reused view element loses its DOM mapping | A later selection update can fail during rendering | Restore the retained mapping when the renderer unbinds the old DOM node |
| Heading 1 is added to normal heading controls | Users can create a second top-level heading or trigger the wrong autoformat | Keep the stored h1 form separate from the heading command options |
| Plain-text indentation is added without respecting HTML or code paths | Rich paste behavior changes or literal code tabs become margins | Only convert tab-led text when no HTML exists and margin-based indentation is active |
| Undo or redo restores a selection without a matching scroll | The user cannot see the restored cursor or edit | Schedule the scroll after rendering and skip it after editor destruction |
| A block reference is duplicated or has an invalid range | A jump or linked update points to the wrong block | Validate IDs, repair duplicates, and keep range edges assigned |
| A tab stores an unsupported alignment or loses its title-panel relation | Titles render on the wrong side or assistive navigation loses the active panel | Parse alignment values and keep title, panel, and print-order contracts shared |
| A host tool provider changes its tool shape without updating the embed toolbar | The selected embed shows stale buttons or runs the wrong action | Keep tool IDs, groups, state, menu ownership, and subscriptions compatible |
| Unknown embed content loads without host sanitization | Unsupported saved HTML can cross the editor boundary unsafely | Require the host sanitizer before storing or rendering unknown content |
| A link preview stores unsafe or unresolved URL data | A toolbar can open an unsafe URL, or automatic conversion replaces a useful plain link | Validate HTTP(S) URLs and preserve unresolved links as ordinary links |
| A slash or mention entry stays enabled after its action becomes unavailable | Committing the entry removes the query but performs no action | Check command availability before removing trigger text and again when committing |
| A source embed has no supported language or host renderer | The note shows a code block but loses its intended behavior | Keep language maps, host loaders, and page renderers aligned |
| A MIME type exists in only one language or theme map | Editing and rendered code use different language or color behavior | Keep CodeMirror, preview, Highlight.js, client MIME, and token maps aligned |
| A named CodeMirror theme is removed from the dependency or has the wrong variant | Theme selection falls back or applies a light surface to dark content | Keep theme IDs, lazy loaders, package dependencies, and variants in one map |
| A code preview parser times out but the fallback is not escaped | Large or malformed source can break the page markup | Stop highlighting at the parse limit and render the remaining source as escaped text |
| A language sync finishes after a newer configuration disables it | Highlight.js renders a language that the current settings removed | Serialize MIME sync operations and apply the latest enabled set |
| A log format changes without a matching highlighter rule | Requests, errors, or SQL lose their visual cues | Keep log shapes, continuation blocks, SQL parsing, and theme classes in sync |
| A delayed search check describes text that the user already changed | The editor shows an error for a newer query | Compare the checked query with the current document before publishing diagnostics |
| A text transformation joins normal typing or loses a multi-range selection | Undo restores the wrong unit or the user loses selected lines | Mark transformations as isolated edits and restore each range |
| A locale is filed under the catalog name instead of CKEditor’s lookup name | A translated editor silently falls back to English | Map each application locale to the language key CKEditor resolves |
| An equation form loses its target while the user edits | Save inserts or changes an equation at the wrong selection | Keep the editing target live until the form closes |
| A task state and its native checkbox state diverge | The task shows one status but saves another | Keep custom state definitions and checkbox post-fixing as one contract |
| A PDF annotation sidebar reads only the saved document | New or deleted annotations do not match what the user sees | Layer editor overrides and serializable unsaved entries over document annotations |
| Adjacent deleted PDF annotations are removed while iterating the same list | One deletion shifts past the loop and remains visible | Build a new remaining list instead of splicing the source list |
| A PDF attachment message forwards file bytes during metadata extraction | Loading a PDF exposes more data and wastes memory | Send only ID, filename, and size; read bytes on a same-origin download request |
| A PDF layer reader handles only direct order IDs | Nested or unordered layers disappear from the sidebar | Recursively flatten every supported order wrapper before filtering named groups |
| A PDF layer toggle uses a different optional-content config | The page does not redraw or the reported state is stale | Mutate the viewer-held config and announce that same object |
| A PDF message lacks note or load context | A split viewer updates or saves another PDF | Filter messages with the current note, frame load token, and same-origin check |
| A PDF save runs during an active annotation edit | The saved file omits the latest stroke or text change | Commit safe pending edits before serialization and request another save after pointer end |
| PDF navigation runs before initial view state or accepts an old request | The viewer returns to the old position or moves to the wrong heading | Wait for the initial view and let only the newest request move the current document |
| A protected PDF uses an unprotected digest, or vice versa | Heading and cached revision lookup fails | Include the protection form in digest and saved-revision keys |
| A stale Split.js instance survives a mode change | Old gutters and listeners control removed panes | Destroy the old split during cleanup |
| Sticky-header measurement and presentation use different table geometry | Header rows fail to stick, overlap content, or move past the table | Keep measured start and travel values compatible with the table CSS and dispose observers with the content |
| A heading or block link has different targets in content and navigation | Navigation fails or reaches the wrong content | Reuse one ordered target contract and reveal hidden tabs before scrolling |
| An optional share enhancement throws during startup | A published page loses unrelated presentation behavior | Start optional modules through isolated guarded calls |
| A shared note view replaces its fallback before its widget is ready | A slow module load leaves a blank published page | Keep fallback content until the view loads and leave it in place on failure |
| A late diagram render updates an unmounted share view | A stale async result replaces newer content or causes an update warning | Cancel the view's effect and ignore results that are no longer current |
| Mermaid cannot render after a theme change | The page keeps the prior diagram or shows an empty replacement | Keep the prior placeholder or drawing until the new render succeeds |
| A video or audio page loads its player or file before user action | A read-only page makes an unwanted third-party request or media load | Keep the media facade until the visitor activates playback |
| Structural HTML export drops direct text or blank lines | Raw HTML loses content or changes after reimport | Preserve significant text and encode blank lines in one raw-HTML block |
Key files
| File | Why to read it |
|---|---|
| packages/…/index.ts | Defines reusable rich-text editor profiles and the host boundary. |
| packages/…/plugins.ts | Shows shared capabilities and the GPL editor feature sets. |
| packages/…/styles.ts | Defines the ordered style contract shared by editing and read-only views. |
| packages/…/inline_widget_caret.ts | Shows how browser caret behavior is made stable around inline widgets. |
| packages/…/drag_out_of_editor.ts | Preserves model-owned moves when text leaves the editor. |
| packages/…/keep_drag_selection.ts | Keeps the browser selection stable during desktop Firefox drags. |
| packages/…/scroll_on_undo_redo.ts | Keeps the restored selection visible after undo and redo. |
| packages/…/drop_disallowed_attributes.ts | Keeps inserted model elements within the allowed schema. |
| packages/…/keep_view_mappings.ts | Keeps reused editor view elements attached to the correct DOM nodes. |
| packages/…/keep_balloon_positions.ts | Prevents widget toolbars from using unusable position targets. |
| packages/…/clipboard_plain_text_indent.ts | Bridges visual indentation across the plain-text clipboard. |
| packages/…/trilium_mention_ui.ts | Connects typed markers to host-owned completion lists. |
| packages/…/collapsible_headings_editing.ts | Defines saved heading sections and editor toggle behavior. |
| packages/…/collapsible_headings_read_only.ts | Defines heading collapse, keyboard access, and temporary reveal outside the editor. |
| packages/…/block_reference_editing.ts | Defines block identity, ranges, and linked-change reports. |
| packages/…/block_reference_read_only.ts | Defines read-only block, anchor, tab, and collapsed-section navigation. |
| packages/…/constants.ts | Defines the saved tab shape, alignment values, and cross-view class names. |
| packages/…/tabs_editing.ts | Defines tab editing, activation, repair, and reveal behavior. |
| packages/…/tabs_read_only.ts | Defines accessible tab presentation and fragment reveal outside the editor. |
| packages/…/content_embed.ts | Defines embedded identity, display modes, position, size, and host rendering. |
| packages/…/inline_source.ts | Defines source-backed embeds such as Mermaid and extended code blocks. |
| packages/…/media_embed.ts | Defines media players, saved link-preview data, thumbnails, and video shape. |
| packages/…/utils.ts | Defines shared editor event and model-change checks. |
| packages/…/index.ts | Defines source-editor behavior, host history, language loading, and runtime configuration. |
| packages/…/color_themes.ts | Defines named light and dark themes and their lazy loaders. |
| packages/…/preview_theme.ts | Bridges editor theme data into static code-preview CSS. |
| packages/…/syntax_highlighting.ts | Maps MIME types to on-demand source languages. |
| packages/…/block_markers.ts | Defines Markdown block-marker chips, identity rules, and jump feedback. |
| packages/…/trilium_search_lint.ts | Defines query diagnostics and safe fixes for search inputs. |
| packages/…/text_tools.ts | Defines selection-preserving text and line transformations. |
| packages/…/code_preview.ts | Defines static themed code previews and bounded parsing. |
| packages/…/index.ts | Defines rendered-code language loading, synchronization, and highlighting. |
| packages/…/gfm.ts | Defines rich HTML to Markdown extensions. |
| packages/…/serialize-structural-html.ts | Defines raw-HTML serialization for structures without Markdown syntax. |
| packages/…/bootstrap.ts | Shows the PDF viewer lifecycle, save boundary, and parent messages. |
| packages/…/annotations.ts | Defines saved, edited, and unsaved annotation state. |
| packages/…/attachments.ts | Defines attachment metadata messages and demand downloads. |
| packages/…/layers.ts | Defines layer discovery, recursive order handling, and visibility changes. |
| packages/…/pages.ts | Defines page reporting, parent page commands, and thumbnails. |
| packages/…/navigation.ts | Defines ordered page, heading, and annotation navigation. |
| packages/…/digest.ts | Defines protected and unprotected document identity. |
| packages/…/position.ts | Defines reading-position and page-rotation reporting. |
| packages/…/toc.ts | Defines PDF outline and table-of-contents requests. |
| apps/…/Pdf.tsx | Shows client PDF events and saves. |
| packages/…/split.js | Defines resizable-pane behavior. |
| apps/…/SplitEditor.tsx | Shows source-preview pane lifecycle. |
| packages/…/index.ts | Defines shared-page startup and guarded enhancements. |
| packages/…/note_view.tsx | Defines lazy read-only views that replace published fallbacks. |
| packages/…/in_page_links.ts | Defines in-page block and anchor navigation. |
| packages/…/content.css | Defines shared rich-content, media, code, embed, aside, and tab presentation. |
| packages/…/link_embed.css | Defines shared mention, card, audio, and video presentation. |
| packages/…/mermaid.ts | Defines asynchronous Mermaid rendering and theme changes on shared pages. |
| packages/…/page.ts | Defines page metadata, language, child links, navigation, and table-of-contents data. |
| packages/…/toc.ts | Defines table-of-contents navigation and heading links. |
packages/share-theme/src/templates/page.ejs | Defines page assembly, metadata, and navigation. |