VibeFox JS Editor — Demo
Hızlı başlangıç
Düz HTML
Hızlı başlangıç bölümündeki editör; tam araç çubuğu ve durum çubuğunda kelime sayısıyla birlikte gelir. Blok menüsünü açmak için boş bir satıra / yazın, metni biçimlendirmek için ise metni seçin.
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) },
});Temel kavramlar
İçerik
İçerik HTML'dir: editörün altındaki kutu, her değişiklikten sonra getData() çıktısını, düz metni ve sayıları gösterir. Başlangıç HTML'indeki script, olay işleyicisi ve güvensiz bağlantı, temizleyici (sanitizer) tarafından kaldırılır.
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();Oluşturma ve yok etme
Düğmeler örneğin metotlarını çağırır: içeriği değiştirir, salt okunur hale getirir, yüksekliği değiştirir, editörü yok eder ve yeniden oluşturur.
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],
]);Komutlar
Her düğme, imlecin bulunduğu yerde exec() ile tek bir komut çalıştırır ve bunu bir geri alma adımı olarak kaydeder; son düğme ise transact() ile iki eklemeyi tek bir adımda yapar. Metnin içine tıklayın, ardından bir düğmeye basın; Ctrl+Z bunu geri alır.
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>'); }); }],
]);Olaylar
Her olay işleyicisi tek bir yük (payload) nesnesi alır; editörün altındaki liste en son olayları gösterir. Yazın, metin seçin veya Ctrl+Z tuşlarına basın.
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'));Durum anlık görüntüleri
getState(), içeriğin ve görünümün (burada: kaynak modu ve bul çubuğu) JSON anlık görüntüsünü verir. Kaydedin, bir şeyi değiştirin, sonra geri yükleyin.
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)); }],
]);Yazma ve biçimlendirme
Yazma yardımcıları
Anmalar için @, boş bir satırda blok menüsü için /, Markdown kısayolları için # , - ya da **bold**, akıllı tipografi için ise tırnak işaretleri ya da -- yazın. Otomatik kaydetme olayı editörün altında gösterilir.
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'; });Biçimlendirme seçenekleri
Araç çubuğundaki yazı tipi ve boyut menüleri kendi yazı tiplerinizi ve boyutlarınızı listeler; Tab bir liste öğesini iç içe yerleştirir. Düğmeler özel karakterler ve emoji panellerini açar.
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', '★'); }],
]);Yapıştırma
Düğme, bir Word belgesinin HTML'ini cleanExternalHtml() üzerinden yapıştırır: liste, başlık ve tablo korunur, Word stilleri ise kaldırılır. Word'den ya da Google Docs'tan kendi metninizi de yapıştırın.
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)); }],
]);Araç çubuğu ve modlar
Araç çubuğu
Gruplar halinde kendi araç çubuğu düzeniniz; sonunda HTML kaynak görünümü, başlıkların ana hatları, odak modu ve tam ekran yer alır.
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,
});Klasik, satır içi ve balon
Üstte: satır içi editör, sayfanın görünümünü korur ve düzenleme sırasında araç çubuğunu bloğun üstünde gösterir. Altta: balon editör, seçimin yanında küçük bir araç çubuğu ve boş bir satırda bir "+" gösterir. Metinlerin içine tıklayın.
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' });Birden çok düzenleyici için tek araç çubuğu
Başlık ve gövde, tek bir araç çubuğu altında iki satır içi editördür: araç çubuğu, odakta olan editör üzerinde çalışır.
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'));Görseller, dosyalar ve gömülü içerikler
Yüklemeler
Buradaki yükleme adaptörü, yalnızca bekleyen ve ilerlemeyi gösteren sahte (stub) bir adaptördür (gerçek bir adaptör dosyayı sunucunuza gönderir). Düğmeye tıklayın, araç çubuğuyla bir dosya seçin ya da bir görseli metnin içine sürükleyip bırakın.
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' })]); }],
]);Gömülü içerikler
Bir YouTube bağlantısı, ağ isteği yapılmadan gömülü içeriğe dönüşür: oynatıcıların yüklenmesine izin verilene kadar editör bir yer tutucu gösterir (embed.live). Boş bir satıra da bir YouTube ya da Vimeo bağlantısı yapıştırın.
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
}],
]);Tablolar
Başlık satırı olan bir tablo; komutlar "Pro" satırının altına bir satır ekler, iki hücresini birleştirir, bu hücreleri renklendirir ve sütun genişliklerini ayarlar. Bir sütun kenarlığını sürükleyin; tablo menüsü için bir hücreye sağ tıklayın.
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));Bul ve değiştir
Bul çubuğu, düzenli ifadeyle açıktır; eşleşmeler vurgulanır. Düğmelere tıklayın ya da metin içindeyken Ctrl+F / Ctrl+H tuşlarına basın.
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()],
]);Kod blokları
Kod blokları dile göre renklendirilir: SQL, Python ve addCodeLanguage() ile eklenen kendi INI diliniz. Bir bloktaki çip dili seçer; yeni bir blok için ```js yazıp Enter tuşuna basın.
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));Formüller
LaTeX formülleri MathML olarak, hem satır içi hem de blok olarak gösterilir. Bir formüle tıklayıp önizlemeli iletişim kutusunda düzenleyin ya da araç çubuğundaki Σ düğmesini kullanın.
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'Değişiklik takibi
Öneri modu açık: Ann'in eklemeleri ve silmesi renklendirilmiştir; yandaki panel bunları listeler. Kendi önerilerinizi eklemek için metin yazın ya da silin; panelde bunları kabul edin ya da reddedin.
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())],
]);Yorumlar
Ann'in yanıtı bulunan Bob'un bir yorum dizisi cümleye iliştirilmiştir; panel dizileri gösterir. Başka bir metin seçin ve bir tane eklemek için Ctrl+Alt+M'ye (ya da yorum düğmesine) basın.
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()));Sürümler ve karşılaştırma
Yan yana karşılaştırılan iki kayıtlı sürüm: taslağın silinen kelimeleri solda, eklenenler sağda. Düğmeler görünümü değiştirir ve taslağı geri yükler.
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); }],
]);Gerçek zamanlı ortak çalışma
Ann ve Bob, iki editörde tek bir belgeyi düzenler; buradaki aktarım, bir sunucu yerine sayfadaki küçük bir röle (relay) ile yapılır. Bir editörde yazın: metin, imleç ve ad etiketi diğer editörde görünür.
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);İçe ve dışa aktarma
HTML ve Markdown
Düğmeler belgeyi HTML ya da Markdown olarak indirir, Markdown'ı editörün altında gösterir ve bir görev listesi ile tablo içeren Markdown'ı içe aktarır.
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 tarayıcıda oluşturulur: seçilebilir metin içeren vektör sayfalar, bir üst bilgi ve sayfa numaraları. İndirmek için düğmeye tıklayın.
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)
Bir öneri ve bir yorum içeren belge, gerçek revizyonlar ve yorumlarla birlikte bir Word dosyası olarak indirilir; "Import" ise .docx dosyasını editöre geri okur.
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'));Sayfa görünümü ve yazdırma
Belge, %60 yakınlaştırmada, üst bilgi, sayfa numaraları ve sayfa sonu içeren Letter sayfalarında gösterilir. Bir sayfa sonu daha eklemek için Ctrl+Enter'a basın; "Print" sayfaları yazdırır.
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()],
]);Yapay zeka asistanı
Buradaki adaptör, sayfadaki hazır yanıtları akıtan sahte (stub) bir modeldir (gerçek bir adaptör kendi modelinizi çağırır). "Summarize" düğmesine tıklayın ya da bir cümle seçip araç çubuğundaki AI düğmesini kullanın (Ctrl+J), ardından yanıtı kabul edin ya da atın.
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(); }],
]);Erişilebilirlik denetleyicisi
Panel, belgenin sorunlarını listeler: alt metni olmayan bir görsel, atlanmış bir başlık düzeyi, belirsiz bir bağlantı. Bir soruna gitmek için ona tıklayın ya da hızlı düzeltmesini kullanın.
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);Kendi blokları ve satır içi düğümler
Sayfada kaydedilmiş bir "callout" bloğu ve bir "kbd" satır içi düğümü; kendi araç çubuğu düğmeleri ve eğik çizgi girişleriyle birlikte. Bir paragrafın içine tıklayın ve Callout düğmesini kullanın ya da /callout yazın.
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));Temalar ve stil
Temalar
Liste, editörün temasını değiştirir: yerleşik açık, koyu ve yüksek kontrastlı temalar, vibefox-js-themes.css temaları ve kendi "brand" temanız.
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 değişkenleri
Tüm VibeFox JS bileşenleri için bir kural (vurgu rengi ve köşe yarıçapı) ve yalnızca bu editör için bir kural (araç çubuğu arka planı, iç boşluk ve metnin yazı tipi boyutu).
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' });Hazır stiller
Liste, hazır stilleri değiştirir: klasik, minimal ve yüzen.
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));Yoğunluk ve boyut
Listeler, kapsayıcıya data-vfjs-density özniteliğini ve --vfjs-size-unit ölçeğini ayarlar: araç çubuğu düğmeleri ve iç boşluklar buna uyar.
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));Kendi CSS'iniz
Sayfanın düz CSS kuralları, !important kullanmadan etkin araç çubuğu düğmelerini ve başlıkları değiştirir. Etkin düğmeyi görmek için imleci kalın kelimenin içine yerleştirin.
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);Yerelleştirme ve RTL
Diller
Editör Rusçada, kütüphaneden sonra yüklenen vibefox-js-editor.ru.js dil paketiyle: ipuçları, menüler, yer tutucu ve durum çubuğu. Liste, bu editörün dilini değiştirir.
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 }));Dil ekleme
Kısmi bir Almanca sözlük: yer tutucu, durum çubuğu ve bazı ipuçları Almancadır; eksik anahtarlar İngilizceye geri döner.
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' });Sağdan sola
Sağdan sola bir belge: araç çubuğu, listeler ve alıntılar aynalanır; araç çubuğunda soldan sağa ve sağdan sola yönlü paragraflar için düğmeler bulunur. Son paragraf soldan sağa yönlüdür.
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));Diğer VibeFox JS kütüphaneleriyle birlikte kullanım
link() ile bileşenleri bağlama
Editörün sayıları, link() ile bir VibeFox JS Grid tablosuna aktarılır (her iki kütüphane de bu sayfada yer alır). Editörde yazın ve tabloyu izleyin.
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() }));Yapay zeka araçları
Düğmeler, editörün araçlarını bir model gibi çağırır: içeriği Markdown olarak okur, bir kelimeyi değiştirir ve tek bir araç çağrısı isteyen sahte (stub) bir modelle kit.ask() çalıştırır. Sonuçlar editörün altında gösterilir.
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) });
}],
]);