VibeFox JS Editor — Demo
Quick start
Plain HTML
The editor of the quick start with the full toolbar and the word count in the status bar. Type / in an empty line for the block menu, select text to format it.
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) },
});Core concepts
Content
The content is HTML: the box under the editor shows getData(), the plain text and the counts after every change. The script, the event handler and the unsafe link of the initial HTML are removed by the sanitizer.
const output = document.createElement('pre');
output.style.cssText = 'height: 120px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const editor = VibeFoxJSEditor.createEditor('#app', {
toolbar: 'basic',
data: '<p>Hello <b>world</b>!<script>alert(1)<\/script></p><p><a href="javascript:alert(2)" onclick="alert(3)">A link</a> to edit.</p>',
});
function show() {
const count = editor.getWordCount();
output.textContent = editor.getData() + '\n\ntext: ' + JSON.stringify(editor.getText()) + '\nwords: ' + count.words + ', chars: ' + count.chars;
}
editor.on('change', show);
show();Creating and destroying
The buttons call the methods of the instance: replace the content, make it read only, change the height, destroy the editor and create it again.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
let editor = null;
function create() {
editor?.destroy();
editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>Hello</p>', toolbar: 'basic' });
}
create();
addButtons([
['setData', () => editor.setData('<h2>Title</h2><p>Text set by <code>setData()</code>.</p>')],
['Read only', () => editor.setOptions({ readonly: !editor.getOption('readonly') })],
['maxHeight 120px', () => editor.setOption('maxHeight', '120px')],
['Destroy', () => { editor.destroy(); editor = null; }],
['Create', create],
]);Commands
Each button runs one command with exec() at the caret, as an undo step; the last button makes two inserts one step with transact(). Click into the text, then a button; Ctrl+Z undoes it.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', {
data: '<p>Click into this line, then a button.</p>',
toolbar: [['undo', 'redo'], ['blockFormat'], ['bold', 'italic', 'textColor'], ['table', 'link']],
});
const run = (name, value) => () => { editor.focus(); editor.exec(name, value); };
addButtons([
['h2', run('h2')],
['bold', run('bold')],
['table 3 × 3', run('table', { rows: 3, cols: 3, header: true })],
['link', run('link', { href: 'https://example.com', text: 'Example', newTab: true })],
['blue text', run('textColor', '#2563eb')],
['transact', () => { editor.focus(); editor.transact(() => { editor.insertText('Done. '); editor.insertHTML('<i>Thanks</i>'); }); }],
]);Events
Every event handler receives one payload object; the list under the editor shows the latest events. Type, select text or press Ctrl+Z.
const output = document.createElement('pre');
output.style.cssText = 'height: 110px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>Type here or select some words.</p>', toolbar: 'basic' });
const write = (text) => { output.textContent = text + '\n' + output.textContent; };
editor.on('change', (e) => write('change ' + e.source + ', ' + e.html.length + ' chars of HTML'));
editor.on('selectionChange', (e) => write('selectionChange collapsed=' + e.collapsed + ' text=' + JSON.stringify(e.text)));
editor.on('wordCountChange', (e) => write('wordCountChange ' + e.words + ' words'));
editor.on('undo', () => write('undo'));State snapshots
getState() is a JSON snapshot of the content and the view (here: the source mode and the find bar). Save, change something, then restore.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>Saved state: this text, the mode and the find bar.</p>', toolbar: 'basic' });
let saved = null;
addButtons([
['Save state', () => { saved = JSON.stringify(editor.getState()); }],
['Change', () => { editor.setData('<p>Something else.</p>'); editor.openFind(); }],
['Source mode', () => editor.setMode(editor.getMode() === 'source' ? 'wysiwyg' : 'source')],
['Restore state', () => { if (saved) editor.setState(JSON.parse(saved)); }],
]);Writing and formatting
Typing helpers
Type @ for the mentions, / in an empty line for the block menu, # , - or **bold** for Markdown shortcuts, and quotes or -- for smart typography. The autosave event is shown under the editor.
const output = document.createElement('pre');
output.style.cssText = 'height: 40px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const users = [{ id: 1, label: 'Alice' }, { id: 2, label: 'Bob' }, { id: 3, label: 'Carol' }];
const notes = VibeFoxJSEditor.createEditor('#app', {
data: '<p>Ask @ about the plan.</p><p><br></p>',
minHeight: '220px',
mentions: { items: async (q) => users.filter((u) => u.label.toLowerCase().startsWith(q.toLowerCase())) },
autosave: { enabled: true, interval: 2000, key: 'demo-notes-draft' },
});
notes.on('mentionInsert', (e) => { output.textContent = 'mention: ' + JSON.stringify(e); });
notes.on('autosave', (e) => { output.textContent = 'autosave at ' + new Date(e.time).toLocaleTimeString() + ': ' + e.html.length + ' chars'; });Formatting options
The font and size menus of the toolbar list your own fonts and sizes; Tab nests a list item. The buttons open the special characters and emoji panels.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', {
data: '<p style="font-family: Georgia, serif">A paragraph in Georgia.</p><ul><li>First item</li><li>Second item (press Tab here)</li></ul>',
toolbar: [['fontFamily', 'fontSize', 'lineHeight'], ['bold', 'italic', 'textColor', 'bgColor'], ['ul', 'ol', 'outdent', 'indent'], ['specialChars', 'emoji']],
format: {
fonts: ['Georgia, serif', { label: 'Mono', value: 'ui-monospace, monospace' }, 'system-ui, sans-serif'],
fontSizes: ['12px', '16px', '24px'],
lineHeights: ['1', '1.5', '2'],
indentStep: '1.5em',
},
});
addButtons([
['Special characters', () => { editor.focus(); editor.exec('specialChars'); }],
['Emoji', () => { editor.focus(); editor.exec('emoji'); }],
['Insert ★', () => { editor.focus(); editor.exec('specialChars', '★'); }],
]);Paste
The button pastes the HTML of a Word document through cleanExternalHtml(): the list, heading and table stay, the Word styles go. Paste your own text from Word or Google Docs too.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>Paste below this line.</p>', toolbar: 'basic' });
editor.on('paste', (e) => console.log('paste', e.kind));
const fromWord = '<h1 class="MsoTitle" style="mso-style-name:Title">Quarterly report</h1>' +
'<p class="MsoListParagraphCxSpFirst" style="mso-list:l0 level1 lfo1"><span style="mso-list:Ignore">1.</span> Sales grew</p>' +
'<p class="MsoListParagraphCxSpLast" style="mso-list:l0 level1 lfo1"><span style="mso-list:Ignore">2.</span> Costs fell</p>' +
'<table class="MsoTableGrid" border="1"><tr><td><p class="MsoNormal"><b>Region</b></p></td><td><p class="MsoNormal"><b>Sales</b></p></td></tr>' +
'<tr><td><p class="MsoNormal">Europe</p></td><td><p class="MsoNormal">1 200</p></td></tr></table>';
addButtons([
['Paste Word HTML', () => { editor.focus(); editor.insertHTML(VibeFoxJSEditor.cleanExternalHtml(fromWord)); }],
]);Toolbar and modes
Toolbar
Your own toolbar layout in groups, with the HTML source view, the outline of the headings, focus mode and full screen at the end.
const doc = '<h2>Release notes</h2>' +
'<p>Version <b>2.4</b> brings <i>faster search</i>, a new <a href="https://example.com">export</a> and many small fixes.</p>' +
'<ul><li>Search is three times faster</li><li>Export to PDF and Word</li><li>Dark theme</li></ul>' +
'<blockquote><p>The best release so far. — Ann, product manager</p></blockquote>';
const editor = VibeFoxJSEditor.createEditor('#app', {
data: doc + '<h3>Known issues</h3><p>None so far.</p>',
toolbar: [['undo', 'redo'], ['blockFormat'], ['bold', 'italic', 'link'], ['ul', 'ol', 'checklist'], ['table', 'image'], ['source', 'outline', 'focus', 'fullscreen']],
stickyToolbar: true,
statusbar: true,
});Classic, inline and balloon
Top: an inline editor keeps the look of the page and shows its toolbar above the block while editing. Bottom: a balloon editor shows a small toolbar at the selection and a "+" at an empty line. Click into the texts.
const app = document.getElementById('app');
app.innerHTML = '<div id="inline"><h2>About us</h2><p>Click to edit this text in place: the toolbar floats above the block.</p></div>' +
'<hr><div id="balloon"><p>Select a word here for the balloon toolbar.</p><p><br></p></div>';
app.style.cssText = 'padding-top: 48px; font-family: Georgia, serif';
const inline = VibeFoxJSEditor.createEditor('#inline', { ui: 'inline' });
const balloon = VibeFoxJSEditor.createEditor('#balloon', { ui: 'balloon' });One toolbar for several editors
The title and the body are two inline editors under one toolbar: it works on the editor that has the focus.
document.querySelector('#app').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 text. Click here or into the title, then use the toolbar.</p>' });
const bar = VibeFoxJSEditor.createSharedToolbar('#bar', { editors: [title, body], toolbar: 'basic' });
bar.on('activeChange', (e) => console.log('active editor changed'));Images, files and embeds
Uploads
The upload adapter here is a stub that only waits and shows the progress (a real one sends the file to your server). Click the button, pick a file with the toolbar, or drop an image into the text.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', {
data: '<p>Images and files go to the upload adapter.</p>',
toolbar: [['bold', 'italic'], ['image', 'file']],
upload: {
// stub: a real adapter sends the file to your server and returns its URL
handler: async (file, { onProgress }) => {
for (let i = 1; i <= 10; i++) { await new Promise((r) => setTimeout(r, 120)); onProgress(i / 10); }
const url = await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(file);
});
return file.type.startsWith('image/') ? { url, alt: file.name } : { url, name: file.name };
},
accept: ['image/*', '.pdf', '.txt'],
maxSize: 10e6,
},
});
editor.on('uploadDone', (e) => console.log('uploaded', e.file.name));
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="240" height="120"><rect width="240" height="120" rx="12" fill="#2563eb"/>' +
'<text x="120" y="68" font-size="22" text-anchor="middle" fill="#fff" font-family="sans-serif">chart.svg</text></svg>';
addButtons([
['Upload a sample image', () => { editor.focus(); editor.uploadFiles([new File([svg], 'chart.svg', { type: 'image/svg+xml' })]); }],
['Upload a text file', () => { editor.focus(); editor.uploadFiles([new File(['Hello'], 'notes.txt', { type: 'text/plain' })]); }],
]);Embeds
A YouTube link becomes an embed without a network request: the editor shows a placeholder until the players are allowed to load (embed.live). Paste a YouTube or Vimeo link into an empty line too.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>The video:</p><p><br></p>', toolbar: [['bold', 'italic'], ['link', 'embed']] });
editor.on('embedInsert', (e) => console.log(e.provider, e.src));
addButtons([
['Insert a YouTube video', async () => {
editor.focus();
const res = await editor.insertEmbed('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
console.log(res.ok, res.provider, res.src); // youtube-nocookie.com player
}],
]);Tables
A table with a header row; the commands add a row below "Pro", merge two of its cells, color them and set the column widths. Drag a column border, right-click a cell for the table menu.
const editor = VibeFoxJSEditor.createEditor('#app', {
data: '<p>Prices</p><table><thead><tr><th>Plan</th><th>Month</th><th>Year</th></tr></thead>' +
'<tbody><tr><td>Basic</td><td>$10</td><td>$100</td></tr><tr><td>Pro</td><td>$25</td><td>$250</td></tr></tbody></table>',
});
const cell = (row, col) => editor.content.querySelectorAll('tr')[row].children[col];
const caretIn = (el) => getSelection().setBaseAndExtent(el, 0, el, 0);
editor.focus();
caretIn(cell(2, 0));
editor.exec('rowBelow');
caretIn(cell(3, 0));
editor.exec('mergeRight');
editor.exec('cellProps', { background: '#fef3c7', align: 'center', valign: 'middle' });
editor.exec('columnWidths', [50, 25, 25]);
editor.on('columnResize', (e) => console.log(e.widths));Find and replace
The find bar is open with a regular expression; the matches are highlighted. Click the buttons, or press Ctrl+F / Ctrl+H in the text.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>Color and colour. COLOR! The colors of the color picker.</p>' });
console.log(editor.find('colou?r', { regex: true })); // { total, index }
editor.openFind({ replace: true });
addButtons([
['Next', () => editor.findNext()],
['Replace with "shade"', () => editor.replace('shade')],
['Replace all with "tone"', () => editor.replaceAll('tone', { query: 'colou?r', regex: true, caseSensitive: false })],
['Clear', () => editor.clearFind()],
]);Code blocks
Code blocks are colored by language: SQL, Python and an own INI language added with addCodeLanguage(). The chip on a block picks the language; type ```js and Enter for a new block.
VibeFoxJSEditor.addCodeLanguage({ id: 'ini', label: 'INI', rules: [['comment', /;.*/], ['property', /^[\w.]+(?=\s*=)/m], ['string', /=.*/]], multiline: true });
const editor = VibeFoxJSEditor.createEditor('#app', {
data: '<pre><code class="language-sql">SELECT id, name FROM users WHERE active = 1 ORDER BY name;</code></pre>' +
'<pre><code class="language-python">def area(r):\n # circle\n return 3.14159 * r ** 2</code></pre>' +
'<pre><code class="language-ini">; settings\nhost = example.com\nport = 8080</code></pre>',
codeBlock: { detect: true, defaultLanguage: 'js', languages: ['js', 'ts', 'sql', 'python', 'ini'] },
});
editor.on('codeLanguageChange', (e) => console.log(e.previous, '→', e.language));Formulas
LaTeX formulas shown as MathML, inline and as a block. Click a formula to edit it in the dialog with a preview, or use the Σ button of the toolbar.
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>The mean is not greater than the length: </p>' });
const p = editor.content.querySelector('p');
getSelection().setBaseAndExtent(p, p.childNodes.length, p, p.childNodes.length);
editor.focus();
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'Track changes
Suggestion mode is on: the insertions and the deletion of Ann are colored, the panel on the side lists them. Type or delete text to add your own suggestions, accept or reject them in the panel.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>The quick brown fox jumps over the lazy dog.</p>', minHeight: '260px' });
editor.setOptions({ trackChanges: { enabled: true, author: { id: 'ann', name: 'Ann' } } });
editor.focus();
const text = editor.content.querySelector('p').firstChild;
getSelection().setBaseAndExtent(text, 4, text, 10); // "quick " is replaced: a deletion and an insertion
editor.insertText('swift ');
const p = editor.content.querySelector('p');
getSelection().setBaseAndExtent(p, p.childNodes.length, p, p.childNodes.length);
editor.insertText(' It was fast!');
editor.toggleChangesPanel(true);
console.log(editor.getChanges());
addButtons([
['Accept all', () => editor.acceptAllChanges()],
['Reject all', () => editor.rejectAllChanges()],
['Suggestion mode on / off', () => editor.setTrackChanges(!editor.isTrackingChanges())],
]);Comments
A comment thread of Bob with a reply of Ann is attached to the sentence; the panel shows the threads. Select other text and press Ctrl+Alt+M (or the comment button) to add one.
const editor = VibeFoxJSEditor.createEditor('#app', {
data: '<p>Revenue grew by 12 percent in March.</p><p>Costs stayed flat.</p>',
minHeight: '260px',
comments: { author: { id: 'ann', name: 'Ann' } },
});
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: { id: 'ann', name: 'Ann' } });
editor.toggleCommentsPanel(true);
editor.on('commentsChange', () => console.log(editor.getComments()));Versions and comparison
Two saved versions compared side by side: deleted words of the draft on the left, inserted ones on the right. The buttons switch the view and restore the draft.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>First draft of the text.</p><p>It has two short paragraphs.</p>' });
const v1 = editor.saveVersion({ name: 'Draft' });
editor.setData('<p>Second draft of the long text.</p><p>It has two short paragraphs and a list:</p><ul><li>one</li><li>two</li></ul>');
editor.saveVersion({ name: 'Review' });
const cmp = editor.compareVersions(v1.id, 'current');
console.log(cmp.stats);
editor.showCompare(v1.id, 'current', { layout: 'side' });
addButtons([
['Side by side', () => editor.showCompare(v1.id, 'current', { layout: 'side' })],
['Inline', () => editor.showCompare(v1.id, 'current', { layout: 'inline' })],
['Close', () => editor.hideCompare()],
['Versions panel', () => editor.toggleVersionsPanel()],
['Restore the draft', () => { editor.hideCompare(); editor.restoreVersion(v1.id); }],
]);Real-time collaboration
Ann and Bob edit one document in two editors; the transport here is a small relay in the page instead of a server. Type in one editor: the text, the cursor and the name tag appear in the other.
const app = document.getElementById('app');
app.innerHTML = '<div id="ann"></div><div id="bob" style="margin-top: 8px"></div>';
// the relay: in a real page send() goes to your WebSocket / WebRTC / server
const members = [];
function relay() {
const me = { listeners: [] };
members.push(me);
return {
send: (msg) => {
const copy = JSON.parse(JSON.stringify(msg));
setTimeout(() => { for (const m of members) if (m !== me) m.listeners.forEach((fn) => fn(copy)); }, 50);
},
onMessage: (fn) => { me.listeners.push(fn); },
};
}
const data = '<h3>Meeting notes</h3><p>Agenda: the release of version 2.4.</p><ul><li>Ann: the release notes</li><li>Bob: the tests</li></ul>';
const ann = VibeFoxJSEditor.createEditor('#ann', { data, toolbar: 'basic', minHeight: '120px' });
const bob = VibeFoxJSEditor.createEditor('#bob', { data, toolbar: 'basic', minHeight: '120px' });
const sessionA = ann.collaborate({ room: 'notes', transport: relay(), user: { name: 'Ann', color: 1 } });
const sessionB = bob.collaborate({ room: 'notes', transport: relay(), user: { name: 'Bob', color: 4 } });
bob.on('peersChange', (e) => console.log('Bob sees', e.peers.map((p) => p.name)));
// Ann types a word to show the remote cursor
setTimeout(() => {
ann.focus();
const li = ann.content.querySelector('li');
getSelection().setBaseAndExtent(li.firstChild, li.firstChild.length, li.firstChild, li.firstChild.length);
ann.insertText(' (draft ready)');
}, 300);Import and export
HTML and Markdown
The buttons download the document as HTML or Markdown, show the Markdown under the editor and import Markdown with a task list and a table.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const doc = '<h2>Release notes</h2>' +
'<p>Version <b>2.4</b> brings <i>faster search</i>, a new <a href="https://example.com">export</a> and many small fixes.</p>' +
'<ul><li>Search is three times faster</li><li>Export to PDF and Word</li><li>Dark theme</li></ul>' +
'<blockquote><p>The best release so far. — Ann, product manager</p></blockquote>';
const output = document.createElement('pre');
output.style.cssText = 'height: 90px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const editor = VibeFoxJSEditor.createEditor('#app', { data: doc, toolbar: 'basic' });
addButtons([
['Download HTML', () => editor.exportHTML({ download: true, filename: 'release-notes.html' })],
['Download Markdown', () => editor.exportMarkdown({ download: true, filename: 'release-notes.md' })],
['Show Markdown', () => { output.textContent = editor.exportMarkdown(); }],
['Import Markdown', () => editor.importMarkdown('# Title\n\n- [x] done\n- [ ] todo\n\n| a | b |\n|---|---|\n| 1 | 2 |')],
]);The PDF is made in the browser: vector pages with selectable text, a header and page numbers. Click the button to download it.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const doc = '<h2>Release notes</h2>' +
'<p>Version <b>2.4</b> brings <i>faster search</i>, a new <a href="https://example.com">export</a> and many small fixes.</p>' +
'<ul><li>Search is three times faster</li><li>Export to PDF and Word</li><li>Dark theme</li></ul>' +
'<blockquote><p>The best release so far. — Ann, product manager</p></blockquote>';
const editor = VibeFoxJSEditor.createEditor('#app', {
data: doc + '<table><tr><th>Region</th><th>Sales</th></tr><tr><td>Europe</td><td>1 200</td></tr><tr><td>America</td><td>950</td></tr></table>',
});
const info = addButtons([
['Download PDF', async () => {
const bytes = await editor.exportPDF('release-notes.pdf', {
pageSize: 'A4', header: '{title}', footer: { text: 'Page {page} of {pages}', align: 'center' }, title: 'Release notes',
});
info.lastChild.textContent = 'release-notes.pdf: ' + Math.round(bytes.length / 1024) + ' KB';
}],
]);
info.append(document.createElement('span'));Word (.docx)
The document with a suggestion and a comment downloads as a Word file with real revisions and comments; "Import" reads the .docx back into the editor.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const editor = VibeFoxJSEditor.createEditor('#app', {
data: '<h2>Contract</h2><p>The term of the contract is one year.</p>',
trackChanges: { author: { id: 'ann', name: 'Ann' } },
});
editor.setTrackChanges(true);
editor.focus();
editor.insertText(' It renews every year.');
editor.setTrackChanges(false);
const range = document.createRange();
range.selectNodeContents(editor.content.querySelector('h2'));
editor.addComment('Use the full name of the contract.', { range, author: { id: 'bob', name: 'Bob' } });
const info = addButtons([
['Download .docx', () => editor.exportDOCX('contract.docx', { changes: 'markup', comments: true })],
['Import the .docx back', async () => {
const docx = await editor.getDOCX({ changes: 'markup', comments: true, font: 'Calibri' });
const result = await editor.importDOCX(docx, { changes: 'markup', comments: true, images: 'inline' });
info.lastChild.textContent = 'imported ' + Math.round(docx.length / 1024) + ' KB, warnings: ' + result.warnings.length;
}],
]);
info.append(document.createElement('span'));Page view and printing
The document on Letter sheets with a header, page numbers and a page break, at 60% zoom. Press Ctrl+Enter for another page break; "Print" prints the sheets.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const doc = '<h2>Release notes</h2>' +
'<p>Version <b>2.4</b> brings <i>faster search</i>, a new <a href="https://example.com">export</a> and many small fixes.</p>' +
'<ul><li>Search is three times faster</li><li>Export to PDF and Word</li><li>Dark theme</li></ul>' +
'<blockquote><p>The best release so far. — Ann, product manager</p></blockquote>';
const editor = VibeFoxJSEditor.createEditor('#app', { data: doc + '<p>More text on the second page.</p>', maxHeight: '520px' });
editor.setPages({ size: 'Letter', orientation: 'portrait', margin: '2cm', header: 'Release notes', pageNumbers: true,
firstPage: { header: null }, zoom: 0.6 });
const p = editor.content.querySelectorAll('p')[1];
getSelection().setBaseAndExtent(p, 0, p, 0);
editor.focus();
editor.exec('pageBreak');
console.log(editor.getPageCount(), editor.getCurrentPage(), editor.getZoom());
addButtons([
['Zoom 100%', () => editor.setZoom(1)],
['Fit width', () => editor.setZoom('width')],
['Print', () => editor.print()],
]);AI assistant
The adapter here is a stub model in the page that streams ready answers (a real one calls your model). Click "Summarize", or select a sentence and use the AI button of the toolbar (Ctrl+J), then accept or discard the answer.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const answers = {
rewrite: 'Our team shipped version 2.4 on time, and the first customers like it a lot.',
grammar: 'We released the new version on Friday, and the customers are happy with it.',
translate: 'Wir haben die neue Version am Freitag veröffentlicht, und die Kunden sind zufrieden.',
summarize: 'Version 2.4 was released on Friday; customers are happy.',
continue: ' Next month we will add comments and version history.',
};
async function* stubModel(prompt, ctx) {
const answer = answers[ctx.command] || 'A stub answer to: ' + ctx.instruction;
for (const word of answer.split(/(?<= )/)) {
await new Promise((resolve) => setTimeout(resolve, 60));
if (ctx.signal.aborted) return;
yield word;
}
}
const editor = VibeFoxJSEditor.createEditor('#app', {
data: '<p>we released the new version on friday and the customers is happy with it.</p><p>The release took three weeks.</p>',
minHeight: '220px',
ai: {
stream: stubModel,
commands: ['rewrite', 'grammar', 'translate', 'summarize', 'continue', { id: 'title', label: 'Suggest a title', prompt: 'Suggest a title for this text.', insert: 'after' }],
languages: ['en', 'de', 'fr'],
},
});
addButtons([
['Summarize', async () => {
const p = editor.content.querySelector('p');
getSelection().setBaseAndExtent(p, 0, p, p.childNodes.length);
const r = await editor.runAI('summarize');
console.log(r.ok, r.text);
}],
['Fix grammar and accept', async () => {
const p = editor.content.querySelector('p');
getSelection().setBaseAndExtent(p, 0, p, p.childNodes.length);
await editor.runAI('grammar', { apply: true });
}],
['Open the AI panel', () => { editor.focus(); editor.openAIPanel(); }],
]);Accessibility checker
The panel lists the problems of the document: an image without alt text, a skipped heading level, a vague link. Click an issue to go to it, or use its quick fix.
const editor = VibeFoxJSEditor.createEditor('#app', { minHeight: '300px' });
editor.setData('<h1>Report</h1><h3>Sales</h3><p><img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==" width="80" height="40"></p>' +
'<p>For the details <a href="/report">click here</a>.</p><p style="color: #bbbbbb">Light gray text is hard to read.</p>');
const { issues, counts } = editor.checkAccessibility({ level: 'AA' });
console.log(counts, issues.map((i) => i.rule));
editor.toggleAccessibilityPanel(true);Own blocks and inline nodes
A "callout" block and a "kbd" inline node registered by the page, with their toolbar buttons and slash entries. Click into a paragraph and use the Callout button, or type /callout.
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 style = document.createElement('style');
style.textContent = '.callout { border-left: 4px solid #2563eb; background: #eff6ff; padding: 4px 12px; margin: 8px 0; }' +
'.callout[data-kind="warning"] { border-color: #d97706; background: #fffbeb; }' +
'kbd { border: 1px solid #94a3b8; border-bottom-width: 2px; border-radius: 4px; padding: 0 4px; font: 0.9em ui-monospace, monospace; }';
document.head.append(style);
const doc = VibeFoxJSEditor.createEditor('#app', {
data: '<p>Press <kbd data-vfjs-inline="kbd">Ctrl</kbd> + <kbd data-vfjs-inline="kbd">S</kbd> to save.</p><p>Back up your files first.</p>',
toolbar: [['bold', 'italic'], ['callout', 'kbd']],
});
const p = doc.content.querySelectorAll('p')[1];
getSelection().setBaseAndExtent(p.firstChild, 0, p.firstChild, 0);
doc.focus(); doc.exec('callout', { kind: 'warning' });
console.log(VibeFoxJSEditor.getBlockTypes().map((t) => t.name));Theming and styling
Themes
The list switches the theme of the editor: the built-in light, dark and high-contrast themes and the themes of vibefox-js-themes.css, plus an own theme "brand".
function addSelect(label, values, onChange) {
const select = document.createElement('select');
select.setAttribute('aria-label', label);
for (const value of values) select.append(new Option(label + ': ' + value, value));
select.onchange = () => onChange(select.value);
document.getElementById('app').before(select);
return select;
}
const doc = '<h2>Release notes</h2>' +
'<p>Version <b>2.4</b> brings <i>faster search</i>, a new <a href="https://example.com">export</a> and many small fixes.</p>' +
'<ul><li>Search is three times faster</li><li>Export to PDF and Word</li><li>Dark theme</li></ul>' +
'<blockquote><p>The best release so far. — Ann, product manager</p></blockquote>';
VibeFoxJSEditor.registerTheme('brand', { accent: '#e11d48', 'accent-fg': '#ffffff', radius: '10px' });
const editor = VibeFoxJSEditor.createEditor('#app', { data: doc, theme: 'dark' });
const themes = ['dark', 'light', 'high-contrast', 'high-contrast-light', 'paper', 'paper-dark', 'glass', 'glass-dark', 'classic', 'classic-dark',
'ocean', 'ocean-dark', 'forest', 'forest-dark', 'sunset', 'sunset-dark', 'graphite', 'graphite-dark', 'brand'];
addSelect('Theme', themes, (name) => editor.setTheme(name));CSS variables
One rule for all VibeFox JS components (accent and radius) and one for this editor only (toolbar background, padding and font size of the text).
const doc = '<h2>Release notes</h2>' +
'<p>Version <b>2.4</b> brings <i>faster search</i>, a new <a href="https://example.com">export</a> and many small fixes.</p>' +
'<ul><li>Search is three times faster</li><li>Export to PDF and Word</li><li>Dark theme</li></ul>' +
'<blockquote><p>The best release so far. — Ann, product manager</p></blockquote>';
const css = document.createElement('style');
css.textContent = '.vfjs { --vfjs-accent: #0f766e; --vfjs-radius: 4px; }' +
'#notes { --vfjs-editor-toolbar-bg: #f0fdfa; --vfjs-editor-content-padding: 24px; --vfjs-editor-font-size: 17px; --vfjs-editor-heading-fg: #0f766e; }';
document.head.append(css);
document.getElementById('app').innerHTML = '<div id="notes"></div>';
const editor = VibeFoxJSEditor.createEditor('#notes', { data: doc, toolbar: 'basic' });Ready-made styles
The list switches the ready-made styles: classic, minimal and floating.
function addSelect(label, values, onChange) {
const select = document.createElement('select');
select.setAttribute('aria-label', label);
for (const value of values) select.append(new Option(label + ': ' + value, value));
select.onchange = () => onChange(select.value);
document.getElementById('app').before(select);
return select;
}
const doc = '<h2>Release notes</h2>' +
'<p>Version <b>2.4</b> brings <i>faster search</i>, a new <a href="https://example.com">export</a> and many small fixes.</p>' +
'<ul><li>Search is three times faster</li><li>Export to PDF and Word</li><li>Dark theme</li></ul>' +
'<blockquote><p>The best release so far. — Ann, product manager</p></blockquote>';
const editor = VibeFoxJSEditor.createEditor('#app', { data: doc, style: 'floating' });
addSelect('Style', ['floating', 'classic', 'minimal'], (name) => editor.setStyle(name));
editor.on('styleChange', (e) => console.log(e.style));Density and size
The lists set data-vfjs-density on the container and the scale --vfjs-size-unit: the toolbar buttons and paddings follow.
function addSelect(label, values, onChange) {
const select = document.createElement('select');
select.setAttribute('aria-label', label);
for (const value of values) select.append(new Option(label + ': ' + value, value));
select.onchange = () => onChange(select.value);
document.getElementById('app').before(select);
return select;
}
const doc = '<h2>Release notes</h2>' +
'<p>Version <b>2.4</b> brings <i>faster search</i>, a new <a href="https://example.com">export</a> and many small fixes.</p>' +
'<ul><li>Search is three times faster</li><li>Export to PDF and Word</li><li>Dark theme</li></ul>' +
'<blockquote><p>The best release so far. — Ann, product manager</p></blockquote>';
const app = document.getElementById('app');
const editor = VibeFoxJSEditor.createEditor('#app', { data: doc, toolbar: 'basic' });
app.dataset.vfjsDensity = 'compact';
addSelect('Density', ['compact', 'normal', 'comfortable'], (value) => { app.dataset.vfjsDensity = value; });
addSelect('Size unit', ['1px', '1.25px', '0.85px'], (value) => app.style.setProperty('--vfjs-size-unit', value));Your own CSS
Plain CSS rules of the page change the active toolbar buttons and the headings, without !important. Put the caret into the bold word to see the active button.
const doc = '<h2>Release notes</h2>' +
'<p>Version <b>2.4</b> brings <i>faster search</i>, a new <a href="https://example.com">export</a> and many small fixes.</p>' +
'<ul><li>Search is three times faster</li><li>Export to PDF and Word</li><li>Dark theme</li></ul>' +
'<blockquote><p>The best release so far. — Ann, product manager</p></blockquote>';
const css = document.createElement('style');
css.textContent = '.vfjs-editor-toolbar .vfjs-editor-btn.vfjs-editor-is-active { color: #fff; background: #1d4ed8; }' +
'.vfjs-editor-content h2 { letter-spacing: -0.01em; border-bottom: 2px solid #1d4ed8; }' +
'.vfjs-editor-content blockquote { font-style: italic; }';
document.head.append(css);
const editor = VibeFoxJSEditor.createEditor('#app', { data: doc, toolbar: 'basic' });
editor.focus();
const b = editor.content.querySelector('b');
getSelection().setBaseAndExtent(b.firstChild, 1, b.firstChild, 1);Localization and RTL
Languages
The editor in Russian, with the language pack vibefox-js-editor.ru.js loaded after the library: the tooltips, menus, the placeholder and the status bar. The list switches the language of this editor.
function addSelect(label, values, onChange) {
const select = document.createElement('select');
select.setAttribute('aria-label', label);
for (const value of values) select.append(new Option(label + ': ' + value, value));
select.onchange = () => onChange(select.value);
document.getElementById('app').before(select);
return select;
}
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<p>Текст документа не переводится.</p><p><br></p>', locale: 'ru' });
addSelect('Locale', ['ru', 'en'], (lang) => editor.setOptions({ locale: lang }));Adding a language
A partial German dictionary: the placeholder, the status bar and some tooltips are German, the missing keys fall back to English.
VibeFoxJSEditor.addLocale('de', {
'editor.placeholder': 'Schreiben Sie, oder drücken Sie „/“ für Blöcke…',
'editor.bold': 'Fett',
'editor.italic': 'Kursiv',
'editor.underline': 'Unterstrichen',
'editor.undo': 'Rückgängig',
'editor.redo': 'Wiederholen',
'editor.words': 'Wörter',
'editor.chars': 'Zeichen',
});
const editor = VibeFoxJSEditor.createEditor('#app', { locale: 'de', toolbar: 'basic' });Right-to-left
A right-to-left document: the toolbar, lists and quotes are mirrored; the toolbar has the buttons for left-to-right and right-to-left paragraphs. The last paragraph is left-to-right.
const editor = VibeFoxJSEditor.createEditor('#app', {
dir: 'rtl',
data: '<h2>מסמך לדוגמה</h2><p>זהו טקסט בעברית שנכתב מימין לשמאל.</p><ul><li>פריט ראשון</li><li>פריט שני</li></ul>' +
'<blockquote><p>ציטוט קצר.</p></blockquote><p dir="ltr">This paragraph is left-to-right.</p>',
});
editor.on('directionChange', (e) => console.log(e.dir));Using with other VibeFox JS libraries
Connecting components with link()
The counts of the editor go to a VibeFox JS Grid table with link() (both libraries are on this page). Type in the editor and watch the table.
const app = document.getElementById('app');
app.innerHTML = '<div id="doc"></div><div id="stats" style="margin-top: 8px"></div>';
const editor = VibeFoxJSEditor.createEditor('#doc', { data: '<p>Type here: the table below counts the words.</p>', toolbar: 'basic', minHeight: '100px' });
const grid = VibeFoxJSGrid.createGrid('#stats', {
height: 140,
columns: [{ field: 'name', header: 'Count' }, { field: 'value', header: 'Value', type: 'number' }],
data: [],
});
const rows = (e) => [{ name: 'Words', value: e.words }, { name: 'Characters', value: e.chars }, { name: 'Reading time, min', value: e.readingTime }];
const unlink = VibeFoxJSEditor.link(editor, 'wordCountChange', grid, 'setData', rows);
grid.setData(rows({ ...editor.getWordCount() }));AI tools
The buttons call the tools of the editor as a model would: read the content as Markdown, replace a word, and run kit.ask() with a stub model that asks for one tool call. The results are shown under the editor.
function addButtons(buttons) {
const bar = document.createElement('div');
for (const [text, onClick] of buttons) {
const button = document.createElement('button');
button.textContent = text;
button.onclick = onClick;
bar.append(button);
}
document.getElementById('app').before(bar);
return bar;
}
const output = document.createElement('pre');
output.style.cssText = 'height: 100px; overflow: auto; margin: 6px 0 0; padding: 4px 8px; border: 1px solid #d0d7de; font: 12px ui-monospace, Consolas, monospace; white-space: pre-wrap';
document.getElementById('app').after(output);
const { describeTools, callTool, createToolKit } = VibeFoxJSEditor;
const editor = VibeFoxJSEditor.createEditor('#app', { data: '<h2>Plan</h2><p>Ship the release on Friday.</p>', toolbar: 'basic', minHeight: '120px' });
const show = (x) => { output.textContent = JSON.stringify(x, null, 1); };
// stub model: first asks for a tool call, then answers with a text (a real one is your request to a model)
let step = 0;
const stubModel = async (request) => (++step % 2
? { text: '', toolCalls: [{ id: 'c1', name: 'doc_editor_insert', arguments: { content: 'Summary: the release is on Friday.', position: 'end' } }] }
: { text: 'Added a summary at the end.' });
addButtons([
['Tool names', () => show(describeTools(editor, { format: 'openai' }).map((t) => t.function.name))],
['Get content', async () => show(await callTool(editor, 'editor_get_content', { format: 'markdown' }))],
['Replace "Friday"', async () => show(await callTool(editor, 'editor_find_replace', { query: 'Friday', replacement: 'Monday' }))],
['Ask (stub model)', async () => {
const kit = createToolKit({ doc: editor });
const answer = await kit.ask('Add a short summary at the end', { model: stubModel });
show({ text: answer.text, calls: answer.calls.map((c) => c.name) });
}],
]);