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>'); }); }],
]);이벤트
모든 이벤트 핸들러는 페이로드 객체 하나를 받으며, 편집기 아래 목록에는 가장 최근 이벤트가 표시됩니다. 입력하거나, 텍스트를 선택하거나, 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)); }],
]);작성 및 서식
입력 도우미
멘션은 @, 빈 줄에서 블록 메뉴는 /를 입력하십시오. Markdown 단축키는 # , - 또는 **bold**이며, 스마트 타이포그래피는 따옴표 또는 --입니다. 자동 저장 이벤트는 편집기 아래에 표시됩니다.
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', '★'); }],
]);붙여넣기
버튼은 cleanExternalHtml()을 통해 Word 문서의 HTML을 붙여넣습니다. 목록, 제목, 표는 유지되고 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, 그리고 addCodeLanguage()로 추가한 사용자 정의 INI 언어를 지원합니다. 블록의 칩으로 언어를 선택하며, 새 블록은 ```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(); }],
]);접근성 검사기
패널에 문서의 문제가 나열됩니다. 예를 들어 대체 텍스트가 없는 이미지, 건너뛴 제목 수준, 모호한 링크가 표시됩니다. 문제를 클릭하면 해당 위치로 이동하거나 빠른 수정을 사용할 수 있습니다.
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' });기본 제공 스타일
목록에서 기본 제공 스타일을 전환합니다: 클래식, 미니멀, 플로팅.
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()로 컴포넌트 연결
편집기의 개수는 link()를 통해 VibeFox JS Grid 표로 전달됩니다(두 라이브러리 모두 이 페이지에 있습니다). 편집기에 입력하면서 표가 어떻게 바뀌는지 확인해 보십시오.
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) });
}],
]);