VibeFox JS Editor — Демо
Швидкий старт
Звичайний HTML
Редактор швидкого старту з повною панеллю інструментів і лічильником слів у рядку стану. Введіть / у порожньому рядку, щоб відкрити меню блоків, або виділіть текст, щоб його відформатувати.
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) },
});Основні поняття
Вміст
Вміст — це HTML: поле під редактором після кожної зміни показує getData(), звичайний текст і лічильники. Скрипт, обробник події та небезпечне посилання з початкового HTML видаляє санітизатор.
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();Створення та видалення
Кнопки викликають методи екземпляра: замінюють вміст, роблять його доступним лише для читання, змінюють висоту, видаляють редактор і створюють його знову.
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],
]);Команди
Кожна кнопка запускає одну команду exec() біля курсора як один крок відміни; остання кнопка виконує дві вставки одним кроком через transact(). Клацніть у тексті, потім натисніть кнопку; Ctrl+Z скасовує дію.
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>'); }); }],
]);Події
Кожен обробник події отримує один об'єкт із даними (payload); список під редактором показує останні події. Введіть текст, виділіть його або натисніть 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'));Знімки стану
getState() — це JSON-знімок вмісту і вигляду (тут: режим джерела та панель пошуку). Збережіть, змініть щось, потім відновіть.
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)); }],
]);Написання та форматування
Допоміжні засоби під час набору
Введіть @ для згадок, / у порожньому рядку для меню блоків, # , - або **bold** для скорочень Markdown, а лапки чи -- для розумної типографіки. Подія автозбереження показується під редактором.
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'; });Параметри форматування
Меню шрифтів і розмірів на панелі інструментів показують ваші власні шрифти та розміри; Tab вкладає пункт списку. Кнопки відкривають панелі спеціальних символів і емодзі.
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', '★'); }],
]);Вставлення
Кнопка вставляє HTML документа Word через cleanExternalHtml(): списки, заголовки й таблиця залишаються, стилі Word видаляються. Вставляйте також власний текст із Word або Google Docs.
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)); }],
]);Панель інструментів і режими
Панель інструментів
Власне розташування панелі інструментів у групах; наприкінці — перегляд HTML-коду, структура заголовків, режим фокусу та повноекранний режим.
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,
});Класичний, вбудований і спливаючий режими
Угорі: вбудований редактор зберігає вигляд сторінки і показує свою панель інструментів над блоком під час редагування. Внизу: спливаючий редактор показує малу панель інструментів біля виділення і знак «+» на порожньому рядку. Клацніть у текстах.
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' });Одна панель інструментів для кількох редакторів
Заголовок і основний текст — два вбудовані редактори під однією панеллю інструментів: вона працює з тим редактором, який має фокус.
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'));Зображення, файли та вбудовування
Завантаження
Адаптер завантаження тут є заглушкою: він лише чекає і показує прогрес (справжній надсилає файл на ваш сервер). Натисніть кнопку, виберіть файл на панелі інструментів або перетягніть зображення в текст.
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' })]); }],
]);Вбудовування
Посилання на YouTube стає вбудовуванням без мережевого запиту: редактор показує заповнювач, доки плеєри не дозволено завантажувати (embed.live). Вставте посилання на YouTube або Vimeo також у порожній рядок.
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
}],
]);Таблиці
Таблиця з рядком заголовка; команди додають рядок під «Pro», об'єднують дві її клітинки, фарбують їх і задають ширину стовпців. Перетягніть межу стовпця, клацніть правою кнопкою миші по клітинці, щоб відкрити меню таблиці.
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));Пошук і заміна
Панель пошуку відкрита з регулярним виразом; збіги виділено. Натисніть кнопки або Ctrl+F / Ctrl+H у тексті.
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()],
]);Блоки коду
Блоки коду підсвічуються за мовою: SQL, Python і власна мова INI, додана через addCodeLanguage(). Мітка на блоці вибирає мову; введіть ```js і натисніть Enter, щоб створити новий блок.
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));Формули
Формули LaTeX, показані як MathML, рядкові та блокові. Клацніть формулу, щоб змінити її в діалозі з попереднім переглядом, або скористайтеся кнопкою Σ на панелі інструментів.
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'Відстеження змін
Режим пропозицій увімкнено: вставки та видалення Ann виділено кольором, панель збоку їх перелічує. Вводьте або видаляйте текст, щоб додати власні пропозиції; приймайте або відхиляйте їх на панелі.
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())],
]);Коментарі
Гілка коментарів Bob із відповіддю Ann прикріплена до речення; панель показує гілки. Виділіть інший текст і натисніть Ctrl+Alt+M (або кнопку коментаря), щоб додати коментар.
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()));Версії та порівняння
Дві збережені версії порівнюються поруч: видалені слова чернетки ліворуч, вставлені — праворуч. Кнопки перемикають вигляд і відновлюють чернетку.
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); }],
]);Спільна робота в реальному часі
Ann і Bob редагують один документ у двох редакторах; транспорт тут — невеликий ретранслятор на сторінці, а не сервер. Введіть текст в одному редакторі: текст, курсор і мітка з іменем з'являються в іншому.
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);Імпорт і експорт
HTML і Markdown
Кнопки завантажують документ як HTML або Markdown, показують Markdown під редактором і імпортують Markdown зі списком завдань та таблицею.
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 |')],
]);PDF створюється в браузері: векторні сторінки з текстом, який можна виділяти, заголовком і номерами сторінок. Натисніть кнопку, щоб завантажити файл.
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)
Документ із пропозицією та коментарем завантажується як файл Word зі справжніми правками й коментарями; «Import» читає .docx назад в редактор.
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'));Вигляд сторінок і друк
Документ на аркушах Letter із заголовком, номерами сторінок і розривом сторінки, масштаб 60%. Натисніть Ctrl+Enter для іншого розриву сторінки; «Print» друкує аркуші.
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-асистент
Адаптер тут — це модель-заглушка на сторінці, яка передає готові відповіді потоком (справжня викликає вашу модель). Натисніть «Summarize» або виділіть речення і скористайтеся кнопкою AI на панелі інструментів (Ctrl+J), а потім прийміть або відхиліть відповідь.
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(); }],
]);Перевірка доступності
Панель показує проблеми документа: зображення без alt-тексту, пропущений рівень заголовка, нечітке посилання. Клацніть проблему, щоб перейти до неї, або скористайтеся її швидким виправленням.
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);Власні блоки та рядкові вузли
Блок «callout» і рядковий вузол «kbd», зареєстровані сторінкою, з кнопками на панелі інструментів і пунктами меню з косою рискою. Клацніть в абзаці й натисніть кнопку Callout або введіть /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));Теми та стилізація
Теми
Список перемикає тему редактора: вбудовані світла, темна та висококонтрастна теми, теми з vibefox-js-themes.css, а також власна тема «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-змінні
Одне правило для всіх компонентів VibeFox JS (акцент і радіус) і одне — лише для цього редактора (фон панелі інструментів, відступи та розмір шрифту тексту).
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' });Готові стилі
Список перемикає готові стилі: classic, minimal і 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));Щільність і розмір
Списки задають data-vfjs-density контейнеру та масштаб --vfjs-size-unit: кнопки панелі інструментів і відступи змінюються відповідно.
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));Власний CSS
Прості правила CSS сторінки змінюють активні кнопки панелі інструментів і заголовки, без !important. Поставте курсор у жирне слово, щоб побачити активну кнопку.
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);Локалізація та RTL
Мови
Редактор російською мовою з мовним пакетом vibefox-js-editor.ru.js, завантаженим після бібліотеки: підказки, меню, заповнювач і рядок стану. Список перемикає мову цього редактора.
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 }));Додавання мови
Неповний німецький словник: заповнювач, рядок стану та деякі підказки німецькою мовою, відсутні ключі повертаються до англійської.
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' });Справа наліво (RTL)
Документ справа наліво: панель інструментів, списки та цитати відзеркалені; на панелі є кнопки абзаців зліва направо і справа наліво. Останній абзац — зліва направо.
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));Робота з іншими бібліотеками VibeFox JS
Зв'язування компонентів через link()
Лічильники редактора передаються в таблицю VibeFox JS Grid через link() (обидві бібліотеки на цій сторінці). Введіть текст у редакторі і стежте за таблицею.
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-інструменти
Кнопки викликають інструменти редактора так, як це зробила б модель: читають вміст як Markdown, замінюють слово і запускають kit.ask() з моделлю-заглушкою, яка запитує один виклик інструмента. Результати показуються під редактором.
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) });
}],
]);