MDZip logo

@mdzip/editor-react

npm license

React component wrapper for the MDZip workspace editor.

@mdzip/editor-react provides a MdzipWorkspace component that embeds the full MDZip workspace UI — document preview, editor, package navigator, and asset manager — as a native React component.

Install

npm install @mdzip/editor-react

Peer dependencies: react and react-dom >=18.

Basic Usage

import { MdzipWorkspace } from '@mdzip/editor-react';

export function Viewer({ bytes }: { bytes: Uint8Array }) {
  return (
    <div style={{ height: 600 }}>
      <MdzipWorkspace
        bytes={bytes}
        fileName="document.mdz"
        mode="read-only"
        controls="viewer"
        onFailed={console.error}
      />
    </div>
  );
}

The parent element must have an explicit height. The component expands to fill it.

Archive Diff

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

<div style={{ height: 600 }}>
  <MdzipDiff
    before={{ bytes: baseBytes, label: 'Git base' }}
    after={{ bytes: workingBytes, label: 'Working tree' }}
    initialPath="index.md"
    toolbarActions={[{ id: 'refresh', label: 'Refresh', icon: 'refresh', run: refresh }]}
  />
</div>

MdzipDiff is read-only and updates the existing comparison view when its props change. A ref exposes openPath, openPreviousChange, openNextChange, setShowUnchanged, setNavigationVisible, and setToolbarActions. The built-in toolbar adds Previous/Next change buttons and a Show-unchanged toggle; pass a controls prop ({ navigation?, changeTraversal?, showUnchanged? }) to opt any of them out.

Editor Mode

<MdzipWorkspace
  bytes={bytes}
  fileName="document.mdz"
  mode="editable"
  controls="standalone-editor"
  onSaved={({ bytes }) => persist(bytes)}
  onChanged={({ bytes }) => setDirty(true)}
/>

Props

Prop Type Default Description
bytes Uint8Array | null — Raw archive bytes to open
workspace MdzWorkspace | null — Pre-built workspace object
fileName string 'document.mdz' Filename used for format detection and Save dialogs
mode MdzipWorkspaceMode 'read-only' 'read-only' or 'editable'
sourceFormat MdzipSourceFormat — Override format detection: 'mdz' or 'markdown'
controls MdzipControlPreset | MdzipControlPolicy 'viewer' 'preview', 'viewer', 'standalone-editor', 'hosted-editor', or a policy object
toolbarDensity 'comfortable' | 'compact' | 'dense' 'comfortable' Semantic sizing preset for built-in toolbar controls
contentDensity 'comfortable' | 'compact' 'comfortable' Semantic padding preset for editor and preview content
imageHydrationAnimation 'auto' | 'initial' | 'off' 'auto' Control preview image reveal animation: every render, first render per document path, or never
initialLayout MdzipWorkspaceLayout — Starting layout: 'preview', 'editor', 'split'
initialColorScheme MdzipColorSchemePreference 'system' 'light', 'dark' or 'system' (follows the OS setting live)
systemColorScheme MdzipSystemColorScheme — Makes the color scheme menu's System choice follow the host's theme instead of the OS setting, with its own label and icon, e.g. { colorScheme: 'dark', label: 'VS Code theme', icon: '<svg…>' }; changes apply live
previewMaxWidth MdzipPreviewMaxWidth 'default' Preview reading-column width: 'narrow', 'default', 'wide', 'full' or a pixel number; the user can change it from the toolbar's page-width menu
navigationMode MdzipNavigationMode — Package navigation mode
navigationButtonActive boolean — Whether the navigation button is shown
inlineSvgLinks boolean true Shows archive SVGs that contain links inline, so the links can be clicked (draw.io .drawio.svg diagrams, for example); other SVGs stay images. Read when the view is created
hostFileActions readonly MdzipFileAction[] — The host's own items in the file tree's right-click menu on files ({ id, label, appliesTo?, run }), e.g. "Open in Another Editor". Also shown as buttons on the card that stands in for a .drawio image. Read when the view is created
markdownRenderer MdzipMarkdownRenderer — Custom markdown renderer (keep the reference stable, e.g. useMemo)
markdownExtensions readonly MdzipMarkdownRenderExtension[] [] Markdown pipeline extensions, diffed by name — inline arrays are safe
entryRenderers readonly MdzipEntryRenderer[] [] Entry renderers claiming the content area for matching entries, diffed by id — inline arrays are safe
renderEntry (context) => ReactNode | undefined — Catch-all entry renderer: return a node to claim the selected entry, undefined to delegate
renderEntryPriority number 0 Matching priority of renderEntry relative to entryRenderers
frontMatter MdzipFrontMatterOptions {} Front matter panel config (enabled, display, collapsible, label) — always registered, diffed by deep equality; inline objects are safe
externalLinks MdzipExternalLinkPolicy — External-link policy, e.g. { target: '_blank' } (adds rel="noopener noreferrer"); optional rel and predicate(href). Re-applies without a re-render only when target, rel or predicate change; inline objects are safe

controls, density, imageHydrationAnimation, and rendering prop changes apply in place — they never recreate the workspace view. Line-number visibility changes preserve the current CodeMirror document and selection. See the @mdzip/editor Rendering Extensibility docs for the contracts and lifecycle rules.

Native entry rendering

<MdzipWorkspace
  bytes={bytes}
  renderEntry={(context) =>
    context.path.toLowerCase() === 'manifest.json'
      ? <ManifestEditor
          manifest={context.manifest}
          editable={context.mode === 'editable'}
          onManifestChange={context.updateManifest}
        />
      : undefined}
/>

The wrapper owns the React root: it mounts when the entry is claimed, re-renders on context updates and on every parent commit (entry content stays live with parent state — inline closures are safe and never re-mount), and unmounts on selection change.

Callbacks

Prop Signature Description
onChanged (event: MdzipWorkspaceChange) => void Called when archive bytes change
onSaved (event: MdzipWorkspaceSave) => void Called on Save
onSnapshotChanged (snapshot: MdzipWorkspaceSnapshot) => void Called on any state change
onSelectionChanged (snapshot: MdzipWorkspaceSnapshot) => void Called when the editor selection changes
onDirtyChanged (snapshot: MdzipWorkspaceSnapshot) => void Called when the dirty flag changes
onValidationChanged (snapshot: MdzipWorkspaceSnapshot) => void Called when validation state changes
onColorSchemeChanged (colorScheme: MdzipColorScheme) => void Called when the color scheme changes
onColorSchemePreferenceChanged (preference: MdzipColorSchemePreference) => void Called when the user picks Light, Dark or System in the toolbar menu
onPreviewWidthChanged (width: MdzipPreviewWidthChoice) => void Called when the user picks a width in the toolbar's page-width menu
onPreviewRendered (snapshot: MdzipWorkspaceSnapshot) => void Called when the preview HTML is mounted
onAssetsHydrated (snapshot: MdzipWorkspaceSnapshot) => void Called once the mounted preview's images have loaded
onLinkActivated (event: MdzipLinkActivatedEvent) => void Called for every preview link click before built-in handling; call event.preventDefault() to take over
onFailed (error: unknown) => void Called on unrecoverable errors
onConversionRequested (action: MdzipConversionAction) => boolean | Promise<boolean> Host hook for the markdown→MDZ conversion flow (nav button, Insert Image, or image paste on a plain .md). Return/resolve true to take over and suppress the built-in conversion dialog
onPackRequested (request: MdzipPackFilesRequest, context: MdzipPackFilesContext) => boolean | Promise<boolean> Host hook for the folder→.mdz packing decision surfaced by the packFilesAsWorkspace(files, options) ref method — fires only when the file list contains more than one Markdown file. Same return contract as onConversionRequested

Image insertion

Use imageInsertMode="markdown", "ask", or "html" for the built-in image markup flow. Pass imageInsertHandler for host-owned image UI; the handler can return Markdown or HTML sizing/alignment settings, return null to cancel, or return undefined to fall back to imageInsertMode.

Pass imageEditHandler to let users edit an existing image by clicking it. Fully opt-in — with no handler, clicking an image does nothing and no edit affordance appears; there is no built-in fallback dialog.

File management (nav 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, rename/move, duplicate, replace, download, copy markdown link, set entry point, set cover image, and delete. Files can also be dragged between folders, and OS files can be dropped onto the pane to add them as assets. Copy and Download remain available in read-only mode. The same operations are exposed imperatively: removeFile, renameFile, setEntryPoint, and setCoverImage on the handle. The handle also exposes whenRendered(), which resolves once the current preview (including its images) is mounted — useful for revealing or animating read-only preview content.

onLinkActivated fires for every preview link click, before the view's own handling, with the parsed link (kind: 'anchor' | 'document' | 'relative' | 'external', plus path, anchor, targetPath, sourcePath, modifier keys). Call event.preventDefault() in the handler to route the link yourself; unprevented clicks keep the built-in behavior. The handle also exposes scrollToAnchor(anchor) (waits for the preview to mount, resolves whether it scrolled; safe straight after load), getAvailableAnchors(), openPath(path, { anchor }) (opens another file, optionally at an anchor) and getCurrentPath(). Changing only fileName (e.g. after Save As) renames in place without reopening; set preserveSelectionOnReopen to stay on the current file when the archive content changes. See the @mdzip/editor README.

Imperative API

Use a ref to access the imperative handle:

import { useRef } from 'react';
import { MdzipWorkspace, type MdzipWorkspaceHandle } from '@mdzip/editor-react';

const ref = useRef<MdzipWorkspaceHandle>(null);

// Flush pending edits and persist
const snapshot = await ref.current?.flush();
if (snapshot) {
  await save(snapshot.bytes);
  ref.current?.markPersisted();
}

// Execute editor commands
await ref.current?.executeCommand('bold');

return <MdzipWorkspace ref={ref} ... />;

See the @mdzip/editor package for the full API reference, theming guide, and framework-agnostic usage.

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