A framework-agnostic Markdown editor for web apps with split code/preview UX, runtime API, extensible toolbar actions, markdown-it parsing, and source-line synchronization.
This document is for developers integrating the editor into their own application. It is not an end-user guide for writing Markdown.
- Getting Started
- Supported Code Block Languages
- Embedding the Editor on a Page
- Configuration Options
- Runtime API
- Events and Callback Usage
- Built-in Plugins and Features
- Extending Functionality (Custom Toolbar Buttons)
- Versioned API Changes
- Markdown Compatibility Notes
- Security Notes
- License
- Development Commands
- Troubleshooting
- Modern browser with ES module support.
- A container element with explicit height (important for CodeMirror layout).
- Optional globals for enhanced preview:
window.mermaidfor Mermaid rendering.- KaTeX CSS for math rendering visuals.
- Fenced code blocks with an explicit language, for example
javascript, are syntax-highlighted in preview.
npm installnpm run buildBuild output is written to dist/:
dist/smart-editor.esm.jsdist/smart-editor.cjs.jsdist/smart-editor.iife.js
Syntax highlighting in preview is enabled for fenced code blocks with explicit language names, for example:
```javascript
console.log('hello');
```Supported language labels:
bashccppdiffdjangodockerfileexcelgraphqlhandlebarshttpjavajavascriptjsonkotlinlispluamakefilemarkdownmathematicamatlabnginxobjectivecperlphpplaintextpowershellpythonrubysqlscalashellswifttypescriptxml
Common aliases are accepted (for example js, ts, html, sh, ps1, gql, md, objc).
Special fallback:
curlis mapped tobashhighlighting.
<div id="editor" style="height: 600px;"></div>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.21/dist/katex.min.css">
<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
<script>
mermaid.initialize({ startOnLoad: false });
</script>
<script type="module">
import { createEditor } from './dist/smart-editor.esm.js';
const editor = createEditor('#editor', {
value: '# Hello',
mode: 'split',
onChange: (markdown, tokens, html) => {
console.log(markdown.length, tokens.length);
},
});
window.editor = editor;
</script>Importing the library registers the custom element as a side effect.
<smart-editor id="mde" mode="split" theme="auto" style="height: 600px;"></smart-editor>
<script type="module">
import './dist/smart-editor.esm.js';
const el = document.getElementById('mde');
el.setMarkdown('# Initial content');
el.addEventListener('se-change', (e) => {
console.log(e.detail.markdown);
});
</script>createEditor(element, options) and new EditorCore(element, options) use the same options schema.
| Option | Type | Default | Description |
|---|---|---|---|
value |
string |
'' |
Initial markdown content. |
mode |
'split' | 'code' | 'preview' | 'wysiwyg' |
'split' |
Initial view mode (wysiwyg is preview-first beta mode). |
scrollSync |
boolean |
true |
In split mode, synchronizes vertical scrolling between code and preview using smooth animated follow. |
theme |
'auto' | 'light' | 'dark' | 'sepia' | 'midnight' | 'solarized' | 'nord' | 'high-contrast' |
'auto' |
Theme id applied to the editor root. auto follows the OS color scheme; the built-in presets can also be switched at runtime. |
markdown.options |
object |
{} |
Options passed to markdown-it. |
markdown.plugins |
Array |
[] |
Extra markdown-it plugins: [[pluginFn, pluginOpts?], ...]. |
upload.endpoint |
string |
undefined |
Default upload endpoint (POST multipart/form-data) used for all file types with no matching entry in upload.endpoints. Images fall back to base64 when omitted or on error; non-image files require an endpoint and are rejected without one. |
upload.endpoints |
Object.<string,string> |
undefined |
Per-type endpoint overrides. Keys can be a MIME type (image/png), a wildcard (image/*), or a file extension (.pdf). The first matching entry wins; unmatched files fall back to upload.endpoint. Example: { 'image/*': '/upload/image', 'application/pdf': '/upload/raw' } |
upload.headers |
object |
{} |
Extra HTTP headers for upload requests (e.g. Authorization). |
upload.extraFields |
object |
{} |
Extra FormData fields appended to every upload (e.g. { upload_preset: 'my_preset' } for Cloudinary unsigned upload). |
upload.responseUrlField |
string |
'url' |
JSON field in the upload response that holds the asset URL (e.g. 'secure_url' for Cloudinary). |
upload.maxSize |
number |
5 * 1024 * 1024 |
Max image size in bytes. |
upload.fileMaxSize |
number |
upload.maxSize |
Max non-image file size in bytes. |
upload.formats |
string[] |
common image MIME list | Allowed image MIME types. |
upload.fileFormats |
string[] |
undefined |
Allowed non-image MIME types/extensions (for example application/pdf, .docx). If omitted, non-image files are accepted. |
upload.pickerAccept |
string |
*/* |
Value for file-picker accept attribute. |
drawio.url |
string |
https://embed.diagrams.net/?embed=1&proto=json&spin=1&ui=min&libraries=1 |
draw.io embed URL used by modal. Set your own URL for self-hosted/offline mode. |
drawio.allowHostedFallback |
boolean |
true |
When true, editor retries with https://embed.diagrams.net if local/self-hosted draw.io fails to initialize. Set to false for strict offline mode. |
toolbar |
object |
undefined |
Declarative toolbar layout: visible items, grouping, ordering, display mode, and dropdown menus. |
busy.showDelay |
number |
140 |
Delay (ms) before showing loading overlay (anti-flicker for very fast tasks). |
busy.minVisible |
number |
180 |
Minimum overlay visibility time (ms) once shown, to avoid flashing. |
busy.texts.defaultLabel |
string |
'Working...' |
Default busy label used when task does not provide one. |
busy.texts.cancel |
string |
'Cancel' |
Cancel button label in the loading overlay. |
compatibility.enabled |
boolean |
false |
Enables publishing-compatibility validation and suggested fixes. |
compatibility.showPanel |
boolean |
false (auto true when enabled) |
Shows built-in compatibility status panel above editor panes. |
compatibility.debounce |
number |
500 |
Validation debounce in milliseconds while typing. |
compatibility.showPreviewUsingProfile |
boolean |
false |
When enabled, preview uses HTML generated by the compatibility profile. |
compatibility.markdownIt |
object |
Eleventy-like defaults | markdown-it options for the built-in Eleventy compatibility profile. |
compatibility.plugins |
Array |
[] |
Extra markdown-it plugins for compatibility profile, e.g. [[markdownItAnchor, opts]]. |
compatibility.disableRules |
string[] |
['emphasis'] |
markdown-it rules disabled by the built-in Eleventy compatibility profile. |
compatibility.profile |
object |
Eleventy markdown-it profile | Custom profile implementing render(markdown) => { html, tokens? }. |
compatibility.rules |
Array |
built-in table rule | Validation/fix rules used by compatibility service. |
onChange |
function |
undefined |
Called with (markdown, tokens, html). |
onSelectionChange |
function |
undefined |
Called with current selection object. |
onPaste |
function |
undefined |
Native paste event hook. |
onUploadStart |
function |
undefined |
Called with (file). |
onUploadDone |
function |
undefined |
Called with (file, urlOrBase64). |
onUploadError |
function |
undefined |
Called with (file, error). |
onPreviewClick |
function |
undefined |
Called with (element, { from, to }). |
onCommand |
function |
undefined |
Called before runCommand(id, args). |
onCompatibilityReport |
function |
undefined |
Called with latest compatibility report object. |
onCompatibilityStatusChange |
function |
undefined |
Called with (status, report) on status transitions. |
onCompatibilityFixApplied |
function |
undefined |
Called after user accepts compatibility fix proposal. |
onBusyChange |
function |
undefined |
Called with busy overlay state { busy, count, label, detail, scope, locked, canCancel, cancelToken }. |
Use this setup when your production publishing pipeline is Eleventy and you want editor preview/validation to match it as closely as possible.
import { createEditor, createEleventyCompatibilityProfile } from 'smart-md-editor';
import markdownItAnchor from 'markdown-it-anchor';
import markdownItCollapsible from 'markdown-it-collapsible';
const profile = createEleventyCompatibilityProfile({
markdownIt: {
html: true,
breaks: true,
linkify: true,
},
disableRules: ['emphasis'],
plugins: [
[markdownItAnchor, {
permalink: true,
permalinkSymbol: '',
permalinkBefore: false,
}],
[markdownItCollapsible, {}],
],
});
const editor = createEditor('#editor', {
compatibility: {
enabled: true,
showPanel: true,
profile,
},
});Notes:
- Keep Eleventy and editor markdown-it options/plugins aligned.
- The compatibility panel supports per-issue jump + fix and batch fix flow.
- Built-in table diagnostics include:
table.missing-leading-pipe,table.missing-trailing-pipe,table.column-count-mismatch,table.invalid-separator-row.
const editor = createEditor('#editor', {
value: '# Content',
scrollSync: true,
busy: {
showDelay: 160,
minVisible: 220,
texts: {
defaultLabel: 'Przetwarzanie...',
cancel: 'Anuluj',
},
},
upload: {
// Option A: custom backend
endpoint: '/api/upload',
headers: { Authorization: `Bearer ${token}` },
maxSize: 8 * 1024 * 1024,
formats: ['image/png', 'image/jpeg', 'image/webp'],
fileFormats: [
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
],
pickerAccept: 'image/*,.pdf,.doc,.docx,.xls,.xlsx',
// Option B: Cloudinary unsigned direct upload (no backend needed)
// endpoint: 'https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/image/upload',
// extraFields: { upload_preset: 'YOUR_UPLOAD_PRESET' },
// responseUrlField: 'secure_url',
// maxSize: 10 * 1024 * 1024,
},
markdown: {
options: { html: true, linkify: true, typographer: true },
plugins: [
[someMarkdownItPlugin, { someOption: true }],
],
},
});const editor = createEditor('#editor', {
theme: 'sepia',
});
editor.setTheme('midnight');
console.log(editor.getAvailableThemes());Built-in presets:
light: neutral bright UIdark: neutral dark UIsepia: warm reading theme for long-form writingmidnight: cool dark coding theme with stronger contrastsolarized: classic balanced palette inspired by Solarizednord: cool arctic dark palettehigh-contrast: accessibility-focused very high contrast variant
Returned editor instance (or <smart-editor> proxies) provides:
| Method | Signature | Description |
|---|---|---|
getMarkdown |
() => string |
Get current markdown string. |
setMarkdown |
(markdown, opts?) |
Replace full document. opts.undoable=false skips undo history entry. Use opts.preservePreviewScroll=true in toolbar/programmatic full-document rewrites to keep preview stable during render. |
getTokens |
() => object[] |
Get markdown-it token array for current markdown. |
getPreview |
() => string |
Get sanitized preview HTML. |
getSelection |
() => { from, to, text, lineFrom, lineTo } |
Current selection info (line* are 0-based). |
setSelection |
(from, to) |
Set selection by character offsets. |
insertText |
(text, position?) |
Insert text at cursor or explicit offset. |
replaceSelection |
(text) |
Replace current selection. |
undo |
() |
Undo in code editor. |
redo |
() |
Redo in code editor. |
focus |
() |
Focus code editor. |
setMode |
(mode) |
Switch mode: split, code, preview, wysiwyg. |
getMode |
() => mode |
Read current mode. |
setTheme |
(theme) => string |
Switch theme to auto or one of the registered built-in theme ids. |
getTheme |
() => string |
Read current theme id. |
getAvailableThemes |
() => { id, label, description, scheme }[] |
List built-in theme metadata for selectors/settings UIs. |
isBusy |
() => boolean |
Returns whether any tracked async task is currently active. |
getBusyState |
() => object |
Returns current busy state snapshot. |
beginBusyTask |
(opts?) => string |
Start a manual busy task and return its token. |
updateBusyTask |
(token, patch) => void |
Update message/details for a running busy task. |
endBusyTask |
(token) => void |
End a previously started busy task. |
cancelBusyTask |
(token?) => void |
Cancel one busy task by token, or all when omitted. |
runWithBusy |
(task, opts?) => Promise<any> |
Wrap an async task with loading overlay, lock, and optional cancellation signal. |
registerAction |
(actionDef) |
Register custom toolbar action. |
unregisterAction |
(id) |
Remove custom toolbar action. |
getToolbarConfig |
() => object | null |
Get the current declarative toolbar config, if one is active. |
setToolbarConfig |
(config) => void |
Replace the toolbar layout at runtime. |
updateToolbarConfig |
(mutator) => object |
Mutate current toolbar config via callback and apply it. |
upsertToolbarGroup |
(group) => object |
Add or replace one toolbar group by id. |
removeToolbarGroup |
(groupId) => object |
Remove one toolbar group by id. |
upsertToolbarItem |
(groupId, item, position?) => object |
Add or replace one top-level group item. |
removeToolbarItem |
(groupId, itemId) => object |
Remove one top-level group item by id. |
upsertDropdownItem |
(groupId, dropdownId, item, position?) => object |
Add or replace one dropdown entry. |
removeDropdownItem |
(groupId, dropdownId, itemId) => object |
Remove one dropdown entry by id. |
runCommand |
(id, args?) |
Run action by id programmatically. |
openDrawioEditor |
(opts?) => Promise<boolean> |
Open draw.io modal and insert/update {xml} block line. |
proposeChange |
(newMarkdown, opts?) => Promise<boolean> |
Open diff modal and apply if accepted. Supports opts.mode: replace-all, replace-selection, insert-at-cursor. |
getCompatibilityReport |
() => object |
Get latest compatibility report (disabled, valid, warning, invalid). |
getCompatibilityStatus |
() => 'disabled' | 'valid' | 'warning' | 'invalid' |
Get current compatibility status. |
isCompatibilityEnabled |
() => boolean |
Check whether compatibility mode is active. |
setCompatibilityEnabled |
(enabled) => object |
Enable/disable compatibility mode and return latest report. |
setCompatibilityProfile |
(profile) => object |
Replace compatibility profile and revalidate when enabled. |
validateCompatibility |
(opts?) => object |
Run compatibility validation manually. |
proposeCompatibilityFix |
(issueId) => Promise<boolean> |
Propose/apply one issue fix through diff modal. |
proposeAllCompatibilityFixes |
() => Promise<boolean> |
Propose/apply one combined fix for all fixable issues. |
destroy |
() |
Dispose editor instance and listeners. |
const accepted = await editor.proposeChange('# Suggested update\n\nGenerated text...');
if (accepted) {
console.log('Applied');
}await editor.runWithBusy(async ({ signal, update }) => {
update({ label: 'Downloading template...', detail: 'Template: weekly-report' });
const response = await fetch('/api/templates/weekly-report', { signal });
const markdown = await response.text();
editor.replaceSelection(markdown);
}, {
label: 'Downloading template...',
detail: 'Template: weekly-report',
lock: true,
cancellable: true,
});await editor.proposeChange('# Full replacement', { mode: 'replace-all' });
await editor.proposeChange('only this part', { mode: 'replace-selection' });
await editor.proposeChange(' inserted chunk ', { mode: 'insert-at-cursor' });replace-selectionfalls back toinsert-at-cursorwhen no text is selected.- In
insert-at-cursor, insertion happens at the end of the current selection/cursor (selection.to).
import { EDITOR_THEME_PRESETS, getEditorThemeList } from 'smart-md-editor';
console.log(Object.keys(EDITOR_THEME_PRESETS));
console.log(getEditorThemeList());If you want to add another built-in theme in the source tree, define its token set in src/styles/themes.js; the editor stylesheet consumes that registry automatically.
const editor = createEditor('#editor', {
compatibility: {
enabled: true,
},
onCompatibilityStatusChange(status, report) {
console.log(status, report.summary);
},
});
const report = editor.validateCompatibility();
if (report.issues[0]?.fixable) {
await editor.proposeCompatibilityFix(report.issues[0].id);
}import markdownItAnchor from 'markdown-it-anchor';
import markdownItCollapsible from 'markdown-it-collapsible';
const editor = createEditor('#editor', {
compatibility: {
enabled: true,
markdownIt: {
html: true,
breaks: true,
linkify: true,
},
disableRules: ['emphasis'],
plugins: [
[markdownItAnchor, {
permalink: true,
permalinkSymbol: '',
permalinkBefore: false,
}],
[markdownItCollapsible, {}],
],
},
});The built-in Eleventy compatibility profile already includes an image resize plugin compatible with #320px / #50% markers in image alt text.
const editor = createEditor('#editor', {
onChange(markdown, tokens, html) {
// Persist markdown or update app state
},
onSelectionChange(sel) {
// sel: { from, to, text, lineFrom, lineTo }
},
onPreviewClick(element, range) {
// range: { from, to }
},
onUploadStart(file) {
console.log('Uploading:', file.name);
},
onUploadDone(file, value) {
// value is URL (upload success) or base64 fallback.
// Images become , other files become [file.name](...).
},
onUploadError(file, error) {
console.warn(error.message);
},
onCommand(id, args) {
console.log('Action run:', id, args);
},
onBusyChange(state) {
// state.busy, state.label, state.detail, state.canCancel
console.log('Busy:', state);
},
});<smart-editor> emits CustomEvents:
se-change:detail = { markdown, tokens, html }se-selection-change:detail = { from, to, text, lineFrom, lineTo }se-preview-click:detail = { element, lineRange: { from, to } }se-busy-change:detail = { busy, count, label, detail, scope, locked, canCancel, cancelToken }
const el = document.querySelector('smart-editor');
el.addEventListener('se-change', (e) => {
console.log(e.detail.markdown);
});
el.addEventListener('se-preview-click', (e) => {
console.log(e.detail.lineRange.from);
});The editor auto-registers built-in toolbar actions grouped by intent.
bolditalicstrikethroughinline-code
h1,h2,h3blockquotehrcode-block
uloltask-list
linkimage(URL prompt)asset-upload(asset picker + paste/drop support; images -> markdown image, files -> markdown link)table(dialog)mermaiddrawio
- Source line mapping attributes for code-preview sync.
- Split-mode bidirectional smooth vertical scroll sync between code and preview (
scrollSync, enabled by default). - Table cell source-column metadata.
draw.ioimage block rendering from{xml}with click-to-edit in preview.- Fenced
mermaidblock placeholders rendered with Mermaid (if present). - Inline/block math placeholders rendered with KaTeX post-processing.
- Image alt resize syntax:
-><img width="320" height="180">.
Use registerAction to add custom actions to the toolbar.
If toolbar is omitted, the editor renders the legacy toolbar derived from registered actions (group + order).
If toolbar is provided, the toolbar becomes fully declarative: you decide which items are visible, in what order, in which group, and whether each item renders as label, icon, or icon-label.
- Action reference: maps to a registered action by id.
- Custom item: defines its own
run(api, state, args?)inline. - Dropdown: groups action references and custom items under one hover/click trigger.
const toolbar = {
groups: [
{
id: 'inline',
order: 10,
items: [
{ action: 'bold', display: 'icon' },
{ action: 'italic', display: 'icon' },
{
id: 'more-inline',
label: 'More',
display: 'icon-label',
items: [
{ action: 'strikethrough', display: 'label' },
{ action: 'inline-code', label: 'Code', display: 'label' },
],
},
],
},
{
id: 'templates',
order: 20,
items: [
{
id: 'templates-menu',
label: 'Templates',
display: 'label',
items: [
{
id: 'template-news',
label: 'News Article',
args: { templateId: 'news' },
async run(api, state, args) {
const res = await fetch(`/api/templates/${args.templateId}`);
const { markdown } = await res.json();
api.setMarkdown(markdown, { preservePreviewScroll: true });
},
},
],
},
],
},
],
};{
id?: string,
order?: number,
items: ToolbarItem[],
}toolbar.groups accepts either an array of group objects or an object map keyed by group id.
type ToolbarDisplay = 'label' | 'icon' | 'icon-label';
type ToolbarItem =
| string
| {
id?: string,
action: string,
label?: string,
icon?: string,
title?: string,
shortcut?: string,
display?: ToolbarDisplay,
args?: object,
}
| {
id?: string,
label?: string,
icon?: string,
title?: string,
shortcut?: string,
display?: ToolbarDisplay,
args?: object,
isEnabled?: (state) => boolean,
isActive?: (state) => boolean,
run: (api, state, args?) => void | Promise<void>,
}
| {
id?: string,
label?: string,
icon?: string,
title?: string,
display?: ToolbarDisplay,
items: Array<string | object>,
};Use helper methods when host data changes, for example after the user creates a new template.
Example for integrators: add a custom action button at runtime in declarative toolbar mode,
even if the target group is not defined in initial toolbar.groups.
editor.registerAction({
id: 'star-wrap',
title: 'Add star',
icon: '⭐',
run(api, state) {
const text = state.selection?.text;
if (text) api.replaceSelection(`⭐ ${text} ⭐`);
else api.insertText(' ⭐ ');
},
});
editor.upsertToolbarItem('custom', {
id: 'star-wrap-item',
action: 'star-wrap',
display: 'icon',
});upsertToolbarItem(groupId, ...) auto-creates the group when it does not exist.
If you need explicit group ordering, call upsertToolbarGroup({ id, order, items: [] }) first.
editor.upsertDropdownItem('templates', 'templates-menu', {
id: 'template-new',
label: 'New Template',
async run(api) {
const res = await fetch('/api/templates/new');
const { markdown } = await res.json();
api.setMarkdown(markdown, { preservePreviewScroll: true });
},
});
editor.removeDropdownItem('templates', 'templates-menu', 'template-new');Positioning is supported by optional { beforeId, afterId } for upsertToolbarItem and upsertDropdownItem.
{
id: string,
label?: string,
icon?: string, // SVG string or text
title?: string,
group?: string, // default: 'default'
order?: number, // default: 50
shortcut?: string, // display only
isEnabled?: (state) => boolean,
isActive?: (state) => boolean,
run: async (api, state, args?) => void,
}getMarkdown,setMarkdowngetTokens,getPreviewgetSelection,setSelectioninsertText,replaceSelectionrunCommandgetToolbarConfig,setToolbarConfigupdateToolbarConfigupsertToolbarGroup,removeToolbarGroupupsertToolbarItem,removeToolbarItemupsertDropdownItem,removeDropdownItemopenDrawioEditorfocus
When an action rewrites the whole document (setMarkdown(...)), prefer:
api.setMarkdown(nextMarkdown, { preservePreviewScroll: true });This keeps preview stable during synchronous/asynchronous render work and avoids visible jump on toolbar-triggered document rewrites.
state.selectionstate.markdownstate.cursorLine
editor.registerAction({
id: 'insert-suggestion',
title: 'Insert suggestion',
label: 'AI',
group: 'custom',
order: 200,
async run(api, state) {
const res = await fetch('/api/suggest', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ markdown: state.markdown }),
});
const { suggestion } = await res.json();
api.replaceSelection(suggestion || 'No suggestion');
},
});To remove it later:
editor.unregisterAction('insert-suggestion');The editor is designed to keep markdown output compatible with markdown-it based pipelines.
- Core parser is markdown-it with configurable options/plugins.
- Generated markdown remains plain markdown text.
- Mermaid integration is represented as fenced blocks.
- draw.io integration is represented as
{xml}lines. - Image resizing metadata is encoded in alt text using
|WxHsuffix.
draw.io diagrams are serialized as one markdown line:
{<uri-encoded-xml>}<image-src>is typically adata:image/svg+xml;base64,...preview image.<uri-encoded-xml>is diagram XML encoded withencodeURIComponent.- In preview, clicking the image or the
Edit diagrambutton opens draw.io modal and preserves XML.
By default, editor starts draw.io modal with hosted embed (https://embed.diagrams.net/?...).
If you provide a custom local drawio.url and init fails, it retries once with hosted embed.
Use this option to enforce strict offline behavior:
createEditor(element, {
drawio: {
url: '/drawio/?embed=1&proto=json&spin=1&ui=min&libraries=1',
allowHostedFallback: false,
},
});The npm package ships editor code only (no bundled dist/drawio webapp). For offline/self-hosted mode,
download draw.io assets directly to your application and point drawio.url at that location.
npx smart-md-editor drawio:download --out ./public/drawio --version latestStatic hosting examples:
# Vite / plain static app
npx smart-md-editor drawio:download --out ./public/drawio --version latest
# Next.js
npx smart-md-editor drawio:download --out ./public/drawio --version latest
# Any app served from a subpath, e.g. https://example.com/docs/
npx smart-md-editor drawio:download --out ./public/docs/drawio --version latestURL mapping:
./public/drawio -> /drawio/?embed=1&proto=json&spin=1&ui=min&libraries=1
./public/docs/drawio -> /docs/drawio/?embed=1&proto=json&spin=1&ui=min&libraries=1Then configure editor:
createEditor(element, {
drawio: {
url: '/drawio/?embed=1&proto=json&spin=1&ui=min&libraries=1',
allowHostedFallback: false,
},
});{%3Cmxfile%20host%3D%22app.diagrams.net%22%3E%3Cdiagram%20id%3D%22d1%22%20name%3D%22Page-1%22%3E%3CmxGraphModel%3E%3Croot%3E%3CmxCell%20id%3D%220%22%2F%3E%3CmxCell%20id%3D%221%22%20parent%3D%220%22%2F%3E%3C%2Froot%3E%3C%2FmxGraphModel%3E%3C%2Fdiagram%3E%3C%2Fmxfile%3E}- Preview HTML is sanitized with DOMPurify before rendering.
- If you add custom parser output attributes/tags needed in preview, update the allowlist in
src/ui/PreviewPanel.js. - Upload endpoint must validate file type/size server-side as well.
This project is licensed under the MIT License. See LICENSE for details.
Use this section as a compatibility reference when upgrading the editor in host applications.
- Initial public integration surface:
- Factory:
createEditor(element, options) - Exports:
EditorCore,SmartEditorElement - Web Component registration:
<smart-editor>
- Factory:
- Runtime API includes document ops, selection ops, mode switching, action registration, draw.io modal, and diff-based
proposeChange. - Core options include markdown-it configuration, upload configuration, draw.io URL override, and integration callbacks.
- Built-in action groups include inline formatting, blocks, lists, links/images, table/mermaid/draw.io, and image upload.
- Parser support includes source-line mapping, table cell metadata, Mermaid/KaTeX placeholders, draw.io image+xml blocks, and image dimension syntax (
|WxH).
- Treat any removal or signature change in methods listed under
Runtime APIas breaking. - Treat callback signature changes in
Configuration Optionsas breaking. - Treat changes to markdown serialization conventions (
draw.ioimage+xml block, image|WxH) as breaking for downstream pipelines. - Prefer additive changes for custom action integrations: add new action IDs instead of mutating existing IDs used by host automation.
- Added declarative
toolbarconfig for explicit grouping, ordering, display mode selection, and dropdown menus. - Added runtime toolbar methods:
getToolbarConfig()andsetToolbarConfig(config). - Toolbar items now support inline async
run(api, state, args?)handlers in addition to references to registered actions. - Added runtime toolbar helper methods for granular updates (
updateToolbarConfig,upsert/removefor groups/items/dropdown items).
npm install
npm run build
npm run dev
npm run drawio:downloadTo run the demo, serve from repository root (not from demo/):
npx serve .Then open /demo/ in the browser.
Ensure the editor container has explicit height, for example:
<div id="editor" style="height: 600px;"></div>Ensure Mermaid script is loaded and initialized on the page (window.mermaid).
Ensure KaTeX CSS is loaded. (KaTeX rendering is run by core, CSS controls visual output.)
For images, if upload.endpoint is missing or the upload request fails, the editor falls back to embedding the image as a base64 data URI (), so the document remains self-contained.
For non-image files (PDF, Word, Excel, etc.), there is no base64 fallback — a data-URI makes no sense as a markdown link and would bloat the document. If no endpoint resolves for a non-image file, onUploadError is fired and nothing is inserted.
If your storage service uses different endpoints per resource type (e.g. Cloudinary's /image/upload vs /raw/upload), use upload.endpoints:
upload: {
endpoint: 'https://api.cloudinary.com/v1_1/demo/raw/upload', // default for everything
endpoints: {
'image/*': 'https://api.cloudinary.com/v1_1/demo/image/upload', // images go here instead
},
extraFields: { upload_preset: 'my_preset' },
}A React adapter exists at src/adapters/react/SmartEditor.jsx. It exports SmartEditor. In the current build exports, the main package entry exports createEditor, EditorCore, and SmartEditorElement.