Back

VibeFox JS Editor — Help

Overview

VibeFox JS Editor is a rich text (WYSIWYG) editor for web applications: formatting, lists, tables, images and files, embeds, code with syntax highlighting, formulas, track changes, comments, versions, real-time collaboration, an AI assistant on your own model, a page view like a word processor, and export to PDF, Word (.docx) and Markdown. It is plain JavaScript with no dependencies and works with or without a framework.

You create an editor with one call, createEditor(target, options), and control it through the same methods as every VibeFox JS library: setData, setOptions, on, getState, setState, setTheme, destroy. The content is HTML: getData() returns clean, sanitized HTML.

Key features

  • Text: headings, bold, italic, underline, strikethrough, inline code, subscript / superscript, fonts, sizes, colors, line spacing, indent, alignment, left-to-right and right-to-left paragraphs, links, quotes, rules, special characters and emoji.
  • Lists and checklists, tables with merged cells, column resizing and cell properties.
  • Images and files with your upload adapter (picker, drag and drop, clipboard, progress), YouTube / Vimeo and other embeds without network requests until you allow them.
  • Code blocks with highlighting for 16 languages, LaTeX formulas shown as MathML.
  • Slash menu, Markdown shortcuts while typing, smart typography, @-mentions, find and replace, autosave, HTML source view, outline, focus mode.
  • Track changes (suggestions with authors), comment threads, version history with a visual comparison, real-time collaboration with cursors of the other participants.
  • Export to PDF (vector, selectable text), Word .docx (with revisions and comments), HTML and Markdown; import of Word .docx and Markdown; a page view with headers, footers and printing.
  • Three modes (classic toolbar, inline, balloon), one toolbar for several editors, your own blocks and inline nodes.
  • An AI assistant (rewrite, grammar, translate, summarize, continue, your own commands) on your model adapter; tools for language model agents.
  • An accessibility checker with quick fixes, three ready-made styles, every color and size as a CSS variable, themes, right-to-left editing, full keyboard access and screen reader texts.

Requirements

  • A current web browser. Colors of code blocks, find matches and the current suggestion use the CSS Custom Highlight API; without it the text is shown without these colors.
  • No runtime dependencies. The editor makes no network requests of its own: uploads go to your adapter, embeds load only with embed.live: true, the AI assistant calls your adapter, collaboration uses your transport (or the tabs of one browser).
  • Node.js is not needed in the browser. The ES module can be imported in Node (no DOM is touched at import): sanitizeHtml, markdownToHtml, docxToHtml, diffHtml, latexToMathML, checkLatex, checkHtmlAccessibility, tokenizeCode and RtcDoc (a collaboration room on a server) run without a DOM.

Installation

Files of the library

VibeFox JS Editor is a separate product with its own files. The whole JavaScript of the library is one file and the styles are one CSS file: a page needs exactly these two. The other files are optional.

FileWhat it is
vibefox-js-editor.global.jsThe library for a classic <script> tag; defines one global variable, VibeFoxJSEditor. Minified: vibefox-js-editor.global.min.js.
vibefox-js-editor.esm.jsThe same code as an ES module. Minified: vibefox-js-editor.esm.min.js.
vibefox-js-editor.cssAll styles of the library, inside @layer vfjs; includes the themes light, dark and high-contrast. Minified: vibefox-js-editor.min.css.
vibefox-js-themes.cssOptional theme pack: 18 ready-made themes (see Theming and styling). Minified: vibefox-js-themes.min.css.
locales/vibefox-js-editor.<lang>.jsOptional language files, one for each language except English (see Localization and RTL). The same language as an ES module: .esm.js; as plain strings: .json.
vibefox-js-editor.d.tsTypeScript declarations (also vibefox-js-editor.esm.d.ts).
*.js.mapSource maps.
vibefox-js-editor-react.js, vibefox-js-editor-vue.js, vibefox-js-editor-svelte.js, vibefox-js-editor-jquery.jsOptional framework wrappers (each with its .d.ts).
vibefox-js-editor-angularOptional Angular package (Angular Package Format).
vibefox-js-editor-wc.jsOptional Web Components wrapper (custom elements).

Script tag

Link the CSS file and the script. The global variable VibeFoxJSEditor holds every export of the library. This also works from a file opened from disk (file://).

<link rel="stylesheet" href="vibefox-js-editor.css">
<script src="vibefox-js-editor.global.js"></script>
<script>
  const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>Hello</p>' });
</script>

ES module

Import the ES module file and link the CSS file. Browsers load modules only over http(s), not from file://.

<link rel="stylesheet" href="vibefox-js-editor.css">
<script type="module">
  import { createEditor } from './vibefox-js-editor.esm.js';
  const editor = createEditor('#app', { data: '<p>Hello</p>' });
</script>

npm

The library is also prepared as an npm package named @vibefox/js-editor. Install it from the package folder (or its packed .tgz file) that you received, then import it by name. Bundlers take the CSS through the @vibefox/js-editor/css export.

npm install ./vibefox-js-editor
import { createEditor } from '@vibefox/js-editor';
import '@vibefox/js-editor/css';

Exports of the package: @vibefox/js-editor (ES module), @vibefox/js-editor/min, @vibefox/js-editor/global, @vibefox/js-editor/global.min, @vibefox/js-editor/css, @vibefox/js-editor/min.css, @vibefox/js-editor/themes, @vibefox/js-editor/themes.min.css, @vibefox/js-editor/locales/<lang>, @vibefox/js-editor/locales/<lang>.json. TypeScript finds the declarations by itself.

Framework wrappers

The wrappers are small separate files; the library works without them. Each wrapper needs only VibeFox JS Editor and its framework (a peer dependency). The wrappers do not load CSS: link vibefox-js-editor.css yourself.

FrameworkFilenpm packageSupported versions
Reactvibefox-js-editor-react.js@vibefox/js-editor-reactReact 16.8 and newer
Vue 3vibefox-js-editor-vue.js@vibefox/js-editor-vueVue 3.3 and newer
Angularvibefox-js-editor-angular@vibefox/js-editor-angularAngular 17 and newer
Sveltevibefox-js-editor-svelte.js@vibefox/js-editor-svelteSvelte 3, 4 and 5
jQueryvibefox-js-editor-jquery.js@vibefox/js-editor-jqueryjQuery 1.12 to 4.x
Web Componentsvibefox-js-editor-wc.js@vibefox/js-editor-wcno framework

The ES module wrappers import the library as @vibefox/js-editor. Without npm, map that name to vibefox-js-editor.esm.js in your bundler settings or in an import map. The jQuery wrapper takes the library from the global VibeFoxJSEditor.

Common rules of all wrappers: props / inputs are the options of the library (changed ones go to setData or one setOptions call); events are framework events with the same payload object as on(); the instance is available for every method; on the server (SSR) an empty container is rendered and the instance is created in the browser only. The option style (ready-made look) is the prop variant in React, Vue, Svelte and Angular, because style and className / class belong to the host element.

Web Components

Load vibefox-js-editor-wc.js after the library file. It defines the element <vfjs-editor> from the global VibeFoxJSEditor. Attributes are options in kebab-case (JSON for objects and arrays), properties are options, the methods of the component are methods of the element, events are CustomEvents named vfjseditor:<event> with the payload in detail. The element uses the light DOM, so the CSS of the library and your page CSS apply as usual.

<link rel="stylesheet" href="vibefox-js-editor.css">
<script src="vibefox-js-editor.global.js"></script>
<script type="module" src="vibefox-js-editor-wc.js"></script>
<vfjs-editor id="g" toolbar="basic" placeholder="Write here…"></vfjs-editor>
<script>
  const el = document.getElementById('g');
  el.data = '<p>Hello <b>world</b></p>';
  el.addEventListener('vfjseditor:change', (e) => console.log(e.detail.html));
</script>

With a bundler: import * as lib from '@vibefox/js-editor'; import { define } from '@vibefox/js-editor-wc'; define(lib);

Quick start

Plain HTML

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="vibefox-js-editor.css">
  <script src="vibefox-js-editor.global.js"></script>
</head>
<body>
  <div id="app"></div>
  <script>
    const editor = VibeFoxJSEditor.createEditor('#app', {
      data: '<h2>Release notes</h2><p>Type <b>/</b> for blocks, or use the toolbar.</p>',
      toolbar: 'full',
      placeholder: 'Start typing…',
      on: { change: (e) => console.log(e.html) },
    });
  </script>
</body>
</html>

The editor takes the width of its element and grows with the text (option minHeight, default 180 px; maxHeight makes it scroll).

React

import { useRef, useState } from 'react';
import { VibeFoxJSEditorReact } from '@vibefox/js-editor-react';
import '@vibefox/js-editor/css';

export function Notes() {
  const editor = useRef(null); // the VibeFoxJSEditor instance
  const [html, setHtml] = useState('<p>Hello</p>');
  return (
    <>
      <VibeFoxJSEditorReact ref={editor} data={html} toolbar="basic" onChange={(e) => setHtml(e.html)} />
      <button onClick={() => editor.current.exportPDF('notes.pdf')}>PDF</button>
    </>
  );
}

Vue 3

<script setup>
import { ref } from 'vue';
import { VibeFoxJSEditorVue } from '@vibefox/js-editor-vue';
import '@vibefox/js-editor/css';
const html = ref('<p>Hello</p>');
</script>
<template>
  <VibeFoxJSEditorVue v-model="html" toolbar="basic" @word-count-change="(e) => console.log(e.words)" />
</template>

v-model is the HTML (data); v-model:pages follows the page view.

Angular

import { Component } from '@angular/core';
import { VibeFoxJSEditorComponent } from '@vibefox/js-editor-angular';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [VibeFoxJSEditorComponent],
  template: `
    <vfjs-editor-ng #ed [data]="html" toolbar="basic" (change)="changed($event)"></vfjs-editor-ng>
    <button (click)="ed.instance?.exportDOCX('notes.docx')">Word</button>`,
})
export class AppComponent {
  html = '<p>Hello</p>';
  changed(e: { html: string }) { console.log(e.html); }
}

Link vibefox-js-editor.css in angular.json (styles) or in index.html. For NgModule applications import VibeFoxJSEditorModule.

Svelte

<script>
  import { vfjsEditor } from '@vibefox/js-editor-svelte';
  let html = '<p>Hello</p>';
</script>
<div use:vfjsEditor={{ data: html, toolbar: 'basic' }}
     on:vfjseditor:change={(e) => (html = e.detail.html)}></div>

jQuery

<script src="jquery.min.js"></script>
<link rel="stylesheet" href="vibefox-js-editor.css">
<script src="vibefox-js-editor.global.js"></script>
<script src="vibefox-js-editor-jquery.js"></script>
<script>
  $('#notes').vfjsEditor({ data: '<p>Hello</p>', toolbar: 'basic' })
    .on('vfjseditor:change', (e, payload) => console.log(payload.html));
  const html = $('#notes').vfjsEditor('getData');
</script>

Core concepts

Content

The content is HTML. setData(html) and the option data sanitize it with an allow-list (scripts, event handlers, unknown tags and unsafe URLs are removed; option sanitize, default true); getData() returns clean HTML, getText() the plain text, getWordCount() the counts. Every change emits change ({ html, source }) and is one undo step.

Creating and destroying

const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>Hello</p>', toolbar: 'basic' });
editor.setData('<h2>Title</h2><p>Text</p>');
console.log(editor.getData(), editor.getText(), editor.getWordCount().words);
editor.setOptions({ readonly: true, placeholder: 'Read only' });
editor.setOption('maxHeight', '400px');
editor.destroy();

new VibeFoxJSEditor(target, options) is the same as createEditor. editor.content is the editable element.

Commands

exec(name, value) runs a command on the selection or the block at the caret (one undo step); isActive(name) tells whether it applies at the caret (bold text, a heading …). transact(fn) makes several changes one undo step; insertHTML() and insertText() insert at the caret.

editor.focus();
editor.exec('h2');
editor.exec('bold');
editor.exec('table', { rows: 3, cols: 3, header: true });
editor.exec('link', { href: 'https://example.com', text: 'Example', newTab: true });
editor.exec('textColor', '#2563eb');
editor.transact(() => { editor.insertText('Done. '); editor.insertHTML('<i>Thanks</i>'); });
console.log(editor.isActive('bold'), editor.canUndo());

Commands: p, h1 … h4, quote, codeBlock, bold, italic, underline, strike, code, subscript, superscript, textColor, bgColor, fontSize, fontFamily, lineHeight, ul, ol, checklist, indent, outdent, alignLeft, alignCenter, alignRight, alignJustify, ltr, rtl, link, unlink, image, imageAlt, imageCaption, file, embed, table and the table commands, hr, pageBreak, math, mathBlock, specialChars, emoji, clearFormat, insertHTML, insertText, find, and the commands of track changes, comments, versions, the AI assistant, the accessibility panel and the page view described below. undo(), redo(), canUndo() and canRedo() work on the history.

Events

Every event handler receives one payload object. Subscribe in the options (on: { change: fn }) or later with on, once and off; on('*', (event, payload) => …) receives every event.

editor.on('change', (e) => console.log(e.source, e.html.length));
editor.on('selectionChange', (e) => console.log(e.collapsed, e.text, e.block));
editor.on('wordCountChange', (e) => console.log(e.words, e.readingTime));

Every VibeFox JS component emits ready, dataChange, optionsChange, themeChange and destroy. The full list is in API reference.

State snapshots

getState() returns a JSON-safe snapshot: the HTML, the mode (WYSIWYG or source), focus mode, direction, the find bar, recent symbols, the style, track changes, the comment threads, the open panels and the page view. setState(state) restores it. Versions are kept with getVersions() / setVersions().

localStorage.setItem('my-doc', JSON.stringify(editor.getState()));
editor.setState(JSON.parse(localStorage.getItem('my-doc')));

Writing and formatting

Typing helpers

  • Slash menu (slashCommands, default true): "/" in an empty line opens a menu of blocks (headings, lists, table, image, video, code, formula, symbol, emoji, rule, page break …); event slashCommand.
  • Markdown shortcuts (markdownShortcuts): # to #### + space = heading, - or * = list, 1. = numbered list, > = quote, ``` (with a language: ```js) = code block, --- = rule, **bold**, *italic*, `code`, ~~strike~~.
  • Smart typography (typography): typographic quotes, dashes, ellipsis and arrows while typing.
  • Mentions (mentions: { items, trigger }): "@" opens a list of your items (an array or an async function of the query); event mentionInsert.
  • Autosave (autosave: { enabled, interval, key }): the event autosave every interval ms after changes and a copy in localStorage under your key; loadDraft() and clearDraft().
const notes = VibeFoxJSEditor.createEditor('#app2', {
  mentions: { items: async (q) => [{ id: 1, label: 'Alice' }, { id: 2, label: 'Bob' }].filter((u) => u.label.toLowerCase().startsWith(q.toLowerCase())) },
  autosave: { enabled: true, interval: 10000, key: 'notes-draft' },
  format: { fonts: ['Georgia, serif', { label: 'Mono', value: 'ui-monospace, monospace' }], fontSizes: ['12px', '16px', '24px'], indentStep: '1.5em' },
});
notes.on('autosave', (e) => fetch('/api/draft', { method: 'POST', body: e.html }));

Formatting options

format: fonts (font menu: CSS font lists or { label, value }), fontSizes, lineHeights, indentStep (default '2em'), maxIndent (8). Tab / Shift+Tab in a list item nests / lifts it; indent / outdent indent other blocks. Special characters and emoji (about 230 characters and 480 emoji, searched by English and Russian names) open from the toolbar or with exec('specialChars') / exec('emoji'); with a value they are inserted (event symbolInsert). searchSymbols('emoji', 'smile') searches the tables.

Paste

Pasted HTML is cleaned (Word and Google Docs lists, headings, quotes and tables are kept as real structure) and sanitized; images and files on the clipboard are uploaded; a bare YouTube / Vimeo link pasted into an empty paragraph becomes an embed (embed.autoEmbed; Ctrl+Z gives the link back). Event: paste ({ kind: 'html' | 'text' | 'image' | 'file' | 'embed' }). cleanExternalHtml(html) is the cleaner.

Toolbar and modes

Toolbar

The option toolbar is a preset name ('full' default, 'basic'; TOOLBAR_PRESETS) or your layout: groups [['bold', 'italic'], ['ul', 'ol']] or a flat list with '|' separators. Items are the commands plus undo, redo, blockFormat, source, focus, outline, fullscreen, accessibility, ai, pages, zoom, print, codeLanguage and the items of your own types. Items without their feature (for example file without an upload adapter, ai without an AI adapter) are hidden.

editor.setOptions({ toolbar: [['undo', 'redo'], ['blockFormat'], ['bold', 'italic', 'link'], ['ul', 'ol', 'checklist'], ['table', 'image'], ['source', 'fullscreen']] });
editor.setOptions({ stickyToolbar: true, statusbar: false });

Other parts: stickyToolbar (stays visible while scrolling), statusbar (words and characters), the HTML source view (setMode('source'), getMode(), event modeChange), full screen (toggleFullscreen()), focus mode that dims every block but the current one (toggleFocusMode()) and the outline of the headings (toggleOutline()).

Classic, inline and balloon

The option ui: 'classic' (default: the toolbar above the text), 'inline' (no frame: the element keeps the font and colors of your page, and the toolbar floats above the block while editing) or 'balloon' (a small toolbar at the selection and a "+" button at an empty paragraph; option balloon: { toolbar, plus }). Inline and balloon editors take the HTML of their element as the content and write it back on destroy().

document.querySelector('#app2').innerHTML = '<h2>About us</h2><p>Edit this text in place.</p>';
const inline = VibeFoxJSEditor.createEditor('#app2', { ui: 'balloon' });

One toolbar for several editors

createSharedToolbar(target, { editors, toolbar, stickyToolbar }) shows the toolbar of the editor that has the focus; methods addEditor(), removeEditor(), getEditors(), getActive(), setActive(), event activeChange.

document.querySelector('#app2').innerHTML = '<div id="bar"></div><div id="title"></div><div id="body"></div>';
const title = VibeFoxJSEditor.createEditor('#title', { ui: 'inline', data: '<h1>Title</h1>' });
const body = VibeFoxJSEditor.createEditor('#body', { ui: 'inline', data: '<p>Body</p>' });
const bar = VibeFoxJSEditor.createSharedToolbar('#bar', { editors: [title, body], toolbar: 'basic' });

Images, files and embeds

Uploads

Without an adapter, images are inserted as data URLs and other files are refused. With the option upload images and files go to your storage — from the file picker, drag and drop and the clipboard — with a placeholder and progress while they upload. The adapter is one of:

// 1. your function
editor.setOptions({ upload: { handler: async (file, { onProgress, signal }) => {
  const body = new FormData(); body.append('file', file);
  const res = await fetch('/api/upload', { method: 'POST', body, signal });
  return (await res.json()).url;             // or { url, alt, caption, name, width }
}, accept: ['image/*', '.pdf'], maxSize: 10e6 } });

// 2. a presigned URL (S3, GCS, R2 …): the editor PUTs the file with progress
editor.setOptions({ upload: { presign: async (file) => (await fetch('/api/presign?name=' + encodeURIComponent(file.name))).json() } });

// 3. an endpoint: multipart POST, the answer { url } / { location } / { data: { url } }
editor.setOptions({ upload: { url: '/api/upload', fieldName: 'file', headers: { 'X-CSRF': 'token' } } });

Methods: uploadFiles(files), openFilePicker({ accept, multiple, images }), getUploads(), abortUpload(id). Events: uploadStart, uploadProgress, uploadDone, uploadError (reason: 'type', 'size', 'failed', 'aborted'), drop, imageInsert, imageResize. Images get alt text and captions (exec('imageAlt', text), exec('imageCaption', text)) and are resized by their corner handle.

Embeds

insertEmbed(url) (or the toolbar, /video) embeds YouTube and Vimeo links without a network request; other links go through your resolver (for example an oEmbed proxy on your server). Only iframes from an allow-list survive the sanitizer. In the editor an embed is a placeholder until you allow the players to load; the placeholder is at most --vfjs-editor-embed-placeholder-width wide (480 px, in the ratio --vfjs-editor-embed-ratio, 16:9), a loaded player takes the full width.

const res = await editor.insertEmbed('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
console.log(res.ok, res.provider, res.src);   // youtube-nocookie.com player
editor.setOptions({ embed: {
  allow: ['https://player.example.com/'],
  resolve: async (url, { signal }) => (await fetch('/api/oembed?url=' + encodeURIComponent(url), { signal })).json(),
} });

embed options: allow (URL prefixes, https://*.example.com/ for subdomains, RegExps or functions), providers (YouTube / Vimeo, default true), resolve, live (load the players in the editor, default false), privacy (youtube-nocookie.com and Vimeo dnt, default true), autoEmbed. Events: embedInsert, embedError. Helpers: parseEmbedUrl(url), iframeAllowed(src, allow), DEFAULT_IFRAMES.

Tables

exec('table', { rows, cols, header }) inserts a table; a right click in a table opens its menu. Columns are resized by dragging their borders (widths in % in a colgroup; exec('columnWidths', [30, 70]), event columnResize). Rows and columns are inserted and deleted on the logical grid, so merged cells stay correct.

Every table of the document gets the class vfjs-editor-table and the table styles (borders, padding, header row), wherever it comes from: the table command, data, setData(), insertHTML(), a paste, a Markdown or DOCX import. Your HTML needs no class; getData() returns the tables with this class (nothing else is added). Tables inside your own blocks (registerBlock()) are left as they are.

editor.setData('<p>Prices</p>');
editor.focus();
editor.exec('table', { rows: 3, cols: 3, header: true });
editor.exec('rowBelow');
editor.exec('cellProps', { background: '#fef3c7', align: 'center', valign: 'middle' });
editor.exec('columnWidths', [50, 25, 25]);

Commands: rowAbove, rowBelow, colBefore, colAfter (start / end side), colLeft, colRight (physical sides), deleteRow, deleteCol, deleteTable, headerRow, mergeCells (the selected rectangle), splitCell, mergeRight, mergeDown, cellBackground, cellAlign, cellVAlign, cellProps, columnWidths. Event: tableInsert.

Find and replace

Ctrl+F opens the find bar, Ctrl+H the bar with replace. From code:

editor.setData('<p>Color and colour. COLOR!</p>');
console.log(editor.find('colou?r', { regex: true }));         // { total: 3, index: 0 }
editor.replace('shade');                                       // the current match, then the next
const n = editor.replaceAll('tone', { query: 'colou?r', regex: true, caseSensitive: false });
editor.clearFind();

Options: caseSensitive, wholeWord, regex (replacements may use $1, $<name>, $&). Methods: findNext(), findPrevious(), openFind({ replace }), closeFind(), isFindOpen(). Events: find, replace. Matches are highlighted without changing the content; replaceAll is one undo step.

Code blocks

Code blocks are <pre><code class="language-js">; the colors are painted over the text and never written into the HTML. A chip on the block picks the language. Built-in languages: js, ts, json, html, xml, css, python, php, sql, bash, java, csharp, cpp, go, markdown, yaml (and their aliases).

editor.setData('<pre><code class="language-sql">SELECT id FROM users WHERE active = 1;</code></pre>');
editor.setOptions({ codeBlock: { detect: true, defaultLanguage: 'js', languages: ['js', 'ts', 'sql', 'python'] } });
VibeFoxJSEditor.addCodeLanguage({ id: 'ini', label: 'INI', rules: [['comment', /;.*/], ['property', /^[\w.]+(?=\s*=)/m], ['string', /=.*/]], multiline: true });
console.log(VibeFoxJSEditor.detectCodeLanguage('def f(x):\n    return x'), VibeFoxJSEditor.tokenizeCode('let a = 1', 'js').length);

codeBlock options: highlight, detect (guess the language, shown as "Auto: …"), languages (of the picker), defaultLanguage, picker, maxLength (500 000 characters); codeBlock: false turns highlighting and the picker off. exec('codeBlock', 'python'), exec('codeLanguage', 'sql'); event codeLanguageChange. Helpers: getCodeLanguages(), CODE_TOKEN_TYPES. Paste inside a code block is plain text.

Formulas

Formulas are written in LaTeX and shown as MathML; the LaTeX source is kept in the HTML and is the truth (the MathML is made again on every load). The toolbar item math, /math or a click on a formula opens the formula dialog with a preview.

const r = editor.insertMath('\\frac{a+b}{2} \\le \\sqrt{x^2+y^2}');
editor.insertMath('\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}', { display: true });
console.log(r.ok, editor.getFormulas());
console.log(VibeFoxJSEditor.checkLatex('\\frac{a}').error.code);   // 'missingArg'
const mathml = VibeFoxJSEditor.latexToMathML('e^{i\\pi} + 1 = 0', { display: true });

Supported: fractions, roots, scripts, big operators with limits, functions, matrices and cases environments, Greek letters, about 200 operators, relations and arrows, \left / \right, text and math fonts, accents, colors and boxes. Methods: openMathDialog(); commands math, mathBlock. Events: mathInsert, mathUpdate, mathRemove. Formulas go to Markdown as $…$, to the PDF as vector boxes and to Word as Office Math; screen readers get a spoken text (speakMath).

Track changes

In suggestion mode every edit becomes a change of its author: insertions, deletions, formatting, blocks, table rows and columns. Changes are accepted or rejected one by one or all at once.

editor.setData('<p>The quick fox.</p>');
editor.setOptions({ trackChanges: { enabled: true, author: { id: 'ann', name: 'Ann' } } });
editor.focus();
editor.insertText(' Jumps!');
console.log(editor.getChanges());                          // [{ id, type: 'insert', author: 'ann', text, … }]
console.log(editor.getData({ changes: 'final' }));         // with every change accepted
editor.acceptAllChanges({ author: 'ann' });
editor.setTrackChanges(false);

trackChanges options: enabled, author (a name, or { id, name, color } with a color slot 0–7), colors (slot per author id), output (what getData() returns: 'markup', 'final', 'original'), announce. Methods: setTrackChanges(), isTrackingChanges(), getChanges({ author, type }), acceptChange(id), rejectChange(id), acceptAllChanges(), rejectAllChanges(), nextChange(), previousChange(), goToChange(id), toggleChangesPanel(), isChangesPanelOpen(). Events: trackChangesToggle, changesUpdate, changeAccept, changeReject, changeFocus, changesPanelChange. The changes are kept in the HTML as <ins> / <del> with data-vfjs-* attributes, so a saved document keeps them.

Comments

A comment thread is attached to a selection (or to a suggestion) and has replies, mentions and a resolved state. Threads are JSON you store on your server; the anchors are kept in the HTML.

editor.setData('<p>Revenue grew by 12 percent in March.</p>');
const range = document.createRange();
range.selectNodeContents(editor.content.querySelector('p'));
const thread = editor.addComment('Source of this number?', { range, author: { id: 'bob', name: 'Bob' } });
editor.addReply(thread.id, 'From the March report.', { author: 'ann' });
editor.resolveComment(thread.id);
const saved = editor.getComments();           // JSON for your server
editor.setComments(saved);

comments options: enabled, author, colors, markup (keep the anchors in getData(); false: clean HTML, threads find their text again by its quote), readonly (comments in a read-only editor), permissions ('own' or 'all'), mentions, announce. Methods: updateComment(), removeComment(), reopenComment(), getComment(id), nextComment(), previousComment(), goToComment(id), toggleCommentsPanel(), isCommentsPanelOpen(), openCommentForm(). Events: commentAdd, commentUpdate, commentRemove, commentResolve, commentOrphan (the commented text was deleted), commentFocus, commentsChange, commentsPanelChange. Adding or resolving a comment is not an undo step of the text.

Versions and comparison

A version is a saved copy of the HTML (with suggestions and comment anchors). Two versions are compared as track-changes markup, shown inline or side by side, or put into the text as suggestions to review.

editor.setData('<p>First draft of the text.</p>');
const v1 = editor.saveVersion({ name: 'Draft' });
editor.setData('<p>Second draft of the long text.</p>');
const cmp = editor.compareVersions(v1.id, 'current');
console.log(cmp.stats);                          // { changes, insert, delete, replace, format, wordsInserted, wordsDeleted }
editor.showCompare(v1.id, 'current', { layout: 'side' });
editor.hideCompare();
editor.restoreVersion(v1.id);                    // one undo step
const diff = VibeFoxJSEditor.diffHtml('<p>a b c</p>', '<p>a x c</p>');   // works without a DOM

versions options: auto (automatic snapshots while the content changes), interval (300 000 ms), max (50 automatic ones kept), author. Methods: getVersions(), getVersion(id), setVersions(list), removeVersion(id), compareVersions(from, to, { asChanges }), isCompareOpen(), toggleVersionsPanel(), isVersionsPanelOpen(). Events: versionSave (with the HTML: keep it on your server), versionRestore, versionRemove, compareChange, versionsPanelChange.

Real-time collaboration

collaborate(options) starts a session: the edits of every participant are merged without conflicts (a CRDT), the cursors and selections of the others are shown, offline edits wait and are sent later, and undo undoes only your own changes. The transport is yours (WebSocket, WebRTC, a server relay); without one the tabs of one browser work together through BroadcastChannel.

const socket = new WebSocket('wss://example.com/rooms/doc-42');
const session = editor.collaborate({
  room: 'doc-42',
  user: { name: 'Ann', color: 2 },
  transport: {
    send: (msg) => socket.send(JSON.stringify(msg)),
    onMessage: (fn) => socket.addEventListener('message', (e) => fn(JSON.parse(e.data))),
  },
  persist: { key: 'doc-42-offline' },   // unsent edits survive a reload
});
editor.on('peersChange', (e) => console.log(e.peers.map((p) => p.name)));
console.log(session.online, session.pending, editor.getPeers());

Options: transport ({ send, onMessage, onStatus, close } or 'broadcast'), room, clientId, user ({ name, color }: a CSS color or a slot 0–7), initial ('shared': everybody starts from the same content, 'local': this content is sent to the room, 'remote': start empty and take the room's document), connect, presence ({ cursors, list, heartbeat, timeout, throttle } or false), persist ({ key } or { save, load }), gc, share ({ comments, versions }). The session has getPeers(), setUser(), connect(), disconnect(), sync(), flush(), snapshot(), receive(msg), undo(), redo(), destroy(). Events: collabSend, remoteChange, collabStatus, peersChange; getCollaboration() returns the session.

A server can keep the room with RtcDoc (also in Node): it receives the operations of the clients (receive(ops)) and gives a newcomer the whole state (snapshot(), load(), toHTML()).

Import and export

HTML and Markdown

const html = editor.exportHTML();                              // with { download: true, filename } it downloads
const md = editor.exportMarkdown();                            // CommonMark + GFM
editor.importMarkdown('# Title\n\n- [x] done\n- [ ] todo\n\n| a | b |\n|---|---|\n| 1 | 2 |');
editor.importMarkdown('**inserted**', { mode: 'insert' });     // at the caret
const page = VibeFoxJSEditor.markdownToHtml('Some *text* and $x^2$');   // without a DOM

The Markdown import reads CommonMark and GFM (tables, task lists, strikethrough, autolinks) and $…$ formulas; export and import give the same document back. htmlToMarkdown(element) converts any element. Event: import.

PDF

The PDF is drawn by the editor itself: vector pages, selectable text, links, bookmarks from the headings, tables with repeated header rows, code colors, images and formulas.

const bytes = await editor.getPDF({ pageSize: 'A4', margin: 56.7, header: '{title}', footer: { text: 'Page {page} of {pages}', align: 'center' } });
await editor.exportPDF('report.pdf', { changes: 'markup', comments: true });

Options: pageSize ('A4', 'A3', 'A5', 'Letter', 'Legal', 'Tabloid' or [width, height] in pt), orientation, margin, header, footer (text with {page}, {pages}, {title}, {date}, an object or a function), pageNumbers, title, author, subject, keywords, changes ('final' default, 'original', 'markup'), comments, colors ('auto', 'editor', 'print'), images, highlight, dir, scale, outline, embedFonts, download, filename. The library ships no fonts: pass your font files with embedFonts (.ttf, .otf or .woff), or embedFonts: true to take the @font-face fonts of the page. With a font that has the letters, Arabic, Hebrew and Hindi text is written as on the screen: right to left where needed, Arabic letters joined, Devanagari syllables built. previewPDF(target) shows the PDF in the browser's viewer. Event: export.

Word (.docx)

const docx = await editor.getDOCX({ changes: 'markup', comments: true, font: 'Calibri' });   // Word revisions and comments
await editor.exportDOCX('report.docx');
const result = await editor.importDOCX(docx, { changes: 'markup', comments: true, images: 'inline' });
console.log(result.warnings);                                   // what could not be taken over

Export options: those of the PDF plus font, monoFont, fontSize, lang, trackRevisions. changes: 'markup' writes real Word revisions; comments: true writes Word comments with replies. Import options: mode ('replace' or 'insert'), changes, comments, images ('inline', false or your store function; default: your upload adapter), pageBreaks ('ignore' or 'marker'), footnotes, formatting ('full' or 'basic'). docxToHtml(data) converts without a DOM (Node, a server); DOCX_MIME is the media type.

Page view and printing

pages: true (or options) shows the document on sheets like a word processor: page breaks while you type, headers and footers, page numbers, zoom. The PDF and DOCX exports take the page settings of the view.

editor.setPages({ size: 'Letter', orientation: 'portrait', margin: '2cm', header: '{title}', pageNumbers: true,
  firstPage: { header: null }, zoom: 'width' });
editor.focus();
editor.exec('pageBreak');                      // also Ctrl+Enter
console.log(editor.getPageCount(), editor.getCurrentPage(), editor.getZoom());
const printable = editor.getPrintHtml();

Options: size, orientation, margin, header, footer, pageNumbers, firstPage, evenPages (own parts of the first and even pages: { header, footer, pageNumbers }), zoom (a number, 'width' or 'page'), repeatHeader (table header rows on every page), exportBreaks. Methods: isPagesView(), goToPage(n), setZoom(), print(options). Events: pagesChange, zoomChange, print. The page view works in the classic mode.

firstPage and evenPages change only the keys they name; the keys you leave out come from the main header, footer and pageNumbers. null (false for pageNumbers) removes only that part on those pages. So firstPage: { header: null } above removes the header of page 1 and keeps its page number — in the view, in print, in the PDF and in the DOCX export. An empty first page (a cover) is firstPage: { header: null, footer: null, pageNumbers: false }.

AI assistant

The option ai connects the assistant to your language model. The editor never calls a model or a service itself: your adapter receives the prompt and the context and returns the answer — a string, a stream, an async iterable, a Response of your server, or parts pushed with callbacks. The answer streams into a preview that the user accepts (one undo step) or discards.

editor.setOptions({ ai: {
  stream: async function* (prompt, ctx) {
    const res = await fetch('/api/ai', { method: 'POST', body: JSON.stringify({ messages: ctx.messages }), signal: ctx.signal });
    const reader = res.body.getReader(); const dec = new TextDecoder();
    for (;;) { const { done, value } = await reader.read(); if (done) break; yield dec.decode(value, { stream: true }); }
  },
  commands: ['rewrite', 'grammar', 'translate', 'summarize', { id: 'title', label: 'Suggest a title', prompt: 'Suggest a title for this text.', insert: 'after' }],
  languages: ['en', 'de', 'fr'],
} });
const r = await editor.runAI('summarize', { apply: true });
console.log(r.ok, r.text);

Commands: rewrite (tone: 'formal', 'simple', 'shorter', 'longer'), grammar, translate (language), summarize, continue, custom (prompt) and your own. The context has command, instruction, system, messages (ready for chat APIs), text (Markdown of the selection or paragraph), before, after, locale, signal and push() / done() / error(). Options: stream, resolve, commands, languages, prompts (replace the English instruction templates), suggest and author (answers as tracked suggestions), contextChars, contextMenu, slash, keys (Ctrl+J), announce. Methods: acceptAI(), rejectAI(), stopAI(), retryAI(), getAIState(), isAIAvailable(), openAIPanel(), closeAIPanel(). Events: aiStart, aiChunk, aiDone, aiError, aiStop, aiRetry, aiAccept, aiReject, aiPanelChange. Without an adapter every AI item is hidden.

Accessibility checker

The checker finds accessibility problems in the document and fixes many of them in one click: images without alt text, empty or skipped headings, a second H1, empty or vague links ("click here"), low text contrast, tables without a header row, text in another language without lang, iframes without a title, long paragraphs.

editor.setData('<h1>A</h1><h3>B</h3><p><img src="data:image/gif;base64,R0lGODlhAQABAAAAACw="></p><p><a href="/x">click here</a></p>');
const { issues, counts } = editor.checkAccessibility({ level: 'AA' });
console.log(counts, issues.map((i) => i.rule));
const img = issues.find((i) => i.rule === 'img-alt');
editor.fixAccessibilityIssue(img.id, 'alt', 'Sales chart');
editor.toggleAccessibilityPanel(true);
const report = VibeFoxJSEditor.checkHtmlAccessibility('<img src="a.png">');   // without a DOM

Option accessibility (false hides the toolbar item): rules (A11Y_RULES), maxParagraphWords, lang, level ('AA' or 'AAA'), live, vagueLinks. Methods: goToAccessibilityIssue(id), isAccessibilityPanelOpen(); contrastRatio(fg, bg). Events: accessibilityCheck, accessibilityFix, accessibilityFocus, accessibilityPanelChange.

Own blocks and inline nodes

registerBlock(spec) and registerInline(spec) add your own content types with their commands, toolbar items, slash entries, keys, Markdown and export: containers of paragraphs (a callout), islands with their own UI (a button, a widget) and inline nodes (a tag, a keyboard key). Register them before creating the editors.

VibeFoxJSEditor.registerBlock({
  name: 'callout',
  className: 'callout',
  content: 'blocks',
  attrs: { kind: { default: 'info', values: ['info', 'warning'] } },
  label: { en: 'Callout', de: 'Hinweis' },
  icon: 'quote',
  toolbar: ['callout'],
  slash: ['callout'],
  keys: { 'Mod+Alt+C': 'callout' },
  markdown: (el, { content }) => '> **Note:** ' + content(),
});
VibeFoxJSEditor.registerInline({ name: 'kbd', tag: 'kbd', content: 'text', label: 'Key', toolbar: ['kbd'] });
const doc = VibeFoxJSEditor.createEditor('#app2', { data: '<p>Press <kbd data-vfjs-inline="kbd">Ctrl</kbd></p>' });
doc.focus(); doc.exec('callout', { kind: 'warning' });
console.log(VibeFoxJSEditor.getBlockTypes().map((t) => t.name));

Spec fields: name, tag, className, content ('blocks', 'text' or 'none'), attrs (each with attr, default, values, pattern, url, max, validate), parse and parseAttrs (read foreign markup), html (stored content of islands), render (an island draws its UI into a shadow root and returns { update, destroy }), label, icon, commands, toolbar, slash, keys, markdown, exportHtml (standard HTML for PDF / DOCX), suggest, comments. Only the declared attributes survive the sanitizer. unregisterType(name), getInlineTypes(); ICONS are the built-in icons.

Theming and styling

Themes

Every VibeFox JS component has the themes light (default), dark and high-contrast built into its CSS file. The optional vibefox-js-themes.css adds the theme pack: high-contrast-light, paper, paper-dark, glass, glass-dark, classic, classic-dark, ocean, ocean-dark, forest, forest-dark, sunset, sunset-dark, graphite, graphite-dark. The same file works for every VibeFox JS library.

VibeFoxJSEditor.setTheme('dark');                 // the whole page
VibeFoxJSEditor.setTheme('ocean', '#sidebar');    // every component inside a container
editor.setTheme('glass');                    // one component (also: the theme option)
editor.setTheme(null);                       // follow the page / container again

A component without its own theme follows the nearest container with a theme, then the page. After setTheme(name, container) the theme variables are set on the container itself too, so your CSS of the container can use them (#sidebar { background: var(--vfjs-bg); }). Your own theme: registerTheme(name, vars) with the theme variables (bg, fg, border, accent, accent-fg, muted, surface, radius, font, shadow, palette-0 … palette-9 and any other token); it applies at once to every component that uses it. getTheme() returns the page theme, themes lists the registered ones; the event themeChange reports a switch.

VibeFoxJSEditor.registerTheme('brand', { accent: '#e11d48', 'accent-fg': '#ffffff', radius: '10px' });
editor.setTheme('brand');

CSS variables

Every color, size, spacing, font, radius, shadow and duration of VibeFox JS Editor is a CSS variable, so any setting is changed in one place. There are three levels:

  • theme variables shared by all VibeFox JS components: --vfjs-bg, --vfjs-fg, --vfjs-border, --vfjs-accent, --vfjs-accent-fg, --vfjs-muted, --vfjs-surface, --vfjs-radius, --vfjs-font, --vfjs-shadow, --vfjs-palette-0 … --vfjs-palette-9;
  • design tokens: spacing --vfjs-space-1 … --vfjs-space-8, font sizes --vfjs-font-size, --vfjs-font-size-sm and others, radii --vfjs-radius-sm …, status colors --vfjs-danger, --vfjs-success, --vfjs-warning, --vfjs-info, the scale --vfjs-size-unit, durations --vfjs-motion-duration, the focus ring --vfjs-focus-ring-color and --vfjs-focus-ring-width;
  • variables of the library, --vfjs-editor-*, which default to the tokens above.
/* all VibeFox JS components of the page */
.vfjs { --vfjs-accent: #0f766e; --vfjs-radius: 4px; }
/* only this editor */
#notes {
  --vfjs-editor-toolbar-bg: #f8fafc;
  --vfjs-editor-content-padding: 24px;
  --vfjs-editor-font-size: 17px;
}

Main groups of the editor variables (all start with --vfjs-editor-): frame (--vfjs-editor-bg, --vfjs-editor-fg, --vfjs-editor-font, --vfjs-editor-border, --vfjs-editor-radius, --vfjs-editor-shadow), toolbar (--vfjs-editor-toolbar-bg, --vfjs-editor-toolbar-padding, --vfjs-editor-toolbar-sticky-top), buttons (--vfjs-editor-btn-height, --vfjs-editor-btn-radius, --vfjs-editor-btn-hover-bg, --vfjs-editor-btn-active-bg), text (--vfjs-editor-content-bg, --vfjs-editor-content-padding, --vfjs-editor-content-max-width, --vfjs-editor-font-size, --vfjs-editor-line-height, --vfjs-editor-paragraph-space, --vfjs-editor-heading-fg, --vfjs-editor-link, --vfjs-editor-selection-bg), quotes (--vfjs-editor-quote-border), tables (--vfjs-editor-table-border, --vfjs-editor-table-header-bg), code (--vfjs-editor-code-bg, --vfjs-editor-code-font, --vfjs-editor-code-keyword, --vfjs-editor-code-string and the other token types), status bar (--vfjs-editor-statusbar-bg), popovers (--vfjs-editor-popover-bg), track changes and comments (--vfjs-editor-track-a … --vfjs-editor-track-h author colors, --vfjs-editor-track-ins-bg, --vfjs-editor-comment-bg), formulas (--vfjs-editor-math-font), AI (--vfjs-editor-ai-*), page view (--vfjs-editor-page-*), collaboration cursors (--vfjs-editor-peer-*), embeds (--vfjs-editor-embed-width, --vfjs-editor-embed-ratio, --vfjs-editor-embed-bg, --vfjs-editor-embed-border, --vfjs-editor-embed-radius, --vfjs-editor-embed-label-bg, --vfjs-editor-embed-label-fg, --vfjs-editor-embed-selected, --vfjs-editor-embed-placeholder-width — the width of a placeholder whose player is not loaded, 480 px).

From JavaScript: the option styleVars sets variables on the editor element ({ 'toolbar-bg': '#eef2ff' } = --vfjs-editor-toolbar-bg; full names work too), className adds your own classes.

Where to set them: on :root, on any container of your page (#checkout { --vfjs-accent: #0f766e; }), on the element of the component, or in a theme (registerTheme). The closest value wins; a component with its own theme (the option theme or component.setTheme(name)) keeps the theme variables of that theme even inside a container that sets them. A container inside another component (a form inside a dialog or a card) passes the variables of the library to the components in it as well. Only the shared design tokens (--vfjs-space, --vfjs-danger, --vfjs-selected-bg …) do not pass there: set them on a container outside the outer component or on the nested components themselves (#form .vfjs { … }). Popups, menus and dialogs placed in <body> take the values set on the page (:root), not those of the container of their component.

Default values: the theme variables are registered with @property (their initial value is the light theme), so they have a value on every element of the page. The variables of the library (--vfjs-editor-*) keep their defaults inside the stylesheet, at the place where they are used, so a variable that you did not set has no value on your elements:

  • in your own CSS that uses a variable of the library, give it a fallback as the library does: var(--vfjs-editor-bg, var(--vfjs-bg)), or use a theme variable directly;
  • from JavaScript, read the current value with cssVar(element, '--vfjs-editor-font-size') (exported by the library; it also returns the default value the component computes); getComputedStyle(element).getPropertyValue() can return an empty string for a variable of the library that nobody set.
/* your own element in the colors of the component */
.my-summary { background: var(--vfjs-editor-bg, var(--vfjs-bg)); color: var(--vfjs-fg); }
const el = document.querySelector('#orders');
console.log(VibeFoxJSEditor.cssVar(el, '--vfjs-editor-font-size'));                    // the value in use (also a default)
console.log(VibeFoxJSEditor.cssLength(el, 'var(--vfjs-editor-font-size)'));            // the same in pixels
console.log(getComputedStyle(el).getPropertyValue('--vfjs-editor-font-size'));  // can be '' unless you set it

If the CSS file of the library comes from another origin without CORS (a <link> without the crossorigin attribute), the browser does not let scripts read the stylesheet, and cssVar() returns an empty string for a variable without a value on the root of the component. From your own origin, or with that attribute, it works.

The stylesheets are written with native CSS nesting; nothing changes for including them, and your own CSS can be written in any form.

Ready-made styles

The option style (the prop variant in the framework wrappers) picks a ready-made look; every style works with every theme and density.

StyleLook
'classic'Default: a frame, the toolbar above the text with separators, a status bar.
'minimal'No frame, a transparent toolbar without separators, muted buttons.
'floating'The toolbar is a floating rounded card with a shadow; the text area is its own card.
editor.setStyle('floating');                          // or the option style: 'floating'
editor.setStyle('minimal', { 'toolbar-bg': '#eef2ff' });   // with variables
editor.getStyle();                                    // 'minimal'

EDITOR_STYLES lists the names; setStyle emits styleChange. Any other name uses your own CSS for the class vfjs-editor-style-<name>.

Density and size

Set data-vfjs-density="compact", "normal" or "comfortable" on the page or on any container: heights and paddings of every VibeFox JS component inside follow. --vfjs-size-unit (default 1px) scales all sizes of a component at once, for example #orders { --vfjs-size-unit: 1.25px; }. Sizes you give as numbers in options are pixels and are not scaled.

Default height: the editor is as high as its content, at least the option minHeight; give the element a height to get a fixed one.

Your own CSS

All library rules are inside the cascade layer @layer vfjs, so your own CSS always wins without !important. The class names of VibeFox JS Editor start with vfjs-editor- (state classes too, for example vfjs-editor-is-active), so other CSS frameworks on the page do not restyle it.

.vfjs-editor-toolbar .vfjs-editor-btn.vfjs-editor-is-active { color: #1d4ed8; }
.vfjs-editor-content h2 { letter-spacing: -0.01em; }

The library ships no font files. It uses the system font stacks of the tokens --vfjs-font, --vfjs-font-mono and --vfjs-font-serif; set them to your own fonts if you want. Animations follow prefers-reduced-motion, and colors follow forced-colors mode (Windows high contrast).

Published content: the HTML of getData() uses classes such as vfjs-editor-table, vfjs-editor-figure, vfjs-editor-align-left, vfjs-editor-embed and vfjs-editor-math; style them on the pages where you show the content.

Localization and RTL

Languages

VibeFox JS Editor comes with 14 interface languages. English (en) is built into the library file; each of the others is a language file of its own (dist/locales/vibefox-js-editor.<lang>.js in the package), and a page loads only the ones it uses: Russian (ru), Spanish (es), German (de), French (fr), Italian (it), Portuguese (Brazilian) (pt), Ukrainian (uk), Turkish (tr), Chinese (Simplified) (zh), Japanese (ja), Korean (ko), Hindi (hi) and Arabic (ar). The locale option sets the language of one component; setLocale(lang) sets the default language of the page, which every component without its own locale follows (it re-renders on a change).

VibeFoxJSEditor.setLocale('ru');                                  // page default
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>Hallo</p>', locale: 'en' }); // this editor only
editor.setOptions({ locale: 'de' });

The example above needs the files of the languages it uses. With script tags, load a language file after the library. The order matters: loaded first, the file adds no language and writes a warning to the console.

<link rel="stylesheet" href="vibefox-js-editor.css">
<script src="vibefox-js-editor.global.min.js"></script>
<script src="locales/vibefox-js-editor.ru.js"></script>

With npm or a bundler, import the language after the library. Without npm, an ES module page imports ./locales/vibefox-js-editor.ru.esm.js, which registers the language in vibefox-js-editor.esm.js.

import { createEditor } from '@vibefox/js-editor';
import '@vibefox/js-editor/locales/ru';

The .esm.js language file does not fit the minified build @vibefox/js-editor/min (it would load a second copy of the library). There, use the .json file:

import { createEditor, addLocale } from '@vibefox/js-editor/min';
import ru from '@vibefox/js-editor/locales/ru.json';
addLocale('ru', ru);

Without its file, locale: 'ru' shows English and writes one warning to the console.

Language codes: uk, ko, zh and pt are the real codes; ua and kr also work, as aliases of uk and ko. For each string the library tries the exact code, then the alias, the base language (pt-BR → pt, zh-CN → zh), English, and finally the key itself. normalizeLocale(code) returns the real code of an alias.

A language does not set the direction: with locale: 'ar', also set rtl: true or dir="rtl" on the container.

Adding a language

addLocale(lang, dictionary) adds strings to a language (and creates it): a language of your own, or your own wording over a language file. A missing key follows the chain above, so a partial dictionary works; addLocale('ua', …) fills uk. Add the dictionary before the components that use it are created, or switch the locale afterwards.

VibeFoxJSEditor.addLocale('de', {
  'editor.placeholder': 'Schreiben Sie, oder drücken Sie „/“ für Blöcke…',
  'editor.bold': 'Fett',
});

The keys of VibeFox JS Editor start with editor. (about 360 keys: the toolbar, menus, dialogs, panels, the find bar, the AI assistant, the accessibility checker, screen reader texts). The language files list every key (locales/vibefox-js-editor.ru.json); the English texts are in the readable file vibefox-js-editor.esm.js. Placeholders in braces, such as {n}, are filled in by the library. t(key, params) translates a key in the page locale, editor.t(key) in the editor's locale; getLocale() returns the page locale, onLocaleChange(fn) reports changes. The content itself is your text and is not translated.

Plural forms: a text with a number has the keys <key>.zero, .one, .two, .few, .many and .other (the categories of Intl.PluralRules); .other is the fallback, so your dictionary can give only that form. {count} and {n} are filled in. tPlural(key, count, params, lang) picks the form; the method editor.tPlural(key, count, params) does it in the locale of the component.

VibeFoxJSEditor.addLocale('de', {
  'editor.ai.ready.one': 'KI-Antwort ist fertig ({words} Wort).',
  'editor.ai.ready.other': 'KI-Antwort ist fertig ({words} Wörter).',
});
VibeFoxJSEditor.tPlural('editor.ai.ready', 5, { words: 5 }, 'de');  // 'KI-Antwort ist fertig (5 Wörter).'

Special characters and emoji are searched by their English and Russian names, and the spoken text of formulas is English or Russian, whatever language files are loaded. The accessibility check messages follow the editor locale; the language of a DOCX export is taken from the locale unless you give lang. Times of comments, changes and versions are shown in the editor locale.

Right-to-left

The option rtl: true lays the component out right-to-left (dir="rtl" on its element); rtl: false forces left-to-right; without it the component follows the page or its container (<html dir="rtl">). The arrow keys follow the reading order. isRtl(element) tells the direction of an element.

In VibeFox JS Editor the option dir ('ltr', 'rtl' or null = the page direction) sets the direction of the document; setDirection(), getDirection(), event directionChange. The toolbar, popovers, panels, lists, quotes and change bars mirror; the HTML source view stays left-to-right. Single paragraphs get their own direction with exec('rtl') / exec('ltr') (toolbar items shown when the editor is right-to-left). The PDF and DOCX exports write right-to-left paragraphs.

Accessibility

The text area is a labelled rich text field ("Rich text editor" unless your element has aria-label / aria-labelledby); every toolbar follows the WAI-ARIA toolbar pattern with one tab stop, and screen readers hear formatting changes, suggestions and comments at the caret, navigation, find results, uploads and AI answers. Focus is visible (the focus ring is the CSS variables --vfjs-focus-ring-color, --vfjs-focus-ring-width, --vfjs-focus-ring-offset, --vfjs-focus-ring-style); dialogs keep the focus inside and give it back when they close. The high-contrast and high-contrast-light themes, forced-colors mode and prefers-reduced-motion are supported. For the content, see Accessibility checker.

Keyboard

On macOS, Cmd works where Ctrl is listed.

KeysAction
Ctrl+B, Ctrl+I, Ctrl+U, Ctrl+Shift+XBold, italic, underline, strikethrough.
Ctrl+, , Ctrl+.Subscript, superscript.
Ctrl+KLink.
Ctrl+Z, Ctrl+Y, Ctrl+Shift+ZUndo / redo.
Ctrl+F, Ctrl+HFind, find and replace; Enter / Shift+Enter next / previous, Esc closes.
Tab, Shift+Tab (list item)Nest / lift the item.
Shift+EnterLine break.
Ctrl+EnterPage break.
/Slash menu (arrows, Enter or Tab, Esc).
@Mentions (option mentions).
Alt+F10To the toolbar (shared toolbar, balloon or own); Esc back to the text.
Arrows, Home, End (toolbar)Move between the buttons.
Ctrl+Shift+ESuggestion mode on / off.
Alt+PageDown, Alt+PageUpNext / previous change.
Ctrl+Alt+MNew comment on the selection.
Alt+Shift+PageDown, Alt+Shift+PageUpNext / previous comment.
A, R (change list)Accept / reject the change.
Ctrl+Enter (comment field, formula dialog, AI answer)Send / insert / accept.
Ctrl+JAI assistant (option ai).
EscClose a popover or panel, stop or discard an AI answer, leave full screen.

Screen readers

Toolbars are toolbars with aria-controls pointing to the text, buttons have names and aria-pressed / aria-haspopup; menus are menus, the symbol grid a listbox, the find bar a search region, the panels labelled asides with lists; suggestions are real <ins> / <del> elements; formulas carry a spoken alttext; collaboration cursors are hidden from screen readers. The announcements of track changes, comments and the AI assistant can be turned off with their announce options.

Methods: focus(), blur(), focusToolbar(). The library also exports the helpers it uses itself: announce(message), trapFocus, rovingFocus, setAria, prefersReducedMotion() and others (see API reference).

Using with other VibeFox JS libraries

VibeFox JS Editor works on its own. Every VibeFox JS library is a separate file with its own copy of the shared core, and several libraries on one page work together without conflicts: one global variable per library (VibeFoxJSEditor, VibeFoxJSCharts, …), class names with the library prefix, one page theme, the same events.

Connecting components with link()

link(source, event, target, method, transform) calls a method of one component whenever another emits an event; it returns a function that removes the link. connect(source, event, handler) subscribes and returns an unsubscribe function. bus is a page-wide event channel shared by all VibeFox JS libraries on the page.

// the word count of the editor goes to a component of another VibeFox JS library (both files loaded on the page)
const unlink = VibeFoxJSEditor.link(editor, 'wordCountChange', grid, 'setData', (e) => [{ name: 'Words', value: e.words }]);
VibeFoxJSEditor.bus.emit('doc:saved', { at: Date.now() });   // any library can listen: VibeFoxJSGrid.bus.on('doc:saved', fn)

What uses another library when it is on the page

  • PDF export and printing: work on their own; if VibeFox JS PDF is also on the page, toPdfDocument(), addToPdfDocument() and the VibeFox JS PDF viewer in previewPDF() are available.
  • Export to DOCX, HTML and Markdown and the import of DOCX and Markdown work on their own.

AI tools

The library describes its main actions as tools for function calling with a language model. It never calls a model or a service itself: you send the descriptions to your model and run the calls it asks for.

ToolWhat it does
editor_get_contentThe document as Markdown, HTML or text.
editor_get_selectionThe selected text.
editor_insertInserts content at the cursor, the start or the end.
editor_replace_selectionReplaces the selection.
editor_set_contentReplaces the document.
editor_find_replaceReplaces every match of a text or a regular expression.
editor_formatApplies a formatting command.
editor_outlineThe headings.
editor_statsWord, character and page counts.
const { describeTools, callTool, createToolKit } = VibeFoxJSEditor;
const tools = describeTools(editor, { format: 'openai' });   // 'plain' / 'anthropic', 'openai', 'webmcp'
const result = await callTool(editor, 'editor_get_content', { format: 'markdown' }); // { ok: true, result } or { ok: false, error }
const kit = createToolKit({ doc: editor });               // tool names get the prefix 'doc_'
const answer = await kit.ask('Add a short summary at the end', {
  format: 'anthropic',
  model: async (request) => (await fetch('/api/llm', { method: 'POST', body: JSON.stringify(request.body) })).json(),
});

callTool checks the arguments against the tool schema before it runs and never throws for bad input. createToolKit(components, { webmcp, readOnly }) joins the tools of several components (also of other VibeFox JS libraries) under unique names; kit.ask(prompt, { model, format, system, maxSteps, signal, onToolCall }) runs the loop "model → tool calls → results" with your model function; kit.registerWebMCP() registers the tools in the browser's navigator.modelContext where available. registerTools(target, provider) adds your own tools; validateSchema(value, schema) is the schema check.

The writing tools take suggest: true to record the change as a tracked suggestion of the AI author. editor.getAITools({ format }) and editor.callAITool(name, args) give the same tools without the core functions. This is separate from the AI assistant, which runs commands for the user inside the editor.

API reference

Exports

Library: createEditor, VibeFoxJSEditor, createSharedToolbar, TOOLBAR_PRESETS, ICONS, EDITOR_STYLES, sanitizeHtml, cleanExternalHtml, DEFAULT_IFRAMES, iframeAllowed, parseEmbedUrl, searchSymbols, tokenizeCode, detectCodeLanguage, getCodeLanguages, addCodeLanguage, CODE_TOKEN_TYPES, htmlToMarkdown, markdownToHtml, DOCX_MIME, docxToHtml, latexToMathML, checkLatex, speakMath, getTextStats, diffHtml, registerBlock, registerInline, unregisterType, getBlockTypes, getInlineTypes, checkHtmlAccessibility, contrastRatio, A11Y_RULES, RtcDoc.

Shared core (the same in every VibeFox JS library): setTheme, getTheme, registerTheme, themes, tokens, componentTokens, densities, cssVar, cssColor, cssLength, observeTokens, setLocale, getLocale, addLocale, normalizeLocale, t, tPlural, withLocale, onLocaleChange, link, connect, bus, Emitter, VibeFoxJSComponent, factory, toCSV, downloadFile, downloadCanvasPNG, createVectorContext, VectorContext, vectorToSVG, vectorToPDF, printSVG, createVectorImage, loadVectorImage, SVG_MIME, PDF_MIME, PDF_PAGE_SIZES, describeTools, callTool, createToolKit, registerTools, validateSchema, announce, trapFocus, rovingFocus, getFocusable, focusFirst, saveFocus, setAria, ensureId, addAriaRef, removeAriaRef, isRtl, mirrorArrow, prefersReducedMotion, prefersHighContrast, motionDuration, onPreferenceChange, injectStyles, ensureBaseStyles, formatNumber, formatDate, escapeHtml, createEl, deepMerge, isPlainObject, getPath, setPath, uid, clamp, debounce, throttle, VERSION.

Options

Also every VibeFox JS component accepts theme, locale, rtl and on (see Core concepts).

OptionTypeDefaultDescription
datastring''Initial HTML (sanitized).
placeholderstring'' (a localized hint)Text of an empty editor.
toolbarstring or array'full'Preset or layout.
stickyToolbarbooleantrueToolbar stays visible while scrolling.
statusbarbooleantrueWord / character counter.
minHeight, maxHeightstring'180px', ''Height of the text area.
autosaveobject{ enabled: false, interval: 30000, key: '' }Autosave.
mentionsobject or nullnull@-mentions.
slashCommands, markdownShortcuts, typographybooleantrueTyping helpers.
sanitizebooleantrueSanitize HTML of setData and paste.
spellcheckbooleantrueBrowser spell check.
readonlybooleanfalseRead only.
uploadobject or nullnullUpload adapter.
dir'ltr' | 'rtl' | nullnullDocument direction.
formatobject{}Font, size and spacing menus, indent.
embedobject{ allow: [], providers: true, resolve: null, live: false, privacy: true, autoEmbed: true }Embeds.
codeBlockobject or false{ highlight: true, detect: false, languages: null, defaultLanguage: '', picker: true, maxLength: 500000 }Code blocks.
stylestring or nullnull (classic)Ready-made style.
classNamestring or string[]''Own classes on the editor element.
styleVarsobject or nullnullCSS variables on the editor element ({ 'toolbar-bg': '#eef' }).
trackChangesobject or boolean{ enabled: false, author: null, colors: null, output: 'markup', announce: true }Track changes.
commentsobject or boolean{ enabled: true, author: null, colors: null, markup: true, readonly: true, permissions: 'own', mentions: null, announce: true }Comments.
versionsobject or boolean{ auto: false, interval: 300000, max: 50, author: null }Version history.
uistring'classic''classic', 'inline', 'balloon'.
balloonobject{ toolbar: 'balloon', plus: true }Balloon mode.
accessibilityobject or false{ rules: null, maxParagraphWords: 0, lang: null, level: 'AA', live: true, vagueLinks: null }Accessibility checker.
aifunction, object or nullnullAI assistant adapter.
pagesboolean or objectfalsePage view.

Events

EventPayloadDescription
ready, dataChange, optionsChange, themeChange, destroysee Core conceptsCommon events.
change{ html, source }Content changed (source: 'user', 'api', 'history', 'source', 'remote' …).
selectionChange{ collapsed, text, block }Selection moved.
wordCountChange{ words, chars, charsNoSpaces, readingTime }Counts changed.
undo, redo, autosave{ html }, { html, time, key }History, autosave.
imageInsert, imageResize, linkInsert, tableInsert, mentionInsert, slashCommand, checklistToggle, symbolInsertwhat was insertedInserts.
paste, drop{ kind, url }, { kind, count }Clipboard, drag and drop.
uploadStart, uploadProgress, uploadDone, uploadError{ id, file, … }Uploads.
embedInsert, embedError{ url, provider, src }, { url, reason, error }Embeds.
find, replace{ query, total, index }, { query, replacement, count, all }Find and replace.
columnResize{ column, widths }Table columns.
directionChange, styleChange, codeLanguageChange{ dir }, { style, className }, { language, previous }Direction, look, code language.
modeChange, fullscreenChange, focusModeChange, outlineChange{ mode }, { fullscreen }, { enabled }, { open }View.
trackChangesToggle, changesUpdate, changeAccept, changeReject, changeFocus, changesPanelChange{ enabled }, { total, authors }, { ids, changes, author }, { change, index, total }, { open }Track changes.
commentAdd, commentUpdate, commentRemove, commentResolve, commentOrphan, commentFocus, commentsChange, commentsPanelChange{ thread, comment, … }Comments.
versionSave, versionRestore, versionRemove, compareChange, versionsPanelChange{ version }, { open, from, to, layout }Versions.
export, import{ format, filename, pages }, { format, mode, warnings }Files.
mathInsert, mathUpdate, mathRemove{ latex, display, previous }Formulas.
accessibilityCheck, accessibilityFix, accessibilityFocus, accessibilityPanelChange{ issues, counts }, { issue, fix }, { id, issue }, { open }Accessibility checker.
aiStart, aiChunk, aiDone, aiError, aiStop, aiRetry, aiAccept, aiReject, aiPanelChange{ command, text, delta, … }AI assistant.
pagesChange, zoomChange, print{ enabled, pages }, { zoom, mode }, { pages, window }Page view.
collabSend, remoteChange, collabStatus, peersChange{ seq, ops, queued }, { client, seq, ops }, { online, pending }, { peers }Collaboration.

Methods

MethodReturnsDescription
setData, getData, setOptions, setOption, getOption, getState, setState, setTheme, on, once, off, use, t, destroy—Common methods (see Core concepts).
getText, getWordCountstring / countsText.
exec, isActive, transact, insertHTML, insertTextthis / booleanCommands.
undo, redo, canUndo, canRedothis / booleanHistory.
focus, blur, focusToolbarthis / booleanFocus.
setMode, getMode, toggleFullscreen, isFullscreen, toggleFocusMode, isFocusMode, toggleOutline, isOutlineOpenthis / valueView.
setDirection, getDirection, setStyle, getStylethis / valueDirection, look.
uploadFiles, openFilePicker, getUploads, abortUpload, insertEmbedPromise / this / list / numberFiles and embeds.
find, findNext, findPrevious, replace, replaceAll, clearFind, openFind, closeFind, isFindOpenresult / number / thisFind and replace.
insertMath, openMathDialog, getFormulasresult / listFormulas.
setTrackChanges, isTrackingChanges, getChanges, acceptChange, rejectChange, acceptAllChanges, rejectAllChanges, nextChange, previousChange, goToChange, toggleChangesPanel, isChangesPanelOpenthis / list / boolean / numberTrack changes.
addComment, addReply, updateComment, removeComment, resolveComment, reopenComment, getComments, getComment, setComments, nextComment, previousComment, goToComment, toggleCommentsPanel, isCommentsPanelOpen, openCommentFormthread / boolean / listComments.
saveVersion, getVersions, getVersion, setVersions, removeVersion, restoreVersion, compareVersions, showCompare, hideCompare, isCompareOpen, toggleVersionsPanel, isVersionsPanelOpenversion / list / comparisonVersions.
exportHTML, exportMarkdown, importMarkdown, importDOCX, getPDF, exportPDF, toPdfDocument, addToPdfDocument, previewPDF, getDOCX, exportDOCXstring / PromiseImport and export.
loadDraft, clearDraftboolean / thisAutosave draft.
checkAccessibility, fixAccessibilityIssue, goToAccessibilityIssue, toggleAccessibilityPanel, isAccessibilityPanelOpenresult / booleanAccessibility checker.
runAI, acceptAI, rejectAI, stopAI, retryAI, getAIState, isAIAvailable, openAIPanel, closeAIPanel, getAITools, callAIToolPromise / boolean / stateAI.
setPages, isPagesView, getPageCount, getCurrentPage, goToPage, setZoom, getZoom, print, getPrintHtmlthis / number / Promise / stringPage view.
collaborate, getCollaboration, getPeerssession / listCollaboration.

The TypeScript declarations (vibefox-js-editor.d.ts) describe every option, payload and return type in detail: EditorOptions, EditorEvents, EditorState, EditorCommand, EditorUpload, EditorPdfOptions, EditorDocxOptions, EditorCommentThread, EditorAIOptions, EditorCollabOptions, EditorTypeSpec and others.

Troubleshooting

No styles

Link vibefox-js-editor.css next to the script. Without it the component works but is unstyled, and the console shows one warning "VibeFox JS stylesheet is not loaded". In a bundler, import @vibefox/js-editor/css. The framework wrappers do not add the CSS for you.

My CSS does not apply, or a page CSS framework changes the component

Your rules win over the library rules without !important because the library CSS is in @layer vfjs. If they still do not apply, check the class names: state classes have the library prefix (vfjs-editor-is-active, not is-active). The library never uses generic class names, so page CSS frameworks do not change it.

ES modules do not load from disk

Browsers load <script type="module"> only over http(s). Use a local web server, or use vibefox-js-editor.global.js, which also works from file://.

Content Security Policy

The library does not use eval or inline scripts and loads nothing from the network. It sets inline styles on its elements (sizes and positions), so a policy with style-src must allow them ('unsafe-inline' for style attributes). Embedded players need frame-src for their hosts (only with embed.live: true in the editor, and on the pages that show the content); uploads, the AI adapter and the collaboration transport are your own requests (connect-src); images need img-src (data URLs too when you insert images without an upload adapter).

Text in the PDF is not in my font

The library ships no fonts. The PDF uses the standard PDF fonts; text outside them stays selectable but is drawn with a fallback. Pass your own font files with embedFonts (.ttf, .otf or .woff), or embedFonts: true to take the @font-face fonts of the page.

Nothing is shown

The target element must exist when createEditor runs (a selector that finds nothing throws an error). An inline or balloon editor has no frame: it looks like the text of your page until it gets the focus.

My HTML loses attributes, classes or scripts

The sanitizer keeps only the tags, attributes and classes the editor knows. Declare your own blocks with registerBlock() / registerInline() (their declared attributes are kept), and allow iframe hosts with embed.allow. sanitize: false turns the sanitizer off — only for HTML you trust.

The upload button or the AI items are missing

The file item is shown only with an upload adapter, the AI items only with an ai adapter.

Code is not colored, find matches are not highlighted

These colors use the CSS Custom Highlight API; a browser without it shows the text without them. Very long code blocks (over codeBlock.maxLength) are not colored.

The text of getData() has <ins>, <del> or comment spans

Suggestions and comment anchors are part of the content. getData({ changes: 'final', comments: false }) returns the clean text with every change accepted.

Copy and paste do not work

The browser gives clipboard access only on secure pages (https or localhost) and after a user action.

Limitations

  • Tab inside a list item nests the item; keyboard users leave the editor with Shift+Tab outside lists, or Esc and then Tab.
  • Block indent uses one unit (indentStep); a margin written in another unit counts as level 0. Live players (embed.live: true) take the mouse: select the embed by its caption or border.
  • Code colors are colors only (no bold or italic tokens); language detection is a heuristic; addCodeLanguage() after an editor is created colors its blocks on the next change.
  • Track changes: a structural change over other suggestions absorbs them; another author's inserted block, row, column or paragraph break cannot be deleted as a suggestion (text inside them can); the HTML source view is not tracked.
  • Comments and versions live in the editor: several people at once need your server (events and setComments() / setVersions()) or a collaboration session. The comparison works on stored HTML: a split paragraph shows as a changed and an inserted one, a moved block as a deletion and an insertion.
  • PDF: no hyphenation and no text shaping (Arabic letters are not joined); without embedFonts the standard PDF fonts are used with the widths of the editor fonts; floating images are placed as blocks.
  • DOCX export: images that cannot be fetched (CORS) are written as their alt text; floats are inline. DOCX import: floating images become inline, text boxes become paragraphs, charts, SmartArt, shapes and EMF images are skipped (with warnings), numbering formats become plain ordered lists, headers, footers and sections are not imported.
  • Formulas: browsers render MathML Core (no \cancel); in the PDF one font is used and accents are placed approximately.
  • Floating toolbars are fixed inside the editor element: an ancestor with transform or filter changes their position, an ancestor with overflow: hidden can clip popovers.
  • Accessibility checker: the language rule guesses by script (languages of one script are not told apart); the contrast rule does not check text over background images.
  • AI: one answer at a time per editor. Page view: a table row, line or image taller than a page is not cut; no widow / orphan control; print headers and footers need browser support of @page margin boxes; headers and footers are options, not edited on the sheet.
  • Collaboration: two participants moving the same list items into each other at the same moment lose the visible content of the cut block until it is moved again; a row added while another participant adds a column is padded by its author only; source view edits replace whole top-level blocks; remote change events come up to 100 ms later.
  • Framework wrappers: functions in options are compared by reference; removing a prop does not reset the option to its default; Vue watches object props shallowly.

Bug Report

Thank you for helping us improve. We carefully review every report, but we do not reply to them individually. If your report leads to a change, it will be listed in the product changelog together with the report number. To discuss something in detail, please open a support ticket.

Slide to fit the puzzle