Shared foundations
Shared foundations give Trilium applications common contracts and reusable tools for note data, content editing, rendering, and public presentation. They keep the meaning of content stable as it moves between hosts, editors, readers, import sources, model-assisted features, document viewers, and export formats.
Shared package roles
The shared packages form a common layer below application targets. Contract packages define shared meaning. Core services apply that meaning to product behavior. Browser packages edit, render, convert, and present the same content.
Common contracts
packages/…/index.ts is the public entry point for shared data shapes, note rules, host interfaces, content helpers, search types, task states, display rules, and shared Markdown behavior. These contracts give each application the same meaning for notes, attachments, branches, attributes, relations, MIME types, events, bootstrap data, scripting, fonts, presentation behavior, model-assisted chat, block targets, and document outlines.
The common rules keep content behavior aligned across packages:
- Note-type helpers define which content needs an image attachment and which renderer group presents it.
- Built-in attributes provide one vocabulary for system labels and relations.
- MIME definitions connect note content, code languages, Markdown names, file names, and syntax display.
- Block-reference contracts give headings and content blocks stable link targets. Block keys compare the same logical block in editor HTML and rendered Markdown without treating equal keys as equal content.
- Markdown indexing and source-edit rules map rendered blocks back to source lines. They let references add or replay markers while checking that other blocks keep their identity.
- Content embed rules describe how note and attachment references expand or become links. They also prevent recursive expansion from running forever and preserve unknown embed kinds for newer hosts.
- Markdown rules cover task states, callouts, highlights, tabs, wiki-links, transclusions, formulas, heading levels, and source markers. The same shared renderer can serve server and browser callers when each supplies its own sanitizer.
- Table-of-contents contracts normalize document headings and give them stable IDs. Format-specific data can add page positions, bookmarks, or other link details without changing the common heading shape.
- Option and locale contracts separate shared settings from device-only settings and keep language, content direction, editor hints, fonts, AI settings, and presentation behavior consistent.
- Desktop host contracts expose native services through one renderer-facing boundary rather than direct Electron access. The boundary is absent in browser and standalone hosts.
- Search and reference contracts carry structured match and in-note target information. Clients can show exact, regular-expression, and approximate matches, then jump to headings, anchors, blocks, or document headings without rebuilding server results.
- LLM contracts carry plain and multimodal messages, provider identity, model information, citations, usage, tool approval, and streaming state between clients and core services.
- Save and revision contracts carry the content version, note format, attachment versions, and draft form that a client used. This lets a host refuse stale edits or keep an unsaved whole note or block range as a revision.
References: packages/…/index.ts• L18-68 packages/…/block_keys.ts• L3-23 packages/…/markdown_block_index.ts• L19-70 packages/…/markdown_references.ts• L15-43 packages/…/toc.ts• L4-45 packages/…/content_embeds.ts• L4-129 packages/…/llm_api.ts• L6-133 packages/…/options_interface.ts• L62-112 packages/…/server_api.ts• L471-552
Core domain services
packages/trilium-core applies the shared contracts to note and application behavior. A host supplies services for storage, encryption, requests, archives, images, backups, setup, messaging, and other runtime needs. Core then provides common rules for notes, attachments, search, synchronization, imports, exports, scripting, AI features, references, document outlines, and shared pages.
This separation keeps product behavior stable while hosts choose how they provide runtime services. Core also joins content conversion, code display, image handling, public rendering, archive creation, document-outline caching, and API routing into one domain layer. Its API and share paths apply the same data, safety, and access rules before content reaches an application or reader.
Core treats Markdown as a content boundary rather than a plain text dump. Import and export preserve note structure such as task states, callouts, collapsible blocks, tables, tabs, columns, formulas, link previews, icons, block references, and embedded content when the format can carry it. Unsupported shapes remain safe HTML or a clear error instead of silently becoming incomplete notes.
Core also exposes reusable APIs for in-note references and block editing. A reference provider identifies targets that a note or attachment type can expose. Text and Markdown notes provide headings and anchors, while document types use cached tables of contents for headings, pages, and bookmarks. The same route layer lets clients read a block range, replace it, create a stable heading reference, or obtain links into a supported document.
Core manages version-safe saves and recovery. A save can name the note version and attachment versions it used, a stale save can be refused, and a user can keep the other version as a revision. Drafts can hold a whole note or an edited block range, so work that cannot be merged is still recoverable in the format in which it was written.
Core keeps external pictures and inline preview pictures under note ownership when the relevant option allows it. It rewrites source links to local attachments and lets callers wait for the one write they need without waiting for unrelated imports. This makes pasted and imported content less dependent on remote URLs.
Core imports folders, Markdown, and Trilium archives into the same note tree. Archive IDs and internal links are remapped together, safe imports limit relations that can point outside the archive, and source order remains stable when a target uses a reverse insertion rule.
Document outlines use the source blob as their version boundary. Core reuses a valid cache, builds one when the host can read the format, or asks a capable viewer to build it when the host cannot. A cache is accepted only when its reader rules and target blob still match the document, so heading links do not silently point into a newer file.
References: packages/…/index.ts• L22-80 packages/…/notes.ts• L108-187 packages/…/revisions.ts• L189-319 packages/…/toc.ts• L10-61 packages/…/notes.ts• L1190-1270 packages/…/image.ts• L20-93 packages/…/image_download.ts• L86-180 packages/…/zip.ts• L81-145 packages/…/zip.ts• L881-1045 packages/…/context.ts• L37-125 packages/…/index.ts• L23-85
Model-assisted content
Core gives applications one model-assisted content flow across hosted providers, local model servers, and web search services. Clients can send text, images, files, and text attachments by using shared message parts. Core resolves note attachments, builds the model context, supplies optional note and web tools, and returns structured stream events that the client can render or ask the user to approve.
Provider configuration is part of the shared application contract rather than a client-only concern. The model list can come from a live provider while pricing and context data remain available as shared metadata. Local providers use the same chat contract as hosted providers, and the request boundary keeps provider endpoint access under the host's network policy.
The chat flow is asynchronous at the route boundary. A client starts a stream with its own identifier, receives text, reasoning, tool, citation, usage, error, and completion events over the host's supported channel, and can abort the stream or answer a pending tool approval by that identifier.
References: packages/…/llm_api.ts• L15-60 packages/…/llm_api.ts• L156-227 packages/…/llm.ts• L37-189 packages/…/base_provider.ts• L98-144 packages/…/local.ts• L70-155 packages/…/model_prices.json• L1-20
Embedded editor
The CKEditor package gives rich text one authoring model across full editors, compact inputs, and content embedded inside a note. Its configured surfaces support formatting, internal links, note and attachment references, files, images, code, tables, task states, tabs, columns, diagrams, math, collapsible blocks, callouts, side content, snippets, AI actions, Markdown import, and optional Vim-style key control.
The editor separates document meaning from the host surface. Fixed, floating, mobile, compact, chat, memo, and nested surfaces select different capability groups while sharing the same commands and saved content rules. Chat and memo inputs can stay lightweight without changing the full note editor. Host callbacks provide application services such as note selection, link dialogs, icon pickers, child-note creation, attachment upload, embedded content, and tab links without changing the editor's content model.
Hidden sections and richer task states are shared content behavior. Collapsible headings save their state while hidden blocks remain part of the document. Search, jumps, caret movement, deletion, and block moves can reveal or move the complete section without losing its structure. Todo items can use configured states beyond the native unchecked and done states. Unknown states remain preserved so content survives a later configuration change.
Tabs are one shared content shape in the editor and in read-only views. The saved form contains every title and panel, while the active tab is view state. Selection, find results, fragments, and block jumps reveal the tab that contains the target. Outside the editor, titles become a scrollable and keyboard-accessible bar with the same nested reveal behavior.
The editor also keeps host behavior stable at common browser boundaries. Text can move from an editor into another editable field without losing the model state. Contextual toolbars stay hidden when their editor is not visible. Inline widgets remain reachable with vertical caret movement. Undo and redo return the caret to view, and desktop Firefox keeps a dragged selection from jumping after a widget is selected. Stored level-one headings remain valid content while the note title keeps its role as the top heading. Mention lists use host-provided feeds and do not change the document when a user dismisses a suggestion.
References: packages/…/index.ts• L98-180 packages/…/plugins.ts• L114-195 packages/…/plugins.ts• L216-282 packages/…/keep_drag_selection.ts• L11-35 packages/…/scroll_on_undo_redo.ts• L3-18 packages/…/constants.ts• L1-39 packages/…/tabs_editing.ts• L31-79 packages/…/tabs_read_only.ts• L17-109 packages/…/trilium_mention_ui.ts• L48-75
Rendering and conversion
Rendering and conversion turn stored content into editable content, readable views, portable output, or public pages. Markdown, rich text, code, spreadsheets, attachments, diagrams, tabs, link previews, embedded notes, and document previews pass through shared rules so editing, preview, sharing, import, and export preserve the same meaning.
The Markdown boundary is designed for round trips. Structures that plain Markdown cannot express directly remain safe HTML when needed. Task states, links, previews, icons, tabs, collapsible blocks, columns, highlights, formulas, tables, callouts, block markers, and embedded content can therefore move between Trilium and another Markdown system without silently becoming plain text. Heading conversion keeps the note title separate while preserving the author's heading levels. Supported Obsidian callout names map to the same shared callout shapes. The block index reads the same rendered shape that a caller uses and maps blocks, anchors, markers, source lines, and writable edits together.
Markdown references are placed only when a new source still renders the intended block and leaves other blocks unchanged. This protects heading links and block IDs across editor saves, imports, exports, and later source edits. CodeMirror presents source markers as atomic chips, protects them from partial edits, and tracks changes for callers that need to rebase source positions.
CodeMirror provides a reusable code surface for language-aware editing and preview. It can switch MIME languages, line wrapping, line numbers, indentation, Vim controls, read-only state, search, completion sources, and shared history without replacing the view. A catalog of light and dark themes is loaded on demand. Preview CSS uses the same token and color information, so a code note and its read-only view can use the selected theme.
Code display follows the common MIME vocabulary. Read-only pages use the matching Highlight.js language when available and fall back to escaped code when it is not. Code previews can highlight the part of a large file that the parser can safely process, while the rest stays readable plain text.
HTML export uses the same stored content but gives block structure stable line breaks. Single-note HTML export inlines image and attachment data so the result stands alone. Archive exports add note pages, navigation, search data, styles, scripts, and the share theme around the rendered content. Editor-only list identity data is removed from exported text while the content structure remains.
Document preview conversion also feeds the shared table-of-contents system. PDF, Office, and EPUB readers expose normalized headings and format-specific destinations. The preview can carry the same heading IDs that reference lists use, so a link selected from a document outline reaches the matching place in the rendered document.
References: packages/…/markdown_renderer.ts• L158-205 packages/…/markdown_renderer.ts• L217-279 packages/…/markdown_renderer.ts• L529-705 packages/…/markdown_block_index.ts• L73-173 packages/…/markdown_references.ts• L45-185 packages/…/index.ts• L76-98 packages/…/index.ts• L385-475 packages/…/color_themes.ts• L3-10 packages/…/preview_theme.spec.ts• L9-60 packages/…/office.ts• L67-110 packages/…/epub.ts• L14-30 packages/…/content_renderer.ts• L570-605 packages/…/markdown.ts• L56-120
Public presentation
The share-theme package turns shared notes into public reading pages and static HTML exports. It combines layout, navigation, search, metadata, themes, child links, table of contents, content enhancement, code copying, diagrams, math, tabs, tables, link previews, and app views around rendered note content.
Core prepares the note content and page data before the theme renders it. The page data supplies safe links, navigation state, metadata, languages, child-page previews, and heading data. Browser behavior then enhances the page with navigation, in-page block jumps, hidden-section reveal, code actions, link previews, diagrams, type-specific views, tab activation, and read-only content behavior.
The public data boundary includes only visible notes, branches, attributes, and links. It can add the built-in templates needed by a view without exposing protected notes or share credentials. Collection views, navigation, child links, previous and next links, and static pages therefore draw from the same note relationships while access decisions stay in the data assembly step.
The theme shares content styles with the editor. Embedded notes, link previews, expandable content, tables, task states, callouts, side content, tabs, block jumps, and narrow-screen layouts therefore keep the saved size and position rules when they move from an editable note to a live page or an archive. A page heading receives a safe anchor and table-of-contents entry, while a block or fragment link reveals hidden containers before it scrolls.
References: packages/…/index.ts• L1-47 packages/…/page.ts• L112-165 packages/…/in_page_links.ts• L5-55 packages/…/content.css• L1-19 packages/…/handlers.ts• L67-195 packages/…/handlers.ts• L263-287 packages/…/snote.ts• L72-155 packages/…/content_renderer.ts• L266-431
Pane layout
The split layout package provides a small reusable capability for resizable panes. Hosts use it for note trees, content panes, sidebars, and other multi-pane surfaces while keeping placement and visual style in the host shell.
References: packages/…/package.json• L1-26
Content lifecycle
Shared foundations support a lifecycle from source data to authoring, reading, model-assisted work, document navigation, and export. A note or imported source enters through shared contracts, uses the content surface for its type, and leaves through a rendered page, an application view, a model response, a document target, or a portable format.
When a host processes content, the main hand-offs are:
- Shared contracts identify the note, its content type, its relations, its references, its outline, and its available resources.
- Core services load or change the note and apply access, safety, cache, and product rules.
- An editor, viewer, or model-assisted feature presents or transforms the content and returns the shared content shape.
- Rendering and conversion produce a read-only view, a public page, a document preview, or an export.
- The next application or reader consumes the same note, relation, reference, and outline rules.
This diagram shows how common contracts connect import and authoring to display, model-assisted work, document navigation, and export.
flowchart LR
Source[Note or imported source] --> Contracts[Shared contracts]
Contracts --> Core[Core domain behavior]
Core --> Editor[Editor or viewer]
Editor --> Content[Stored content]
Content --> Render[Rendering and conversion]
Render --> Read[Read-only or public page]
Render --> Export[Markdown, HTML, or archive output]
Contracts --> AI[Model-assisted feature]
AI --> Content
Contracts --> Outline[Document outline and targets]
Outline --> Read
Contracts --> Host[Desktop, web, standalone, or server host]
Host --> Editor
Cross-package contracts
The key shared contract is the content hand-off. Editors, renderers, importers, exporters, scripts, reference providers, document readers, and model-assisted features may hold temporary state. When they cross a package or runtime boundary, they return the agreed content, metadata, event, relation, resource, reference, outline, or platform shape.
Sanitization and access checks are part of this boundary. Imported content, authored HTML, model output, embedded notes, link previews, document previews, and public pages must not bypass the rules that protect stored content and shared readers. Import and export also preserve IDs and references so notes, attachments, relations, headings, anchors, blocks, rendered images, and document destinations continue to point to the right entities after a transfer.
Search adds a second cross-package contract: the server returns result order, query errors, and match details in a form that clients can use for snippets and jumps. Approximate matches remain marked as approximate instead of appearing as exact matches. Reference APIs add the same kind of stable target contract inside a note or document. Bootstrap data carries the settings, theme, font, and host state that a client needs for its first view.
Document outline readers add a cache contract. A heading ID is meaningful only with the outline's source blob, reader version, protection state, and format-specific destination data. Viewers must report the blob they read, and core must reject or rebuild results when the document changes.
Model-assisted work adds a long-lived stream contract. The client must match every event to its stream identifier, keep tool approval tied to the requested call, and receive a terminal event even when the provider fails or the user aborts the turn. Provider endpoints remain behind the host request policy rather than becoming browser-controlled network access.
References: packages/…/server_api.ts• L337-552 packages/…/llm_api.ts• L272-308 packages/…/content_embeds.ts• L47-129 packages/…/markdown_block_index.ts• L57-70 packages/…/toc.ts• L106-166 packages/…/notes.ts• L375-453 packages/…/revisions.ts• L239-319 packages/…/toc.ts• L10-61 packages/…/zip.ts• L174-183 packages/…/sanitizer.ts• L1-80 packages/…/handlers.ts• L584-668
Related pages
- Core domain and common contracts explains the shared note model, metadata, API, event, script, desktop, standalone, AI, resource, transcript, and attribute contracts.
- Editing, rendering, and presentation packages explains the reusable editors, content conversion, code display, themes, and layout behavior.
Change checklist
When these files or sections are changed, remember to consider these:
- A shared data, event, host, editor, reference, outline, save, revision, or stream configuration shape must stay aligned between its producers, consumers, caches, and host-facing views.
- A note type, built-in attribute, task state, MIME type, locale, font option, AI option, or text rule change must stay aligned between storage, type checks, runtime recognition, editors, import, export, search, and public rendering.
- A block-reference or Markdown-source change must preserve block keys, marker placement, source lines, single-block and range links, URI encoding, nested selection, list numbering, column and aside behavior, API extraction, CodeMirror editing, and editor movement.
- A document-outline change must keep normalized titles, heading IDs, depth limits, reader versions, blob checks, cache fields, format destinations, preview markers, client-built caches, and reference listings aligned.
- A content embed, link preview, callout, aside, or positioned widget change must preserve its saved attributes, copy and paste behavior, read-only rendering, host callbacks, access checks, cycle protection, and export fallback.
- A collapsible section, hidden-block, tab, or inline-widget change must preserve saved state, section boundaries, search and jump reveal behavior, caret movement, deletion, drag range, keyboard navigation, and read-only controls.
- A save, revision, or draft change must keep note version checks, attachment version checks, block-range hashes, format changes, restore behavior, and revision limits aligned.
- A custom task-state change must keep configured states, native checkbox anchors, unknown-state preservation, editor conversion, Markdown markers, tooltips, and exported labels aligned.
- A code language or theme change must keep the commons MIME mapping, CodeMirror, Highlight.js, CKEditor code blocks, Markdown fences, code previews, and public previews in agreement.
- A Markdown, HTML, or external-import rule change must be checked across import, editor content, read-only rendering, shared pages, document previews, and export so structure, headings, attributes, markers, and links survive the next round trip.
- A shared-page change must keep page data, templates, browser setup, styles, static exports, in-page navigation, type-specific views, document links, and public route access rules aligned.
- An option change must keep its type, default, sync scope, readable or write-only API behavior, bootstrap data, and every editor or presentation consumer aligned.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A common contract changes on one side only | A host can misread state or lose part of a result | Treat commons types as the boundary and update all producers and consumers together |
| A Markdown block key or source marker is mapped with a different rendered shape | A reference can move to the wrong block or a source edit can damage another block | Index source with the same renderer and sanitizer that the reader uses |
| A save uses a stale note or attachment version | A newer edit can be overwritten or a user can lose the reason for a conflict | Send the base version and keep the other version as a revision when the user chooses it |
| A document outline cache has the wrong blob or reader version | A heading link can open the wrong place or disappear from the reference list | Validate the target blob and reader properties before reuse |
| A collapsed section or tab is moved without its hidden content | A later jump can reveal the wrong target or content can be left behind | Use the shared range and reveal rules for selection, drag, delete, and move actions |
| A new editor feature has no read-only or export form | Public pages and exports lose content or show raw editor data | Add the saved fallback and pair editor conversion with read-only and export conversion |
| A MIME mapping exists in only one editor or renderer | Code loses its language or falls back to the wrong display | Keep commons, CodeMirror, Highlight.js, CKEditor, Markdown, code previews, and share preview mappings aligned |
| An imported relation points outside a safe archive | Imported content can gain unwanted inherited behavior | Limit outside targets to approved system notes during safe import |
| An image write finishes after its note or attachment is deleted | A late result can fail noisily or recreate stale content | Track pending writes and re-check the entity before storing the result |
| A remote image URL is fetched without scheme and option checks | The host can read an unsafe address or make an unwanted request | Allow only HTTP(S) and require the image-download setting |
| An embed expands through a cycle or bypasses access checks | A page can loop or disclose a protected note | Track the current embed path and apply the caller's access decision at each embedded note |
| A model stream has no terminal event or reuses a live stream ID | The client can wait forever or attach events to the wrong chat | Reserve IDs while active and always broadcast an end event after success, abort, or error |
| A provider base URL bypasses the host request policy | A server may send credentials or content to an unsafe destination | Route provider calls through the host fetch boundary |
| Static and live share paths use different content rules | A public page and its archive show different content or navigation | Keep nested expansion, link rewriting, metadata, styles, scripts, and access rules shared |
Key files
| File | Why to read it |
|---|---|
| packages/…/index.ts | Shows the public common contract surface. |
| packages/…/notes.ts | Shows shared note-type, MIME, icon, and renderer-group rules. |
| packages/…/block_reference.ts | Defines stable block targets and logical block-range behavior. |
| packages/…/markdown_renderer.ts | Shows the common Markdown-to-editor HTML boundary. |
| packages/…/toc.ts | Defines shared document heading data and stable IDs. |
| packages/…/server_api.ts | Defines save, revision, bootstrap, reference, and search data sent to clients. |
| packages/…/options_interface.ts | Defines shared option names, types, and settings scope. |
| packages/…/notes.ts | Shows note creation, content saves, attachment ownership, and link processing. |
| packages/…/notes.ts | Shows note data, block editing, and in-note reference routes. |
| packages/…/revisions.ts | Shows revision restore, excess cleanup, and unsaved draft recovery. |
| packages/…/zip.ts | Shows archive import, ID remapping, safe relations, and source-order handling. |
| packages/…/image_download.ts | Shows how remote and inline pictures become local attachments. |
| packages/…/context.ts | Shows request-scoped state and delayed work boundaries. |
| packages/…/handlers.ts | Shows public route access, protected-content checks, and media delivery. |
| packages/…/snote.ts | Shows the public note model and visible-tree rules. |
| packages/…/index.ts | Defines the supported rich-text editor surfaces and host-facing editor types. |
| packages/…/plugins.ts | Shows the capability groups used by each editor mode. |
| packages/…/tabs_editing.ts | Defines saved tabs, active-tab behavior, and target reveal. |
| packages/…/tabs_read_only.ts | Defines read-only tab activation, keyboard control, and fragment reveal. |
| packages/…/keep_drag_selection.ts | Defines stable selection behavior during desktop Firefox drags. |
| packages/…/scroll_on_undo_redo.ts | Defines caret visibility after editor history actions. |
| packages/…/index.ts | Defines the reusable code editor and its configurable capabilities. |
| packages/…/color_themes.ts | Defines the shared light and dark code-theme catalog. |
| packages/…/preview_theme.ts | Defines how editor themes become read-only preview CSS. |
| packages/…/index.ts | Shows the public page enhancement lifecycle. |
| packages/…/page.ts | Defines public page metadata, navigation, child links, and table-of-contents data. |
| packages/…/content.css | Shows how shared content styles preserve editor layout in public pages. |
| packages/…/package.json | Identifies the reusable resizable-pane capability. |