Skip to content
On this page

Marzipan Class API

Complete reference for the Marzipan editor class.

Constructor

new Marzipan(target, options)

Creates one or more Marzipan editor instances.

Parameters:

  • target (string | Element | NodeList | Array) - Target element(s) to initialize
    • string - CSS selector (e.g., '#editor', '.markdown')
    • Element - Single DOM element
    • NodeList - Collection of DOM elements
    • Array - Array of DOM elements
  • options (Object) - Configuration options (see Options)

Returns: Array<Marzipan> - Always returns an array of instances

Examples:

ts
// Single element by selector
const [editor] = new Marzipan('#editor');

// Multiple elements
const editors = new Marzipan('.markdown-editor');

// Direct element reference
const element = document.getElementById('editor');
const [editor] = new Marzipan(element);

// With configuration
const [editor] = new Marzipan('#editor', {
  fontSize: '16px',
  toolbar: true,
  showStats: true,
  theme: 'cave'
});

Array Destructuring

The constructor always returns an array. Use array destructuring for single editors:

ts
const [editor] = new Marzipan('#editor');

Content Methods

getValue()

Get the current markdown content from the editor.

Returns: string - Current markdown content

ts
const content = editor.getValue();
console.log(content); // "# Hello World\n\nMarkdown content..."

setValue(value)

Set the markdown content in the editor.

Parameters:

  • value (string) - Markdown content to set

Returns: void

ts
editor.setValue('# New Content\n\nCompletely new text.');

WARNING

Setting a new value will trigger the onChange callback if configured.


getStats()

Return live statistics for the current editor content.

Returns: { chars: number, words: number, lines: number, line: number, column: number }

ts
const stats = editor.getStats();
console.log(`${stats.words} words, cursor at line ${stats.line}:${stats.column}`);

getRenderedHTML(options?)

Get the rendered HTML of the current content.

Parameters:

  • options (Object) - Optional rendering options
    • cleanHTML (boolean) - Remove syntax markers and Marzipan classes (default: false)

Returns: string - Rendered HTML

ts
// Get HTML with Marzipan classes and syntax highlighting
const html = editor.getRenderedHTML();

// Get clean HTML for export (no Marzipan classes)
const cleanHtml = editor.getRenderedHTML({ cleanHTML: true });

getPreviewHTML()

Get the current preview element's HTML including all syntax markers.

Returns: string - Current preview HTML as displayed

ts
const previewHtml = editor.getPreviewHTML();

getCleanHTML()

Get clean HTML without any Marzipan-specific markup. Shorthand for getRenderedHTML({ cleanHTML: true }).

Returns: string - Clean HTML suitable for export

ts
const cleanHtml = editor.getCleanHTML();

// Same as:
const cleanHtml = editor.getRenderedHTML({ cleanHTML: true });

Focus Methods

focus()

Focus the editor textarea.

Returns: void

ts
editor.focus();

blur()

Remove focus from the editor textarea.

Returns: void

ts
editor.blur();

DOM Helpers

getContainer()

Get the root container element that wraps the toolbar, editor, and stats bar.

Returns: HTMLElement

ts
const container = editor.getContainer();
container.classList.add('rounded');

Display Mode Methods

showPlainTextarea(show?)

Toggle between plain textarea and overlay markdown preview.

Parameters:

  • show (boolean | undefined) - true for plain textarea, false for overlay preview. Omit the argument to query the current state.

Returns: boolean - Current plain textarea state

ts
// Show plain textarea (no markdown preview)
editor.showPlainTextarea(true);

// Show markdown overlay preview
editor.showPlainTextarea(false);

// Get current state
const isPlain = editor.showPlainTextarea();

showPreviewMode(show)

Toggle between edit and preview-only modes.

Parameters:

  • show (boolean) - true for preview-only, false for edit mode

Returns: boolean - Current preview mode state

ts
// Switch to preview-only mode (read-only)
editor.showPreviewMode(true);

// Switch back to edit mode
editor.showPreviewMode(false);

showStats(show)

Show or hide the statistics panel.

Parameters:

  • show (boolean) - Whether to show statistics

Returns: void

ts
// Show statistics panel
editor.showStats(true);

// Hide statistics panel
editor.showStats(false);

State Methods

updatePreview()

Manually trigger a markdown preview update. Usually called automatically on content changes.

Returns: void

ts
editor.updatePreview();

isInitialized()

Check if the editor is fully initialized and ready to use.

Returns: boolean - Initialization status

ts
if (editor.isInitialized()) {
  console.log('Editor is ready!');
  editor.setValue('# Hello');
}

reinit(options)

Re-initialize the editor with new options. Existing options are merged with new ones.

Parameters:

  • options (Object) - New options to apply

Returns: void

ts
editor.reinit({
  fontSize: '18px',
  theme: 'solar',
  toolbar: false
});

destroy()

Destroy the editor instance and clean up all resources, event listeners, and DOM elements.

Returns: void

ts
editor.destroy();

Cleanup

Always call destroy() when removing an editor to prevent memory leaks, especially in SPAs.

Static Methods

Marzipan.init(target, options)

Convenience method to create new instances. Equivalent to new Marzipan().

Parameters:

  • target (string | Element | NodeList | Array) - Target element(s)
  • options (Object) - Configuration options

Returns: Array<Marzipan> - Array of instances

ts
const editors = Marzipan.init('.markdown-editor', {
  toolbar: true
});

Marzipan.getInstance(element)

Get an existing Marzipan instance from a DOM element.

Parameters:

  • element (Element) - DOM element

Returns: Marzipan | null - Instance or null if not found

ts
const element = document.getElementById('my-editor');
const instance = Marzipan.getInstance(element);

if (instance) {
  console.log(instance.getValue());
}

Marzipan.destroyAll()

Destroy all existing Marzipan instances on the page.

Returns: void

ts
// Clean up all editors
Marzipan.destroyAll();

Marzipan.setTheme(theme, customColors?)

Set the global theme for all Marzipan instances.

Parameters:

  • theme (string | Object) - Theme name ('solar', 'cave') or custom theme object
  • customColors (Object) - Optional color overrides

Returns: void

ts
// Use built-in theme
Marzipan.setTheme('cave');

// Custom theme object
Marzipan.setTheme({
  name: 'ocean',
  colors: {
    bgPrimary: '#1a2332',
    bgSecondary: '#152033',
    text: '#d4e4f7',
    h1: '#5fb3d4',
    codeBg: 'rgba(95, 179, 212, 0.18)',
    toolbarBg: '#0f172a'
  }
});

// Override specific colors
Marzipan.setTheme('solar', {
  bgPrimary: '#fdf6e3',
  text: '#657b83'
});

See Themes Guide for complete color reference.


Marzipan.injectStyles(force?)

Manually inject Marzipan styles into the document. Usually called automatically.

Parameters:

  • force (boolean) - Force re-injection even if already injected (default: false)

Returns: void

ts
// Force style re-injection
Marzipan.injectStyles(true);

Properties

editor.element

The root DOM element containing the editor.

Type: HTMLElement

ts
editor.element.classList.add('custom-class');

editor.container

The editor's container element (includes toolbar, stats, etc.).

Type: HTMLElement

ts
const container = editor.container;

editor.textarea

The underlying textarea element.

Type: HTMLTextAreaElement

ts
// Add custom event listeners
editor.textarea.addEventListener('paste', (e) => {
  console.log('Content pasted');
});

// Access native properties
editor.textarea.selectionStart;
editor.textarea.selectionEnd;

editor.instanceId

Unique identifier for this editor instance.

Type: number

ts
console.log('Editor ID:', editor.instanceId);

editor.options

Current configuration options (read-only).

Type: Object

ts
console.log('Font size:', editor.options.fontSize);
console.log('Toolbar enabled:', editor.options.toolbar);

editor.toolbar

Reference to the toolbar instance (if toolbar is enabled).

Type: Toolbar | undefined

ts
if (editor.toolbar) {
  editor.toolbar.updateButtonStates();
}

editor.shortcuts

Reference to the shortcuts manager instance.

Type: ShortcutsManager

ts
// Access shortcuts manager
console.log(editor.shortcuts);

Complete Example

ts
import { Marzipan, actions } from '@pinkpixel/marzipan';
import { tablePlugin } from '@pinkpixel/marzipan/plugins/tablePlugin';

// Create editor with full configuration
const [editor] = new Marzipan('#editor', {
  // Typography
  fontSize: '16px',
  lineHeight: 1.6,
  padding: '20px',
  
  // Behavior
  autofocus: true,
  autoResize: true,
  minHeight: '300px',
  maxHeight: '800px',
  placeholder: 'Start writing...',
  smartLists: true,
  
  // Features
  toolbar: true,
  showStats: true,
  theme: 'cave',
  
  // Initial content
  value: '# Welcome\n\nStart writing your markdown!',
  
  // Callbacks
  onChange: (value, instance) => {
    console.log('Content changed');
    localStorage.setItem('draft', value);
  },
  
  onKeydown: (event, instance) => {
    if ((event.ctrlKey || event.metaKey) && event.key === 's') {
      event.preventDefault();
      console.log('Save shortcut pressed');
    }
  },
  
  // Plugins
  plugins: [tablePlugin()]
});

// Use the editor
console.log('Initial content:', editor.getValue());

// Set new content
editor.setValue('# Updated Content');

// Get HTML
const html = editor.getCleanHTML();

// Focus editor
editor.focus();

// Toggle modes
editor.showPreviewMode(true);  // Preview only
editor.showPlainTextarea(true); // Plain textarea

// Use actions
actions.toggleBold(editor.textarea);
actions.insertLink(editor.textarea, { 
  url: 'https://example.com',
  text: 'Click here'
});

// Cleanup when done
editor.destroy();

See Also

Released under the Apache 2.0 License