MDZip logo

@mdzip/editor

npm license

Framework-independent MDZip workspace engine and browser view.

@mdzip/editor provides reusable helpers for opening .mdz archives, rendering Markdown previews, editing archive contents, comparing archive inventories, and embedding a configurable MDZip workspace UI.

Install

npm install @mdzip/editor

Basic Usage

import { MdzipWorkspaceView } from '@mdzip/editor';

const view = new MdzipWorkspaceView(container, {
  controls: 'viewer',
  initialLayout: 'preview',
  onFailed(error) {
    console.error(error);
  }
});

await view.open(bytes, {
  mode: 'read-only',
  fileName: 'document.mdz'
});

Regular Markdown is also supported:

await view.open(markdownBytes, {
  mode: 'editable',
  fileName: 'notes.md'
});

In the split layout the editor and preview scroll together, block by block: each heading, paragraph, list, code block, table or image in the preview stays level with its Markdown, so a tall image or table doesn't pull the two apart. The preview marks its blocks with data-mdzip-block for this; copies of the preview leave the marks out. With a custom markdownRenderer the panes scroll in proportion instead.

CodeMirror is not initialized until a source or split layout is used. Consumers that only need archive, rendering, and preview helpers can import from @mdzip/editor/preview; that entry point excludes MdzipWorkspaceView and its CodeMirror dependencies from the module graph.

The filename normally selects the source format. Pass sourceFormat: 'markdown' or sourceFormat: 'mdz' to override detection.

Normalized @mdzip/core-js workspaces can be opened without an initial archive rebuild:

await view.openWorkspace(workspace, {
  mode: 'editable',
  fileName: 'document.mdz',
  assetSourceId: 'document-etag-or-content-id'
});

Images are resolved only when referenced by the active document or selected in the navigator. To reuse resolved bytes across sessions, inject the optional bounded IndexedDB cache:

import { MdzipIndexedDbAssetCache, MdzipWorkspaceView } from '@mdzip/editor';

const view = new MdzipWorkspaceView(container, {
  assetCache: new MdzipIndexedDbAssetCache({ maxBytes: 64 * 1024 * 1024 })
});

For openWorkspace(), provide a stable assetSourceId (or archiveBytes) so cache hits can bypass lazy ZIP readers. Cache and storage failures automatically fall back to archive reads.

Editor Mode

const view = new MdzipWorkspaceView(container, {
  controls: 'standalone-editor',
  async onSaved(bytes) {
    await persist(bytes);
    view.markPersisted();
  }
});

await view.open(bytes, {
  mode: 'editable',
  fileName: 'document.mdz'
});

When onSaved is omitted, the built-in Save button downloads the current file in the browser. When onSaved is provided, the host owns persistence and must call markPersisted() after a successful write. Failed writes should leave the workspace dirty.

Control Presets

  • preview: clean document preview with no toolbar or package navigation.
  • viewer: read-only viewer controls, including navigation, layout switching, and zoom.
  • standalone-editor: full editor controls, including save.
  • hosted-editor: editor controls without an embedded save button, for hosts such as VS Code that own persistence.

Call setControls(nextControls) to update the policy after construction without rebuilding the workspace view. lineNumbers changes are applied to the existing CodeMirror editor, preserving the current document and selection.

The Show whitespace button (¶, at the end of the formatting buttons; controls.whitespace, on except in preview) shows spaces as faint dots and tabs as arrows in the source editor; it appears while the editor is visible. The marks start hidden unless showWhitespace: true is passed; setWhitespaceVisible() and isWhitespaceVisible switch and read them, and onWhitespaceVisibilityChanged lets a host remember the reader's choice.

Density and Spacing

Hosts can opt into smaller built-in UI without targeting private classes:

const view = new MdzipWorkspaceView(container, {
  controls: 'hosted-editor',
  toolbarDensity: 'compact', // 'comfortable' | 'compact' | 'dense'
  contentDensity: 'compact'  // 'comfortable' | 'compact'
});

view.setDensityOptions({
  toolbarDensity: 'dense',
  contentDensity: 'compact'
});

For exact sizing, set stable CSS custom properties on an ancestor of the workspace:

.studio-editor {
  --mdzip-toolbar-button-size: 28px;
  --mdzip-toolbar-compact-button-size: 26px;
  --mdzip-toolbar-icon-size: 14px;
  --mdzip-format-button-size: 26px;
  --mdzip-format-icon-size: 14px;
  --mdzip-toolbar-padding: 2px 8px;
  --mdzip-toolbar-gap: 4px;
  --mdzip-editor-content-padding: 16px 20px;
  --mdzip-preview-content-padding: 16px 20px 24px;
  --mdzip-preview-content-max-width: 720px;
}

Preview Width

The toolbar's page-width menu (between zoom and the color scheme menu) sets the preview's reading-column width: Narrow, Default, Wide or Full Width. Narrow, Default and Wide are 650 / 900 / 1200px at 100% zoom and scale with zoom; Full Width fills the preview pane. Each item's tooltip shows its width at the current zoom, e.g. "Wide (1200 px)", plus the width it fits to when the pane is narrower: "Wide (1200 px, fits to 461 px)". Hide the menu with controls: { previewWidth: false }.

previewMaxWidth sets the width from code (--mdzip-preview-content-max-width under the hood), and onPreviewWidthChanged(width) reports the user's menu choice so a host can remember it:

const view = new MdzipWorkspaceView(container, {
  controls: 'hosted-editor',
  previewMaxWidth: savedWidth ?? 'default', // 'narrow' | 'default' | 'wide' | 'full', or pixels
  onPreviewWidthChanged: (width) => saveWidth(width)
});

view.setPreviewMaxWidth(720);

Unset is the same as 'default'. A pixel number is used exactly as given and doesn't scale with zoom, and leaves no menu item checked; so does setting the --mdzip-preview-content-max-width CSS variable directly.

Find

view.openSearch(), the toolbar's Find button and Ctrl+F (Cmd+F on a Mac) with focus in the editor open find for the current Markdown document:

  • In View, a find bar over the preview searches the rendered text, what the reader sees rather than the Markdown, and the layout stays View. It counts matches in the whole document ("3 of 12"), including parts the progressive preview hasn't drawn yet; going to one of those draws it first. Matches are highlighted with the CSS Custom Highlight API, so the preview's DOM isn't changed. Enter and Shift+Enter (or F3 and Shift+F3, or the arrow buttons) move between them, Aa matches case, and Escape closes the bar and clears the highlights. Spaces in the query match any whitespace, and a match doesn't run from one paragraph into the next. Diagrams, code-block headers and other editor chrome aren't searched.
  • In Edit and Split, it's the source editor's find and replace panel, as before.

closeSearch() closes either; isFindOpen says whether the bar is open. controls.search: false turns both off. Find works in read-only documents too.

Outline Panel

The outline panel is a table of contents built from the document's headings, beside the preview. It marks the section being read, and a click scrolls smoothly to that section (it jumps instead when the system asks for reduced motion). The toolbar's outline button (next to Find) shows and hides it; it appears while the preview of a Markdown document is visible, in View or Split layout. Under progressive rendering it lists every heading, including ones in chunks that haven't been drawn yet, and a click draws the chunks up to the heading first, as scrollToAnchor() does.

The panel is closed at start. outline opens it and configures it, and onOutlineVisibilityChanged(visible) reports the button so a host can remember the choice:

const view = new MdzipWorkspaceView(container, {
  controls: 'hosted-editor',
  outline: { visible: savedOutline ?? false, levels: [1, 2, 3], collapse: true, label: 'Outline' },
  onOutlineVisibilityChanged: (visible) => saveOutline(visible)
});

view.setOutlineVisible(true);
view.isOutlineVisible; // true

levels defaults to [1, 2, 3]. With collapse (the default), deeper levels show only under the section being read. controls: { outline: false } hides the button; outline: true still opens the panel, for hosts with their own toggle. The panel is 240px wide (--mdzip-outline-pane-width, or the width option), and the reader can drag its edge to resize it; onOutlineWidthChanged(width) reports the new width when they let go, so a host can pass it back as width next time. It goes on the right of the document; position: 'left' puts it on the left instead, between the contents pane and the document, and setOutlinePosition('left' | 'right') moves it later (outlineSide says where it is). Below 760px it floats over the preview, on its side. Its links use the .mdz-outline* classes and take their colors from --mdz-outline-text, --mdz-outline-muted, --mdz-outline-rule and --mdz-outline-current.

The outline also works on its own, on any page that shows rendered Markdown (@mdzip/editor/outline, no other editor code):

import { createMdzipHeadingOutline, collectMdzipOutlineHeadings } from '@mdzip/editor/outline';

const outline = createMdzipHeadingOutline({
  content: document.querySelector('article')!,
  container: document.querySelector('#toc')!,
  levels: [2, 3],        // default
  label: 'On this page', // default
  scrollContainer: null  // the window; or the element that scrolls the content
});
outline.refresh(); // after the content changes
outline.destroy();

// Or just the headings, to draw your own: [{ id, text, level, element }]
const headings = collectMdzipOutlineHeadings(document.querySelector('article')!, { levels: [2, 3] });

Headings without an id get one. onNavigate(heading, event) runs on click (call event.preventDefault() to scroll some other way), offset sets where a heading counts as reached (default 96px from the top), and headings / findElement supply headings that aren't in the DOM yet.

Host Persistence

Desktop hosts can flush pending editor content, persist the returned bytes, and only then acknowledge a successful write:

const snapshot = await view.flush();
if (snapshot) {
  await nativeSave(snapshot.bytes);
  view.markPersisted();
}

flush() deliberately leaves dirty set until markPersisted() is called. serialize() and getCurrentSnapshot() provide non-acknowledging alternatives.

Structured callbacks are available for workspace, document, asset, manifest, selection, dirty, validation, and snapshot changes. Asset hosts can also call addAsset(), replaceAsset(), removeAsset(), and listAssets().

Editing JSON and the Manifest

.json files open in the editor with JSON highlighting, and are checked as you type: a syntax error is underlined where it is, with what's wrong ("Remove the comma before }: JSON has no trailing commas."), and a status line under the editor sums it up. Other JSON files are saved exactly as typed, even when they don't parse.

The archive's manifest.json opens as a form, Document properties, in the View layout: Title, Description, Author, Keywords, Language, License and Document version, with the entry point and mode under Advanced and the dates, spec version and producer as read-only details. Where a label isn't the JSON key itself, the key follows it in parentheses, such as "Opens with (entryPoint)" and "Kind of archive (mode)". Edit shows the JSON, and Split shows both, each following the other as you type. The JSON text is the one source of truth: a change in the form sets only that value in the text (setMdzipJsonMember()), so key order, formatting and fields the form doesn't show are kept, and Ctrl+Z in the JSON editor undoes it. Clearing a field removes the property. A field's problem shows under it; while the text isn't valid JSON, the form shows a notice with Fix in JSON instead. The manifest remembers its own layout, so opening it doesn't change how your documents are shown. manifestView: 'json' opens it in the JSON editor instead of the form.

manifest.json is checked against the spec in both views:

Problem
Not JSON, not an object, or a property name used twice error
spec, spec.version, mode or entryPoint invalid, or entryPoint not a Markdown file in the archive error
A descriptive field with a wrong type or format (title: 42, created: "yesterday") error
cover names no file in the archive warning
producer or spec.version edited (tools normally set these) warning
Fields the spec doesn't define fine: listed as custom fields and kept

While the manifest has an error, saving is blocked: flush(), saveToBytes(), exportBytes(), serialize() and getCurrentSnapshot() throw MdzipManifestInvalidError (code: 'ERR_MANIFEST_INVALID', with the problems in validity), and the toolbar's save button opens the manifest to show them. The broken text is kept while you look at other files. A valid manifest is saved as core-js writes every manifest: the same values, in the same order, custom fields included, with modified refreshed and 2-space indentation.

const view = new MdzipWorkspaceView(container, {
  jsonStatus: true, // the status line under the editor (default)
  onJsonValidityChanged: (validity, path) => {
    // validity: { kind, status: 'valid' | 'warnings' | 'invalid', problems, canSave, customFields }
    // null when the open file isn't JSON
  }
});

view.getManifestValidity(); // the manifest's problems that block saving, or null

JSON files also get the usual editing aids: matching brackets are highlighted, {, [ and " close themselves as you type, and arrows in the gutter fold objects and arrays (Ctrl+Shift+[ and Ctrl+Shift+] too). Format JSON (the {} button in the editing toolbar, or Shift+Alt+F) re-indents the file with 2 spaces in one undo step. It only changes whitespace: keys stay in their order, and numbers (1.0, 1e3, very long integers) and strings stay exactly as typed. It's disabled while the text isn't valid JSON. view.formatJson() does the same, and formatMdzipJsonText(text) formats any JSON text.

The checks are also available on their own: validateMdzipManifestText(text, { archivePaths, stored }) and validateMdzipJsonText(text) return the same MdzipJsonValidity, with each problem's position in the text.

File Management (navigation pane)

With controls: 'standalone-editor' or 'hosted-editor' (or fileActions: true in a custom policy), the navigation pane offers a right-click context menu: new .md file, new folder, Add Files… (a file picker; the files go into that folder), rename/move (edit the full archive path), duplicate, replace, download, copy markdown link / image embed, set entry point (shown bold in the tree), set/remove cover image, and delete with a confirmation prompt (orphaned assets delete immediately). The entry-point document and manifest.json cannot be deleted. Copy and Download remain available in read-only contexts.

Drag and drop is supported in all directions: move files between folders, drop OS files onto the pane to add them as assets (a host whose drags carry only file URIs, like VS Code's Explorer, can read them through resolveDroppedUris), drag a tree file onto the editor to insert a markdown link or image embed at the pointer, and drop an OS image onto the editor to embed it like a paste.

Host actions in the file menu. hostFileActions adds the host's own items to the right-click menu on files, above Download, for things only the host can do. VS Code uses it for Open in VS Code Editor, which opens the file in whatever VS Code editor handles its type:

new MdzipWorkspaceView(container, {
  hostFileActions: [{
    id: 'open-elsewhere',
    label: 'Open in Another Editor',
    appliesTo: (file) => !file.isMarkdown,  // optional: which files get it
    run: (file) => openElsewhere(file.path) // file: { path, isMarkdown, isImage, isManifest, isEntryPoint }
  }]
});

The items show in read-only workspaces too; the host decides what each one allows. The Angular, React and Vue wrappers take the same hostFileActions.

Selecting and extracting files. Ctrl+click (Cmd+click on a Mac) adds a row of the tree to the selection or takes it off, Shift+click selects the rows in between, and Ctrl+A / Cmd+A with focus in the tree selects every row (Escape clears it). Right-clicking a row outside the selection selects just that row; inside a selection of several, the menu offers only taking them out of the archive. Folders take all their files, and manifest.json comes only when it's selected itself. Paths below the folder are kept and bytes are copied as stored. The archive isn't changed, so this works in read-only workspaces too.

  • On the web (no onExtractFiles), one file is Download, and a folder or several rows are Download as ZIP (the folder's name, or the archive's, .zip), plus Extract to Folder… in browsers that can write to a folder (showDirectoryPicker). That asks in the editor before replacing files already there.
  • In a desktop host, onExtractFiles replaces all of these with Extract… (Extract All… on the empty part of the pane). It's called with { files: [{ path, bytes }], selection: { files, folders } }; the host picks where they go, keeps the paths below it and asks before replacing.
new MdzipWorkspaceView(container, {
  onExtractFiles: async ({ files }) => {
    const folder = await pickFolder();       // the host's own dialog
    await writeFiles(folder, files);         // ask first if any exist
  }
});

view.extractFiles(paths, { includeFolders }) returns the same { path, bytes }[] for files and folders named by path ('' is the whole archive), for hosts with their own commands.

The same operations are available programmatically: removeFile(), renameFile() (rewrites markdown references, including a moved document's own relative links), setEntryPoint(), and setCoverImage().

Conversion Hook

For plain-markdown sources, hosts can take over the markdown→MDZ conversion flow (triggered by the nav button, Insert Image, or an image paste/drop):

const view = new MdzipWorkspaceView(container, {
  async onConversionRequested(action, context) {
    // action.kind: 'navigation' | 'image-picker' | 'image-file' (with action.file)
    const relativePath = await hostHandlesImage(action);
    return relativePath
      ? context.insertMarkdown(`![](${relativePath})`)
      : false;
  }
});

Returning or resolving false (or omitting the callback) keeps the built-in conversion dialog. Errors thrown by the hook are reported via onFailed and fall back to the built-in dialog. The context preserves the triggering selection while a host dialog is open; it returns false if that document has changed. context.convertToMdz() runs the built-in conversion and image action against the same captured selection.

A host that writes the image file itself (a linked image next to the .md) can still give the user the same Markdown/HTML, alt text, size and alignment choices an .mdz paste gets: await context.promptImageInsert({ bytes, fileName, altText }) runs imageInsertHandler or the 'ask' dialog and resolves null on cancel (write nothing), then context.formatImageInsert(src, decision) returns the text to pass to context.insertMarkdown(). src is used as given, so URL-encode it.

Image Insert Hook

Set imageInsertMode to choose the built-in image markup flow: 'markdown' keeps the default ![alt](path) insertion, 'html' inserts a default <img> element, and 'ask' opens a small dialog for Markdown vs HTML, alt text, proportional size, and alignment.

For host-owned UI, provide imageInsertHandler. It receives file metadata, intrinsic image size when detected, and the source ('paste', 'drop', or 'picker'). Return { mode: 'markdown', altText } or { mode: 'html', altText, width, height, position }; return null to cancel. The built-in dialog asks for width, height, or percent scaling and preserves aspect ratio by emitting one dimension, or proportional dimensions for percent scaling. Returning undefined falls back to imageInsertMode. The built-in HTML path uses portable align attributes for positioning because the default preview sanitizer strips inline style attributes.

MdzipRenderingService uses defaultSafeMarkdownRenderer when no renderer is injected. The default renderer sanitizes generated HTML and unsafe URL schemes.

Image Edit Hook

Editing an existing image (Markdown ![]() or raw HTML <img>, including one wrapped in <p align="...">) is fully opt-in — unlike image insertion, there is no built-in fallback dialog and no imageEditMode. Set imageEditHandler to enable it:

const view = new MdzipWorkspaceView(container, {
  async imageEditHandler(request) {
    // request: { src, altText, width?, height?, position?, mode: 'markdown' | 'html' }
    const decision = await hostEditDialog(request);
    if (!decision) return null; // cancel — leaves the image untouched
    return decision; // same shape as an image-insert decision
  }
});

With no imageEditHandler set, clicking an existing image does nothing — no edit affordance ever appears. With one set, clicking an image reference in the source editor shows a small edit icon next to it; clicking that icon calls the handler with the image's current alt/width/height/position parsed from its existing Markdown or HTML, and rewrites that exact reference in place with whatever decision is returned (same { mode, altText, width, height, position } shape imageInsertHandler returns). Reference-style Markdown images (![alt][label]) aren't supported.

Pack Files Hook

Hosts that let a user pick a folder (Electron dialog, VS Code workspace API, etc.) can hand the collected files straight to the view instead of building the .mdz themselves:

const result = await view.packFilesAsWorkspace(
  files, // Array<{ path: string; bytes: Uint8Array }>
  { title: 'My Project', fileName: 'project.mdz' }
);

With zero or one Markdown file among files, it packs Document mode immediately and opens the result in memory — no prompt. With more than one, it needs a Document-vs-Project mode and entry-point decision. Provide onPackRequested to own that decision:

const view = new MdzipWorkspaceView(container, {
  async onPackRequested(request, context) {
    // request.markdownFiles, request.suggestedEntryPoint
    const decision = await hostPicksModeAndEntryPoint(request);
    if (!decision) return false; // fall back to the built-in dialog
    await context.applyDecision(decision);
    return true;
  }
});

Returning or resolving false (or omitting the callback) keeps the built-in dialog — a mode toggle plus an entry-point picker listing the discovered Markdown files. Errors thrown by the hook are reported via onFailed and fall back to the built-in dialog. context.applyDecision({ mode, entryPoint }) performs the actual pack either way.

Document mode opens the packed archive in the view (unsaved); Project mode returns the archive bytes without opening them, since only the host knows where a project archive should be saved — save it, then view.open(bytes, ...).

Rendering Extensibility

The view accepts a custom markdown renderer, composable markdown pipeline extensions, and entry renderers that replace the content area for selected archive entries — all optional, with built-in behavior as the fallback:

import { mdzipPathMatcher, type MdzipEntryRenderer } from '@mdzip/editor';

const manifestRenderer: MdzipEntryRenderer = {
  id: 'host-manifest-editor',
  priority: 100,
  matches: mdzipPathMatcher('manifest.json'),
  mount: (container, context) => mountManifestEditor(container, {
    manifest: context.manifest,
    editable: context.mode === 'editable',
    onChange: (manifest) => context.updateManifest(manifest)
  })
};

const view = new MdzipWorkspaceView(container, {
  markdownRenderer,                  // optional full renderer replacement
  markdownExtensions: [mermaidExt],  // transformMarkdown/transformHtml/mount
  entryRenderers: [manifestRenderer]
});

Renderers may be asynchronous; stale results are dropped when the selection moves on. Sanitization stays in the pipeline: string output from custom renderers and transform hooks passes through DOMPurify before insertion. Entry renderer handles are destroyed on selection change and destroy(). The same options are available as inputs/props on the Angular, React, and Vue wrappers. See the Developer Guide's Rendering Extensibility section for the contracts and lifecycle rules.

An extension whose transformHtml emits markup the default policy would strip (inline SVG, for example) declares the narrow relaxations it needs via a sanitize contribution (MdzipSanitizeContribution), merged into the single DOMPurify pass. Keep contributions minimal — they widen the policy for the whole preview, since the extension output and surrounding markdown HTML are sanitized together.

Switching between light and dark keeps the rendered preview: the root's theme class re-colors it through CSS, and nothing is re-rendered or moves. An extension whose output has the scheme baked in (a diagram's SVG colors, say) implements updateColorScheme(root, context) to re-theme just its own output in place, with context.colorScheme set to the new scheme; extensions whose output doesn't depend on the scheme implement it as a no-op. While any registered extension that transforms or mounts content lacks the hook, or with a custom markdownRenderer, a scheme change re-renders the whole preview, as before. The Mermaid and front-matter extensions implement it.

Mermaid diagrams

Render fenced ```mermaid blocks to inline SVG with the optional extension from the @mdzip/editor/mermaid entrypoint. It is shipped separately so the ~1MB mermaid library stays out of the core bundle — it is dynamically imported the first time a document actually contains a mermaid block. Install mermaid (an optional peer dependency) alongside @mdzip/editor:

import { mdzipMermaidExtension } from '@mdzip/editor/mermaid';

const view = new MdzipWorkspaceView(container, {
  markdownExtensions: [mdzipMermaidExtension({ theme: 'auto' })]
});

Diagrams render with mermaid's strict security level, each SVG is re-sanitized before insertion, and an invalid diagram renders as an inline error block instead of breaking the preview. theme defaults to 'auto', following the preview color scheme. Enabling the extension widens the preview's sanitize policy to allow SVG and inline styles for the whole render. For a CSP-restricted host, mermaid bundles into the consumer's webview script (no new img-src needs); if you lazy-load its chunk, serve it under the existing script-src nonce.

ELK layout. Mermaid 12 bundles the ELK layout engine and uses it by default for ER, flowchart, state, class, requirement and use-case diagrams, giving right-angle lines like GitHub's. A diagram can opt back out with frontmatter config: layout: dagre. The extension leaves Mermaid's own default look, so Mermaid 12's new default styling applies too.

On Mermaid 11, diagrams use the Dagre layout, with curved lines. To use ELK for ER diagrams there, set a default layout for that diagram type and supply the layout engine:

mdzipMermaidExtension({
  defaultLayouts: { er: 'elk' },
  // Mermaid 11: npm install @mermaid-js/layout-elk@^0.2
  loadLayouts: () => import('@mermaid-js/layout-elk').then((m) => m.default)
});

A layout the diagram declares itself (frontmatter config: layout: dagre, or an %%{init}%% directive) always wins, and other diagram types are unaffected. The layout engine loads lazily, the first time an ER diagram needs it, and is registered once. On Mermaid 12 neither option is needed. If it fails to load, diagrams keep mermaid's default layout.

Front matter

A leading ----delimited YAML block is recognized automatically — no markdownExtensions wiring needed — and no longer falls through to marked as a stray <hr> plus paragraph/setext heading. Control how it renders with frontMatter:

const view = new MdzipWorkspaceView(container, {
  frontMatter: {
    enabled: true,        // default; false strips it with nothing rendered in its place
    display: 'table',     // default; 'raw' shows the YAML source as a syntax-highlighted code block
    collapsible: true,    // default; false renders a static, always-visible block (no collapse toggle)
    label: 'Front matter' // default; a custom string, or the sentinel 'first-line' — see below
  }
});
  • display: 'table' (default) — a key/value table. 'raw' — the block's YAML source as a fenced, syntax-highlighted yaml code block. Either way the panel is wrapped the same: same header, same expand/collapse behavior.
  • collapsible: false turns off the collapsible <details> wrapper, rendering a static block with the same header and body instead.
  • label sets the header text — a fixed string ('Front Matter', 'Metadata', etc.), or the sentinel 'first-line' to use the block's own first raw YAML line instead (e.g. title: My Document), falling back to the default label when that line is blank.
  • enabled: false strips the block with nothing rendered in its place.

setRenderingOptions({ frontMatter }) updates it live. A manifest-less .md file's front matter title: also feeds the title-fallback chain (suggestedTitleFromMarkdown), ahead of the first heading and filename. The parser itself (parseFrontMatter, DOM-free) is exported from the package root for hosts that want the raw data without the render extension.

Developer Guide

See the Developer Guide for granular host controls, height requirements, lifecycle events, persistence, theming, and Raw, Angular, React, and Vue examples.

See the Theming Guide for custom theme examples and the complete CSS variable reference.

Archive Helpers

import {
  openMdzArchive,
  readCanonicalMarkdown,
  createArchiveInventory,
  diffArchiveInventories
} from '@mdzip/editor';

These helpers are built on @mdzip/core-js and are suitable for framework wrappers, desktop hosts, browser apps, and extension integrations.

Archive Diff View

The optional diff entry point keeps merge dependencies out of normal editor and preview bundles:

import { MdzipDiffView } from '@mdzip/editor/diff-view';

const diff = new MdzipDiffView(container, {
  before: { bytes: baseBytes, label: 'Git base' },
  after: { bytes: workingBytes, label: 'Working tree' },
  initialPath: 'index.md',
  toolbarActions: [{
    id: 'refresh',
    label: 'Refresh comparison',
    icon: 'refresh',
    run: refreshComparison
  }]
});

Construction opens the initial comparison. Use await diff.open(options) to replace both sides, openPath(path) to select an entry, and setShowUnchanged(false) to focus the tree on changes. Toolbar actions may be updated with setToolbarActions() without reopening either archive.

The library-owned toolbar provides a navigation toggle, Previous/Next change buttons, and a Show-unchanged toggle. Drive change traversal in code with openPreviousChange() / openNextChange() (they walk non-unchanged entries and resolve false at the ends). Opt individual built-in controls out with the controls option (navigation, changeTraversal, showUnchanged; all default on). The navigation pane animates open/closed like the workspace nav pane.

The read-only view shows the union of archive paths in a directory tree, added/removed/changed status, side-by-side text diffs, explicit missing-side states, image previews with metadata, and binary metadata. Entry content is loaded only when selected. Call destroy() to release editors, listeners, and image object URLs.

Plain Markdown files

A side can be a plain .md document instead of an archive. Pass its text as markdown, and, for images in the rendered view, a readResource function that reads the files it links to:

const diff = new MdzipDiffView(container, {
  before: { markdown: headText, label: 'HEAD', readResource: readImageAtHead },
  after: { markdown: workingText, label: 'Working tree', fileName: 'notes.md', readResource: readImageOnDisk },
  rendered: true
});

readResource receives the image source normalized relative to the document's folder (images/a.png, ../shared/a.png; a root-relative source keeps its leading /) and resolves the bytes, or null when there's no such file. Give each side its own reader, so a comparison with an older version shows that version's images. Without one, images show as missing.

Set editable: true on a Markdown side (typically the working copy) to let the user edit it in the source view; onMarkdownChange(text) receives the full text after each edit, and the comparison updates as they type. The rendered view stays read-only but shows the edited text. Saving is up to the host.

The comparison has a single entry, named after fileName (or document.md), and the navigation pane starts hidden unless navigationVisible says otherwise. One side may be plain Markdown and the other an archive: the document then lines up with the archive's main document.

Resolving Merge Conflicts

When two branches change the same part of a document, a Git merge leaves conflict markers in its text. For an .mdz, the mdz merge driver (mdzip-cli) merges the archive file by file: it puts the markers inside the documents, keeps both versions of an image both sides replaced (chart.png and chart.theirs.png), and decides a few things itself (a file one side deleted and the other changed is kept; a manifest field both changed keeps the current value). MdzipMergeView resolves what it left, in the layout of the Visual Studio and VS Code merge editors:

import { MdzipMergeView } from '@mdzip/editor/merge-view';

const view = new MdzipMergeView(container, {
  bytes: mergedArchiveBytes,              // or { markdown: text, fileName: 'notes.md', readResource }
  // Optional: the versions Git holds during the merge (index stages 1, 2, 3).
  versions: { base: { bytes: baseBytes }, ours: { bytes: oursBytes }, theirs: { bytes: theirsBytes } },
  oursLabel: 'main',                      // branch names, shown under Current and Incoming
  theirsLabel: 'topic',
  colorScheme: 'dark',
  toolbarDensity: 'dense',
  onChange: ({ path, text, bytes, remaining }) => save(bytes ?? text),
  onComplete: ({ remaining }) => markResolved() // shows a Complete Merge button
});
  • A tree of the archive's files with a marker on each: ● text conflicts (with a count), ◐ a choice to make (an image both sides replaced), ↺ a choice the merge made that's worth reviewing, ✓ merged. Unchanged files are hidden unless you ask for them. A plain Markdown document has no tree.
  • A text file shows Incoming (theirs) on the left and Current (ours) on the right, each with its changes from the original marked, over the result. Each change has a checkbox: one-sided changes start ticked, conflicts unticked. Ticking a side takes its text into the result; ticking both sides of a conflict keeps both, in the order you ticked them, and unticking both brings the conflict back. Take All Incoming / Take All Current in each pane's heading tick every change on that side. In the source view the result is editable (the boxes follow what you type), and each conflict has Accept Incoming, Accept Current, Accept Both and Use Original links above it. The three panes scroll together; in the source view they're lined up line for line (blank filler where one pane has fewer lines for a change, a dashed line where it has none), with word wrap off so the lines stay level. In the rendered view, matching headings stay level and the stretches between them scroll in step. The result's heading counts the conflicts remaining in the file, and the toolbar counts those left overall ("2 of 5 conflicts") and steps through them across files. The rendered view shows all three as the preview, with unresolved conflicts in the result showing the current version, marked, and a bar that accepts the current conflict.
  • An image both sides replaced shows incoming, current and the original, with Take Incoming (which removes the .theirs copy) and Keep Current. A file one side deleted has Keep it and Delete it. Manifest fields both sides changed are listed with Take Incoming / Take Current.
  • With versions, the tree shows every change (added, deleted, changed in current, incoming or both) and spots renames, as mdz merge does, and each text file shows its one-sided changes with checkboxes too; without them, the view works from the conflict markers and .theirs copies alone.
  • onChange fires after each change with the entry's new text and, for an archive, the whole archive's new bytes (typing in the result is reported once it pauses). onResolved fires when nothing is left, and Complete Merge (shown when you pass onComplete) reports every pending change, then calls onComplete with what's still unresolved, so the host can ask before completing anyway. files lists each file's state and summary, conflicts what's left; resolve(index, resolution), chooseChange(path, index, sides) (a file's changes, as the checkboxes set them), resolveFile(path, 'keep' | 'delete') and chooseManifestField(key, side) resolve from code; getText(path) and getArchiveBytes() return the current result.

The parsing is also available on its own from the main entry: findMergeConflicts(text) returns each block (with ours, base or null, theirs, labels and position), and resolveMergeConflict(text, index, 'ours' | 'theirs' | 'both' | 'base' | { text }) returns the text with that block replaced. Markers longer than seven characters (Git's conflict-marker-size) and CRLF line endings are handled; an unfinished block is left alone.

Preview Lifecycle Signals

To reveal or animate read-only preview content without scraping internal DOM, use the preview lifecycle signals on MdzipWorkspaceView:

const view = new MdzipWorkspaceView(container, {
  controls: 'preview',
  onPreviewRendered: (snapshot) => { /* preview HTML is mounted */ },
  onAssetsHydrated: (snapshot) => { /* its images have finished loading */ }
});

// Or await the fullest "ready" point (mounted + images hydrated):
await view.whenRendered();
revealContent();

whenRendered() resolves immediately when the latest preview is already hydrated, and resolves (rather than hanging) if the view is destroyed.

The preview hydrates images progressively: the text mounts right away with each archive image in a collapsed slot, so the reader gets a compact, readable text block first. As each image resolves, its slot eases open to the height reserved from dimensions sniffed out of the image header — a single slide to the exact box, so the pixels arrive with no further reflow (and it snaps open instead under prefers-reduced-motion). onPreviewRendered fires when the text is mounted; onAssetsHydrated fires once every referenced image has resolved and its final src is assigned.

In live-editing hosts where the preview re-renders frequently, pass imageHydrationAnimation: 'initial' to keep the first-load reveal but snap images open on same-document edits. Use 'off' to disable the loading pulse and slide-open animation entirely.

Hosts that embed the preview as a doc browser can route links, set an external-link policy and deep-link to headings, all without touching preview DOM.

Link clicks. onLinkActivated(event) fires for every click on a preview link, before the view's own handling. event.kind is 'anchor' (a bare #fragment), 'document' (another Markdown document in the archive; event.targetPath is its archive path), 'relative' (relative, but not to an archive document, e.g. ../design/foo.md) or 'external' (has a URL scheme). The event also carries href, text, path (the href without its fragment), anchor (the decoded fragment), sourcePath, the modifier keys and domEvent. Call event.preventDefault() synchronously to take over: the view then does nothing more and the browser doesn't navigate. If you leave it unprevented, the built-in behavior runs as before (anchor scroll, document open, onUnresolvedLinkClick).

const view = new MdzipWorkspaceView(container, {
  controls: 'viewer',
  onLinkActivated: (event) => {
    if (event.kind === 'relative') {
      event.preventDefault();
      router.openDoc(resolve(event.sourcePath, event.path), event.anchor);
    }
  }
});

parseMdzipLink(href, currentPath, entries) gives the same classification outside a click.

External links. externalLinks: { target: '_blank' } makes http:, https:, mailto: and //host links open in a new tab with rel="noopener noreferrer". Pass rel to override that default, or predicate(href) to choose which links count. Only hrefs with a URL scheme reach the predicate; relative links and #fragments never change. The policy also covers links written as raw HTML. It's unset by default, and setExternalLinks(policy) changes it at runtime without a re-render (undefined restores each link's own attributes).

Links inside SVG diagrams. An SVG shown as an image is a flat picture, so its links can't be clicked. When an archive SVG contains links, such as a draw.io diagram saved as .drawio.svg, the preview shows it inline instead, in its own shadow root, and its links behave like any other preview link: onLinkActivated, links to other files in the archive and externalLinks all apply. The SVG is cleaned first: no scripts, event handlers or javascript: links, nothing loaded from outside the archive (other than data: images), and its styles and ids stay inside the shadow root. It keeps the image's alt text (as aria-label), width and align. SVGs without links stay images. Turn it off with inlineSvgLinks: false.

Raw draw.io diagrams. The preview can't draw a .drawio or .dio file yet (#59). An image pointing at one, such as ![System](diagrams/system.drawio), shows a card instead of a broken image: the alt text (or file name), the file's path, why it isn't drawn, and how to show it (save it from draw.io as an editable SVG, .drawio.svg, which the preview draws). The host's hostFileActions that apply to the file appear on the card as buttons, so in VS Code Open in VS Code Editor opens it in Draw.io Integration. When the contents pane is shown (controls.navigation), the card also points to the same actions on the file's right-click menu there. Copying the preview gives the original <img> back, and plain-text copies leave the card out. .drawio.svg and .drawio.png files are ordinary images and unaffected.

Deep links to headings. await view.scrollToAnchor('some-heading') scrolls the preview to a heading or an explicit <a id>/<a name>. It accepts the fragment with or without # and matches the way a clicked #fragment does. You can call it at any time, including straight after open() or from onPreviewRendered. It waits for the current document to mount and, under progressive rendering, mounts the chunks up to the target first. It resolves true when it scrolled and false when nothing matched. '' and 'top' scroll to the top. { smooth: true } glides there over a fraction of a second, as an outline click does, instead of jumping (except under prefers-reduced-motion). getAvailableAnchors() lists the reachable anchors in document order, including headings in chunks that haven't mounted yet.

await view.open(bytes, { fileName: 'guide.md' });
if (location.hash && !(await view.scrollToAnchor(location.hash))) {
  console.warn('No such section', location.hash, view.getAvailableAnchors());
}

Opening another file. await view.openPath('docs/install.md', { anchor: 'windows' }) opens another file of the workspace, as clicking it in the file tree does, and then scrolls to the anchor the way scrollToAnchor does. It resolves false for a path that isn't in the archive (the current file stays open) or an anchor that isn't found (the file still opens). Paths must match exactly: archive paths are case-sensitive. getCurrentPath() returns the file currently shown.

Reopening without losing the user's place. open() and openWorkspace() accept initialPath to show a file other than the entry point, for example the one the user was on before the host reloaded the archive:

const path = view.getCurrentPath() ?? undefined;
await view.open(newBytes, { fileName, initialPath: path });

setFileName(name) changes the name in the title bar and the save name in place, without reopening, for example after Save As. It returns false when the new name implies a different format (.md vs .mdz), which needs a reopen. The framework wrappers do this for you: a fileName-only change renames in place, and preserveSelectionOnReopen keeps the current file when bytes or workspace change.

Content Security Policy (restricted hosts)

Archive images resolve to URL.createObjectURL() blob: object URLs (the view falls back to data: URLs only where createObjectURL is unavailable, such as Node). When embedding the editor in a host with a restrictive Content-Security-Policy — a VS Code webview, a sandboxed iframe, etc. — the policy's img-src must include blob:, or every archive image renders as a broken placeholder:

img-src 'self' <cspSource> blob: data:;

Including data: as well lets the view's built-in recovery path work: if a blob: URL fails to load (for example because img-src omits blob:), the view retries that image once with a data: URL and, if it still fails, reports the error through the onFailed option instead of failing silently. Listen on onFailed to surface image-load problems during development:

const view = new MdzipWorkspaceView(container, {
  onFailed: (error) => console.warn('[mdzip]', error)
});

Call destroy() to revoke the object URLs the view created.

This page mirrors @mdzip/editor README — the canonical, versioned source in its home repository. It is re-fetched on every site build.