API Reference

EditorManager

The core class for creating and managing editor instances.

EditorManager.create(element, config?)

The ? in the signature means the parameter is optional.

Creates an EditorManager instance and initializes the editor inside the given DOM container.

  • element: the HTML element (HTMLElement) to mount the editor on.
  • config: optional editor configuration object; all fields are optional.
  • Returns: an EditorManager instance. Access the underlying editor via manager.getEditor().
const manager = EditorManager.create(
  document.querySelector('#editor'),
  {
    // ——— Dimensions ———
    height: '400px',
    minHeight: '200px',
    maxHeight: '800px',
    autoHeight: false,
    // ——— Basics ———
    placeholder: 'Start writing...',
    readonly: false,
    disabled: false,
    autofocus: false,
    locale: 'en-US',
    // ——— Toolbar (insert '|' in the array for a visual separator) ———
    toolbar: [
      'undo', 'redo', 'formatPainter', '|',
      'bold', 'italic', 'underline', 'strikethrough',
      'superscript', 'subscript', '|',
      'fontFamily', 'fontSize', 'color', 'bgColor', '|',
      'heading', 'align', 'lineHeight',
      'bulletList', 'orderedList', 'outdent', 'indent', '|',
      'link', 'insertTable', 'imageUpload', 'video', '|',
      'blockquote', 'codeBlock', '|',
      'import', 'export', 'getHTML', 'getJSON', '|',
      'fullscreen', 'snapshot', 'compare',
    ],
    // ——— Paste ———
    paste: {
      mode: 'rich',           // 'rich' | 'html' | 'text'
      retainStyle: true,
      filterTags: ['script', 'style'],
      imageUpload: true,
      maxImageSize: 5 * 1024 * 1024,
      // onBeforePaste: (event, html) => html,  // Return modified HTML / false to cancel
      // onAfterPaste: (html) => {},             // Paste complete callback
    },
    // ——— Image upload (only url is required) ———
    upload: {
      url: '/api/upload',
      headers: { Authorization: 'Bearer ...' },
      fieldName: 'file',
      maxSize: 10 * 1024 * 1024,
      accept: 'image/*',
      multiple: true,
      // onUpload: (file) => Promise.resolve(url),  // Custom upload, overrides url
    },
    // ——— Version compare / snapshots (requires ProRevision plugin) ———
    compare: {
      autoBaseline: true,
      baselineLabel: 'Session baseline',
      maxVersions: 50,
      changeThreshold: 10,
      maxIntervalMs: 300000,
      triggers: { blur: true, paste: true, import: true, interval: true },
    },
    // ——— License (activates Pro features) ———
    license: {
      key: 'your-license-jwt',
      appId: 'my-app-id',
      online: 'lazy',         // false | 'lazy' | 'strict'
      offlineGraceDays: 14,
      fallback: 'watermark',  // 'watermark' | 'readonly' | 'block'
      // apiBase: 'https://api.cyteeditor.com',
      // jwksUrl: 'https://api.cyteeditor.com/.well-known/jwks.json',
    },
    // ——— Pro plugins (registered before creation) ———
    plugins: [
      ProPaste(),
      ProExport(),
      ProRevision(),
    ],
  }
)

EditorConfig

All options are optional unless otherwise noted.

OptionTypeDefaultDescription
heightstring | number300pxEditor height. Accepts CSS values (e.g. 400px, 50vh) or a number (treated as px).
minHeightstring | number150pxMinimum editor height. Same format as height.
maxHeightstring | numberMaximum editor height. When set, the editor shows a scrollbar if content exceeds this value.
autoHeightbooleanfalseWhen true, the editor automatically resizes to fit its content, up to maxHeight.
placeholderstring``Placeholder text displayed when the editor is empty.
readonlybooleanfalseWhen true, the editor enters read-only mode — content is visible but not editable.
disabledbooleanfalseWhen true, the editor is fully disabled — toolbar and editing are inactive.
autofocusbooleanfalseWhen true, the editor automatically receives focus after mounting.
localestringzh-CNUI language locale code. If an unrecognized code is passed, the current locale is kept unchanged; the initial locale is zh-CN. Custom locales can be registered at runtime via I18nManager.getInstance().registerLocale(code, messages). See the locale mapping table below.
toolbarToolbarItem[]default setArray of toolbar item names. When not set, the default toolbar is used; available items and the '|' separator syntax are described in ToolbarItem.
pastePasteConfigPaste behavior configuration. Controls paste mode (rich text / raw HTML / plain text), inline style retention, automatic upload of pasted images, etc. See PasteConfig.
uploadUploadConfigImage upload configuration. Set url to enable server-side uploads; when not set, images are embedded as Base64. See UploadConfig for the server response format.
compareCompareConfigVersion compare and snapshot configuration for content versioning and diffing. Requires ProRevision() to be registered via plugins, and a valid Pro license to take effect. See CompareConfig.
licenseLicenseConfigLicense key configuration for activating Pro features (e.g. Word import/export, version snapshots, advanced paste). A license key is obtained after purchasing a Pro subscription — see the pricing page. See LicenseConfig.
pluginsProPlugin[]Array of Pro plugins to register before editor creation; a valid Pro license is required to activate them. Available plugins: ProPaste(), ProExport(), ProRevision(). Can also be registered dynamically after creation via manager.use(plugin).

Pro features: The compare, license, and plugins parameters, as well as the import, export, snapshot, and compare toolbar buttons, require a valid Pro license — see the pricing page.

Locale Mapping

CodeLanguage
zh-CNSimplified Chinese
zh-TWTraditional Chinese
en-USEnglish
jaJapanese
ko-KRKorean
fr-FRFrench
deGerman
esSpanish
pt-BRPortuguese (Brazil)
ruRussian

Default Toolbar

When toolbar is not provided, the editor uses the following default set. Free and Pro versions use the same array; Pro-only items are disabled when no valid license is present.

[
  'undo', 'redo', 'formatPainter', '|',
  'bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', '|',
  'fontFamily', 'fontSize', 'color', 'bgColor', '|',
  'heading', 'align', 'lineHeight', 'bulletList', 'orderedList', 'outdent', 'indent', '|',
  'link', 'insertTable', 'imageUpload', 'video', '|',
  'blockquote', 'codeBlock', '|',
  'import', 'export', 'getHTML', 'getJSON', '|',
  'fullscreen', 'snapshot', 'compare',
]

ToolbarItem

toolbar is an array of strings, each representing a toolbar button or control.

Visual separator: Insert the string '|' in the array to display a vertical divider between adjacent button groups. For example, ['bold', 'italic', '|', 'undo'] places a separator between "Bold / Italic" and "Undo". '|' is not a button — it is used solely for visual grouping.

import and export are dropdown groups. Their children importWord, importMarkdown, exportWord, and exportMarkdown are not top-level ToolbarItem values.

ValueTypeLicenseDescription
undobuttonFreeUndo
redobuttonFreeRedo
formatPainterbuttonFreeFormat painter
boldbuttonFreeBold text
italicbuttonFreeItalic text
underlinebuttonFreeUnderline text
strikethroughbuttonFreeStrikethrough text
superscriptbuttonFreeSuperscript
subscriptbuttonFreeSubscript
fontFamilydropdownFreeFont family selector
fontSizedropdownFreeFont size selector
colorcolor-pickerFreeText color picker
bgColorcolor-pickerFreeBackground/highlight color picker
headingdropdownFreeHeading level selector
aligndropdownFreeText alignment
lineHeightdropdownFreeLine height
bulletListbuttonFreeBullet list
orderedListbuttonFreeOrdered list
outdentbuttonFreeDecrease indent
indentbuttonFreeIncrease indent
linkbuttonFreeInsert/edit link
insertTablebuttonFreeInsert table
imageUploaddropdownFreeInsert image
videobuttonFreeInsert video
blockquotebuttonFreeBlockquote
codeBlockbuttonFreeCode block
importdropdownProImport (Word / Markdown)
exportdropdownProExport (Word / Markdown)
getHTMLbuttonFreeView HTML source
getJSONbuttonFreeView JSON structure
fullscreenbuttonFreeToggle fullscreen
snapshotbuttonProCreate version snapshot
comparebuttonProVersion compare

PasteConfig

OptionTypeDefaultDescription
mode'rich' | 'html' | 'text'richPaste mode. rich retains rich-text formatting; html keeps raw HTML; text strips all formatting.
retainStylebooleantrueWhether to retain inline styles from pasted content.
filterTagsstring[]['script', 'style']List of HTML tag names to strip from pasted content.
imageUploadbooleantrueWhen true, pasted images are automatically uploaded using the upload config.
maxImageSizenumber5242880Maximum image file size in bytes (default: 5 MB). Images exceeding this limit are rejected.
onBeforePasteFunction(event: ClipboardEvent, html: string) => string | false | void Callback invoked before paste. Return modified HTML to transform, false to cancel, or void to proceed.
onAfterPasteFunction(html: string) => void Callback invoked after paste with the final inserted HTML.

UploadConfig

OptionTypeDefaultDescription
urlstring''Your own image upload service endpoint URL. The editor sends images to this address via HTTP POST multipart/form-data. When not set, images are embedded as Base64 — no upload service required.

Server response format

After a successful upload (HTTP 2xx), the server should return the following JSON format:

FieldTypeDescription
statusnumberBusiness status code, 200 for success
data.urlstringImage URL after successful upload

Response example

{
  "status": 200,
  "data": {
    "url": "https://cdn.example.com/img/abc.png"
  }
}

CompareConfig

OptionTypeDefaultDescription
autoBaselinebooleantrueAutomatically create a baseline snapshot when content is present.
baselineLabelstring会话基线Label for the auto-created baseline snapshot.
maxVersionsnumber50Maximum number of snapshots to keep.
changeThresholdnumber10Minimum character difference to trigger a new snapshot.
maxIntervalMsnumber300000Maximum time in ms between automatic snapshots (default: 5 minutes).
triggersobjectAll enabledEnable/disable specific snapshot triggers: blur, paste, import, interval (all boolean, default true).

LicenseConfig

OptionTypeDefaultDescription
keystringLicense JWT key, issued after purchase. Required to activate Pro features.
appIdstringApplication ID for multi-app licensing scenarios.
onlinestringlazyOnline verification strategy. false = offline only; lazy = verify when possible; strict = must verify online.
offlineGraceDaysnumber14Grace period in days for offline use under strict mode.
fallbackstringwatermarkDegradation behavior when license verification fails. watermark = editable with watermark overlay; readonly = read-only mode; block = block all editing.
apiBasestringCustom Worker API base URL for OEM / private deployments.
jwksUrlstringJWKS endpoint URL. Must use https:// and domain must be in *.cyteeditor.com whitelist.

Instance Methods

Getting the editor instance

The following methods are all defined on the EditorManager instance. Each adapter obtains this instance differently:

  • Vanilla: EditorManager.create() returns the EditorManager instance directly; all methods can be called directly.
  • Vue3 / Vue2 / React / Angular / Svelte: the component ref exposes a subset of common methods directly; to call the full method set, first obtain the EditorManager instance via the ref's getEditorManager().

Vanilla

import { EditorManager } from '@cyte-editor/core'

const manager = EditorManager.create(document.querySelector('#editor'), { /* config */ })
manager.getHTML()          // direct call
manager.insertTable(2, 3)  // direct call

Vue 3

<script setup>
import { ref } from 'vue'
import { CyteEditor } from '@cyte-editor/vue3'
import type { CyteEditorExpose } from '@cyte-editor/vue3'

const editorRef = ref<CyteEditorExpose>()

// Common methods can be called directly via ref
editorRef.value?.getHTML()

// Full method set requires getting the instance via getEditorManager()
const manager = editorRef.value?.getEditorManager()
manager?.insertTable(2, 3)
</script>

<template>
  <CyteEditor ref="editorRef" v-model:html="content" />
</template>

Vue 2

<script>
export default {
  methods: {
    doSomething() {
      // Common methods
      this.$refs.editor.getHTML()
      // Full method set
      this.$refs.editor.getEditorManager()?.insertTable(2, 3)
    },
  },
}
</script>

React

import { useRef } from 'react'
import { CyteEditor } from '@cyte-editor/react'
import type { CyteEditorHandle } from '@cyte-editor/react'

function App() {
  const editorRef = useRef<CyteEditorHandle>(null)

  const doSomething = () => {
    // Common methods
    editorRef.current?.getHTML()
    // Full method set
    editorRef.current?.getEditorManager()?.insertTable(2, 3)
  }

  return <CyteEditor ref={editorRef} html={content} onChange={({ html }) => setContent(html)} />
}

Angular

import { ViewChild } from '@angular/core'
import { CyteEditorComponent } from '@cyte-editor/angular'

export class AppComponent {
  @ViewChild('editor') editor!: CyteEditorComponent

  doSomething() {
    // Common methods
    this.editor.getHTML()
    // Full method set
    this.editor.getEditorManager()?.insertTable(2, 3)
  }
}
// Template: <cyte-editor #editor [html]="content" (onChange)="content = $event.html"></cyte-editor>

Svelte

<script>
  import { CyteEditor } from '@cyte-editor/svelte'
  import type { CyteEditorApi } from '@cyte-editor/svelte'

  let editor: CyteEditorApi

  function doSomething() {
    // Common methods
    editor.getHTML()
    // Full method set
    editor.getEditorManager()?.insertTable(2, 3)
  }
</script>

<CyteEditor bind:this={editor} html={content} onChange={(e) => (content = e.html)} />

In the examples below, manager refers to the EditorManager instance obtained in the previous step (the return value of EditorManager.create() for Vanilla, or getEditorManager() for other frameworks).

Content operations

MethodReturnsDescription
getHTML()stringGet the editor content as an HTML string. Useful for saving content to a backend, rendering to a page, or copying to the clipboard.
getJSON()JSONContentGet the editor content as JSON data. Useful for serializing content for storage or transferring between editor instances, preserving all formatting and marks.
getText()stringGet the editor content as plain text, without any HTML tags or formatting marks. Useful for word counting, search indexing, or plain-text export.
setContent(html)voidReplace the entire editor content with an HTML string. Useful for initializing the editor, resetting content, or loading data from a backend. The cursor moves to the beginning of the document after calling.
setJSON(json)voidReplace the entire editor content with JSON data. Useful for restoring content previously serialized via getJSON(), preserving all formatting and marks.
insertHTML(html)voidInsert an HTML fragment at the current cursor position without replacing existing content. Useful for template insertion, drag-and-drop content, or appending HTML from an external source.
insertText(text)voidInsert plain text at the current cursor position. The inserted content carries no formatting, useful for pasting unformatted text or programmatic input.
isEmpty()booleanCheck whether the editor has no content at all. Useful for validating required fields before form submission, or controlling the disabled state of a submit button.
clear()voidRemove all content from the editor. Useful for form reset or content initialization scenarios.
// Read content
const html = manager.getHTML()
const json = manager.getJSON()

// Replace content
manager.setContent('<p>New content</p>')

// Clear
manager.clear()

State and focus

MethodReturnsDescription
focus()voidSet focus to the editor. Useful for auto-focusing after page load, guiding input after opening a modal, or switching focus back from other UI elements.
blur()voidRemove focus from the editor. Useful for triggering auto-save on blur, or actively removing focus when switching to another input area.
setReadonly(value)voidToggle the editor's read-only mode. Pass true to enter read-only (content is visible but not editable), false to restore editing. Useful for document preview, review mode, or permission-based access control.
isActive(name, attributes?)booleanCheck whether the current selection is in a specific format or block element, returning a boolean. name is a registered format or element name. Marks: 'bold', 'italic', 'underline', 'strike', 'code', 'link', 'highlight', 'superscript', 'subscript'. Nodes: 'paragraph', 'heading', 'bulletList', 'orderedList', 'listItem', 'blockquote', 'codeBlock', 'table', 'tableRow', 'tableCell', 'tableHeader', 'image', 'video', 'horizontalRule', 'taskList', 'taskItem'. Optional attributes for precise matching (e.g. specify heading level). Commonly used to sync toolbar button active states.
manager.focus()
manager.setReadonly(true)   // Enter readonly
manager.setReadonly(false)  // Exit readonly

// Check whether the current selection is bold
manager.isActive('bold')

History

MethodReturnsDescription
undo()voidUndo the last editing operation. Useful for custom undo button binding or keyboard shortcut handling.
redo()voidRedo the last undone operation. Useful for custom redo button binding or keyboard shortcut handling.
manager.undo()  // Undo
manager.redo()  // Redo

Plugins, commands and internal access

MethodReturnsDescription
use(plugin)thisRegister a Pro plugin (e.g. ProExport, ProPaste, ProRevision), returning the instance itself for chaining. The corresponding plugin package must be imported before calling.
registerExtension(ext)voidRegister an editor extension. Usually called internally by Pro plugins; manual use is only needed when developing custom extensions.
executeCommand(command, ...args)booleanExecute a registered editor command. command is the command name in camelCase (e.g. 'toggleBold', 'toggleItalic', 'toggleHeading'). Useful for custom toolbar button binding, keyboard shortcut handling, or programmatically triggering edit operations. When a dedicated instance method exists (e.g. insertTable(), setTableBorder()), prefer using it instead.
getConfig()EditorConfigGet the current editor configuration object. Useful for reading effective config values at runtime, such as locale or height constraints.
getI18n()I18nManagerGet the i18n manager instance. Useful for dynamically switching languages or reading the current locale at runtime.
getEditor()EditorGet the underlying editor instance. Useful for advanced scenarios that require direct access to the internal API; not typically needed in normal development.
// Register a Pro plugin at runtime (equivalent to config.plugins at creation)
// import { ProExport } from '@cyte-editor/pro-export'
manager.use(ProExport())  // Import the plugin first

// Execute an editor command
manager.executeCommand('toggleBold')

// Get the underlying editor instance and current config
const editor = manager.getEditor()
const config = manager.getConfig()

Tables

MethodReturnsDescription
insertTable(rows?, cols?, withHeaderRow?)voidInsert a table at the cursor position. Optional parameters specify the number of rows, columns, and whether to include a header row; defaults to a 3×3 table with a header row.
addTableRowBefore()voidInsert a new row above the current cursor row.
addTableRowAfter()voidInsert a new row below the current cursor row.
addTableColumnBefore()voidInsert a new column to the left of the current cursor column.
addTableColumnAfter()voidInsert a new column to the right of the current cursor column.
deleteTableRow()voidDelete the entire row where the cursor is located.
deleteTableColumn()voidDelete the entire column where the cursor is located.
deleteTable()voidDelete the entire table where the cursor is located, including all rows, columns, and cell content.
mergeCells()voidMerge the currently selected cells into one. Requires selecting two or more adjacent cells before calling.
splitCell()voidSplit a previously merged cell back into its original individual cells.
setTableBorder({ color?, width?, style? })voidSet the border style for all tables in the document. color is a CSS color value (e.g. '#ccc'), defaulting to '#d9d9d9'; width is a CSS width string (e.g. '1px'), defaulting to '1px'; style is the border line style, supporting 'solid', 'dashed', 'dotted', 'double', 'groove', 'ridge', 'inset', 'outset', 'none', 'hidden', defaulting to 'solid'.
setCellTextAlign(align)voidSet the text alignment of the selected cells. Accepts 'left', 'center', 'right', or 'justify'.
// Insert a 3×4 table with header row at cursor
manager.insertTable(3, 4, true)

// Set table border
manager.setTableBorder({ color: '#ccc', width: 1 })

Media insertion

MethodReturnsDescription
insertImage(src, alt?, title?)voidInsert an image at the cursor position. The first parameter is the image URL (required); the next two are alt text and hover tooltip (optional).
insertVideo(src, width?, height?)voidInsert a video at the cursor position. The first parameter is the video URL (required); the next two are width and height in pixels (optional).
manager.insertImage('/assets/logo.png', 'Logo', 'Company logo')
manager.insertVideo('/assets/demo.mp4', 640, 360)

Import and export

MethodReturnsDescription
parseHTML(html)JSONContentParse an HTML string into JSON data without modifying the editor content. Useful for preprocessing, content validation, or programmatic analysis of external HTML.
importHTMLFile(file)Promise<void>Import an HTML file (File object), asynchronous. Useful when users upload .html files via a file picker.
importMarkdownFile(file)Promise<void>Import a Markdown file (File object), asynchronous. Useful when users upload .md files via a file picker.
importMarkdown(markdown)voidImport a Markdown string, synchronous. Useful for loading Markdown content directly from an API or local variable.
importWordFile(file)Promise<{ messages: string[] }>Import a Word (.docx) file (File object), asynchronous. Returns a { messages } object containing warnings or hints from the import process (e.g. unsupported formatting). Commonly used for document migration.
exportMarkdown()stringExport the editor content as a Markdown string. Useful for sending content via API, storing in a database, or using in another Markdown system.
exportHTMLDocument(title?)stringExport as a full HTML document string (including <html>, <head>, <body> tags). The optional parameter specifies the document title. Useful for print preview or saving as an HTML file.
exportWordFile(filename?)Promise<void>Export the editor content as a Word (.docx) file and trigger a browser download. The optional parameter specifies the filename, defaulting to document.docx.
exportMarkdownFile(filename?)Promise<void>Export the editor content as a Markdown file and trigger a browser download. The optional parameter specifies the filename, defaulting to document.md.
getDocumentTitle()stringAutomatically extract the document title from the current editor content (typically the text of the first heading node). Useful for auto-generating filenames or page titles.
// Export as Word file (async, requires ProExport plugin)
await manager.exportWordFile('document.docx')

// Export as Markdown string (sync)
const md = manager.exportMarkdown()

// Extract document title
const title = manager.getDocumentTitle()

// Import a Markdown file (async)
const file = new File(['# Title\nBody'], 'note.md', { type: 'text/markdown' })
await manager.importMarkdownFile(file)

Version snapshots (Pro)

MethodReturnsDescription
enableVersionSnapshot(config?)voidEnable version snapshot management (requires ProRevision plugin). Must be called once before first use; optional parameters configure max snapshot count and other options.
listVersions()Promise<VersionSnapshot[]>Get all snapshots, ordered newest first. Useful for rendering a version history panel.
getVersion(id)Promise<VersionSnapshot | null>Get a specific snapshot by ID, returning a VersionSnapshot object or null if not found. Useful for previewing historical version content.
deleteVersion(id)Promise<void>Delete a snapshot by ID. Useful when users want to clean up no longer needed historical versions.
addSnapshot(content, label?)Promise<VersionSnapshot | null>Import an external snapshot (JSON data). Useful for injecting a previously saved version on page load, enabling cross-session version recovery.
createSnapshot(label?)Promise<VersionSnapshot | null>Create a snapshot based on the current editor content. Useful when users click a "Save Version" button. Asynchronous, returns the created snapshot or null.
hasSnapshots()Promise<boolean>Check whether any snapshots exist. Useful for deciding whether to display a "Version History" entry in the UI.
compareWithVersion(versionId)Promise<DiffResult | null>Compare the current editor content with a specific snapshot, returning a DiffResult object. Useful for showing "changes since last save".
compareVersions(oldVersionId, newVersionId)Promise<DiffResult | null>Compare two snapshots against each other, returning a DiffResult object. Useful for browsing version history and viewing changes between any two versions.
// Create a snapshot manually (async)
const snap = await manager.createSnapshot('v1.0')

// Compare current content with a snapshot (async)
const diff = await manager.compareWithVersion(snap.id)

// Compare two snapshots (async)
const diff2 = await manager.compareVersions(oldId, newId)

License and lifecycle

MethodReturnsDescription
updateLicense(opts)voidUpdate the license configuration at runtime and re-verify. Useful when users upgrade their plan (e.g. Free to Pro) within the app, enabling new features without a page refresh.
destroy()voidClean up editor resources and destroy the instance. Should be called during component unmounting in single-page applications to prevent memory leaks and lingering event listeners.
// Update license at runtime and re-verify
manager.updateLicense({ key: 'new-jwt', appId: 'my-app' })

// Destroy the instance and release resources
manager.destroy()

Events

Subscribe with manager.on(event, handler), unsubscribe with manager.off(event, handler).

EventPayloadDescription
create{ editor }Editor created.
update{ editor, html }Content changed.
selectionUpdate{ editor }Selection changed.
transaction{ editor }Any transaction applied.
focus{ editor, event }Editor focused.
blur{ editor, event }Editor blurred.
destroyEditor destroyed.
license:verifiedLicenseVerifyEventLicense check complete.
license:error{ error }License check failed.