戻る

VibeFox JS Editor — ヘルプ

概要

VibeFox JS Editor は、Web アプリケーション向けのリッチテキスト(WYSIWYG)エディターです。書式設定、リスト、表、画像とファイル、埋め込み、シンタックスハイライト付きのコード、数式、変更の追跡、コメント、バージョン、リアルタイム共同編集、ご自身のモデルで動く AI アシスタント、ワードプロセッサーのようなページ表示、PDF、Word(.docx)、Markdown へのエクスポートに対応しています。依存関係のない素の JavaScript で書かれており、フレームワークを使う場合も使わない場合も動作します。

エディターは createEditor(target, options) の 1 回の呼び出しで作成でき、すべての VibeFox JS ライブラリと同じメソッド(setData、setOptions、on、getState、setState、setTheme、destroy)で操作します。内容は HTML です。getData() はクリーンでサニタイズ済みの HTML を返します。

主な機能

  • テキスト:見出し、太字、斜体、下線、取り消し線、インラインコード、下付き/上付き文字、フォント、サイズ、色、行間、インデント、配置、左から右/右から左の段落、リンク、引用、区切り線、特殊文字と絵文字。
  • リストとチェックリスト、結合セルを含む表、列幅の変更、セルのプロパティ。
  • ご自身のアップロードアダプターによる画像とファイル(ファイル選択、ドラッグ&ドロップ、クリップボード、進行状況)。YouTube/Vimeo などの埋め込みは、許可するまでネットワークリクエストを行いません。
  • 16 言語のシンタックスハイライト付きのコードブロック、MathML として表示される LaTeX 数式。
  • スラッシュメニュー、入力中の Markdown ショートカット、スマートタイポグラフィー、@ メンション、検索と置換、自動保存、HTML ソース表示、アウトライン、フォーカスモード。
  • 変更の追跡(作成者付きの提案)、コメントスレッド、視覚的な比較付きのバージョン履歴、他の参加者のカーソルを表示するリアルタイム共同編集。
  • PDF(ベクター、テキスト選択可能)、Word(.docx、変更履歴とコメント付き)、HTML、Markdown へのエクスポート。Word(.docx)と Markdown のインポート。ヘッダー、フッター、印刷に対応したページ表示。
  • 3 つのモード(クラシックツールバー、インライン、バルーン)、複数のエディターで共有する 1 つのツールバー、独自のブロックとインラインノード。
  • ご自身のモデルアダプターで動く AI アシスタント(書き換え、文法チェック、翻訳、要約、続きの生成、独自のコマンド)。言語モデルのエージェント向けのツール。
  • クイック修正付きのアクセシビリティチェッカー、既製のスタイル 3 種類、すべての色とサイズを CSS 変数で指定できること、テーマ、右から左への編集、キーボードによる完全な操作、スクリーンリーダー向けのテキスト。

動作要件

  • 最新の Web ブラウザー。コードブロックの色、検索の一致箇所、現在の提案は CSS Custom Highlight API で表示されます。この API がない場合、テキストはこれらの色なしで表示されます。
  • ランタイムの依存関係はありません。エディター自身はネットワークリクエストを行いません。アップロードはご自身のアダプターに送られ、埋め込みは embed.live: true の場合にのみ読み込まれ、AI アシスタントはご自身のアダプターを呼び出し、共同編集はご自身のトランスポート(または 1 つのブラウザーのタブ)を使います。
  • ブラウザーでは Node.js は必要ありません。ES モジュールは Node でインポートできます(インポート時に DOM には触れません)。sanitizeHtml、markdownToHtml、docxToHtml、diffHtml、latexToMathML、checkLatex、checkHtmlAccessibility、tokenizeCode、RtcDoc(サーバー上の共同編集ルーム)は、DOM なしで実行できます。

インストール

ライブラリのファイル

VibeFox JS Editor は独立した製品で、専用のファイルがあります。ライブラリの JavaScript 全体は 1 つのファイルに、スタイルは 1 つの CSS ファイルにまとめられています。ページに必要なのはこの 2 つだけです。その他のファイルは任意です。

ファイル内容
vibefox-js-editor.global.js従来の <script> タグ用のライブラリです。グローバル変数 VibeFoxJSEditor を 1 つ定義します。圧縮版:vibefox-js-editor.global.min.js。
vibefox-js-editor.esm.js同じコードの ES モジュール版です。圧縮版:vibefox-js-editor.esm.min.js。
vibefox-js-editor.cssライブラリのすべてのスタイルで、@layer vfjs に含まれます。テーマ light、dark、high-contrast を含みます。圧縮版:vibefox-js-editor.min.css。
vibefox-js-themes.css任意のテーマパック:既製のテーマ 18 種(テーマとスタイルを参照)。圧縮版:vibefox-js-themes.min.css。
locales/vibefox-js-editor.<lang>.js任意の言語ファイル。英語を除く言語ごとに 1 つあります(ローカライズと RTLを参照)。同じ言語の ES モジュールは .esm.js、プレーンな文字列は .json です。
vibefox-js-editor.d.tsTypeScript の型宣言(vibefox-js-editor.esm.d.ts も含む)。
*.js.mapソースマップ。
vibefox-js-editor-react.js, vibefox-js-editor-vue.js, vibefox-js-editor-svelte.js, vibefox-js-editor-jquery.js任意のフレームワーク用ラッパー(それぞれに .d.ts があります)。
vibefox-js-editor-angular任意の Angular パッケージ(Angular Package Format)。
vibefox-js-editor-wc.js任意の Web Components ラッパー(カスタム要素)。

script タグ

CSS ファイルとスクリプトを読み込みます。グローバル変数 VibeFoxJSEditor には、ライブラリのすべてのエクスポートが入ります。ディスクから開いたファイル(file://)でも動作します。

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

ES モジュール

ES モジュールのファイルをインポートし、CSS ファイルを読み込みます。ブラウザーがモジュールを読み込めるのは http(s) 経由のみで、file:// からは読み込めません。

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

npm

ライブラリは @vibefox/js-editor という名前の npm パッケージとしても用意されています。受け取ったパッケージフォルダー(または圧縮された .tgz ファイル)からインストールし、名前を指定してインポートします。バンドラーは @vibefox/js-editor/css のエクスポートを通じて CSS を取り込みます。

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

パッケージのエクスポート:@vibefox/js-editor(ES モジュール)、@vibefox/js-editor/min、@vibefox/js-editor/global、@vibefox/js-editor/global.min、@vibefox/js-editor/css、@vibefox/js-editor/min.css、@vibefox/js-editor/themes、@vibefox/js-editor/themes.min.css、@vibefox/js-editor/locales/<lang>、@vibefox/js-editor/locales/<lang>.json。TypeScript は型宣言を自動で見つけます。

フレームワーク用ラッパー

ラッパーは小さな独立したファイルです。ラッパーがなくてもライブラリは動作します。各ラッパーには VibeFox JS Editor と、それぞれのフレームワーク(peer dependency)のみが必要です。ラッパーは CSS を読み込みません。vibefox-js-editor.css は自分で読み込んでください。

フレームワークファイルnpm パッケージ対応バージョン
Reactvibefox-js-editor-react.js@vibefox/js-editor-reactReact 16.8 以降
Vue 3vibefox-js-editor-vue.js@vibefox/js-editor-vueVue 3.3 以降
Angularvibefox-js-editor-angular@vibefox/js-editor-angularAngular 17 以降
Sveltevibefox-js-editor-svelte.js@vibefox/js-editor-svelteSvelte 3、4、5
jQueryvibefox-js-editor-jquery.js@vibefox/js-editor-jqueryjQuery 1.12 〜 4.x
Web Componentsvibefox-js-editor-wc.js@vibefox/js-editor-wcフレームワーク不要

ES モジュールのラッパーはライブラリを @vibefox/js-editor としてインポートします。npm を使わない場合は、バンドラーの設定または import map でその名前を vibefox-js-editor.esm.js に対応付けてください。jQuery ラッパーはグローバル変数 VibeFoxJSEditor からライブラリを取得します。

すべてのラッパーに共通のルール:props/inputs はライブラリのオプションです(変更されたものは setData または 1 回の setOptions 呼び出しに渡されます)。イベントは on() と同じペイロードオブジェクトを持つフレームワークのイベントです。インスタンスはすべてのメソッドで利用できます。サーバー側レンダリング(SSR)では空のコンテナーが描画され、インスタンスはブラウザーでのみ作成されます。オプション style(既製の見た目)は、React、Vue、Svelte、Angular では prop の variant になります。style と className/class はホスト要素に属するためです。

Web Components

vibefox-js-editor-wc.js はライブラリのファイルの後に読み込みます。グローバル変数 VibeFoxJSEditor を使って、要素 <vfjs-editor> を定義します。属性はケバブケースのオプション(オブジェクトと配列は JSON)、プロパティはオプションです。コンポーネントのメソッドは要素のメソッドになり、イベントは vfjseditor:<event> という名前の CustomEvent で、ペイロードは detail に入ります。この要素は light DOM を使うため、ライブラリの CSS とページの CSS は通常どおり適用されます。

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

バンドラーを使う場合:import * as lib from '@vibefox/js-editor'; import { define } from '@vibefox/js-editor-wc'; define(lib);

クイックスタート

プレーン HTML

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

エディターは要素の幅を使い、テキストに合わせて高さが伸びます(オプション minHeight、既定値 180 px。maxHeight を指定するとスクロールします)。

React

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

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

Vue 3

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

v-model は HTML(data)です。v-model:pages はページ表示に従います。

Angular

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

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

vibefox-js-editor.css は angular.json の styles または index.html で読み込みます。NgModule を使うアプリケーションでは、VibeFoxJSEditorModule をインポートしてください。

Svelte

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

jQuery

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

基本概念

コンテンツ

内容は HTML です。setData(html) とオプション data は、許可リストで HTML をサニタイズします(スクリプト、イベントハンドラー、未知のタグ、安全でない URL は削除されます。オプション sanitize、既定値は true)。getData() はクリーンな HTML を、getText() はプレーンテキストを、getWordCount() は集計値を返します。すべての変更は change({ html, source })を発行し、1 回の取り消し操作として記録されます。

作成と破棄

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

new VibeFoxJSEditor(target, options) は createEditor と同じです。editor.content は編集可能な要素です。

コマンド

exec(name, value) は、選択範囲またはキャレット位置のブロックにコマンドを実行します(取り消し操作 1 回分)。isActive(name) は、キャレット位置でそのコマンドが適用されているかどうか(太字のテキスト、見出し …)を返します。transact(fn) は複数の変更を 1 回の取り消し操作にまとめます。insertHTML() と insertText() はキャレット位置に挿入します。

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

コマンド:p、h1 … h4、quote、codeBlock、bold、italic、underline、strike、code、subscript、superscript、textColor、bgColor、fontSize、fontFamily、lineHeight、ul、ol、checklist、indent、outdent、alignLeft、alignCenter、alignRight、alignJustify、ltr、rtl、link、unlink、image、imageAlt、imageCaption、file、embed、table と表のコマンド、hr、pageBreak、math、mathBlock、specialChars、emoji、clearFormat、insertHTML、insertText、find、そして以下で説明する変更の追跡、コメント、バージョン、AI アシスタント、アクセシビリティパネル、ページ表示のコマンド。undo()、redo()、canUndo()、canRedo() は履歴を操作します。

イベント

すべてのイベントハンドラーは 1 つのペイロードオブジェクトを受け取ります。オプションで購読するには(on: { change: fn })、または後から on、once、off を使います。on('*', (event, payload) => …) はすべてのイベントを受け取ります。

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

すべての VibeFox JS コンポーネントは ready、dataChange、optionsChange、themeChange、destroy を発行します。完全な一覧は API リファレンスにあります。

状態のスナップショット

getState() は JSON で扱えるスナップショットを返します。含まれるもの:HTML、モード(WYSIWYG またはソース)、フォーカスモード、方向、検索バー、最近使った記号、スタイル、変更の追跡、コメントスレッド、開いているパネル、ページ表示。setState(state) で復元します。バージョンは getVersions() / setVersions() で保存します。

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

入力と書式設定

入力の補助機能

  • スラッシュメニュー(slashCommands、既定値 true):空の行で「/」を入力すると、ブロックのメニュー(見出し、リスト、表、画像、動画、コード、数式、記号、絵文字、区切り線、改ページ …)が開きます。イベント slashCommand。
  • Markdown ショートカット(markdownShortcuts):# から #### に続けてスペースを入力すると見出し、- または * でリスト、1. で番号付きリスト、> で引用、```(言語を付ける場合は ```js)でコードブロック、--- で区切り線、**bold**、*italic*、`code`、~~strike~~。
  • スマートタイポグラフィー(typography):入力中に、印刷用の引用符、ダッシュ、三点リーダー、矢印を自動で整えます。
  • メンション(mentions: { items, trigger }):「@」を入力すると、ご自身の項目の一覧が開きます(配列、またはクエリを受け取る非同期関数)。イベント mentionInsert。
  • 自動保存(autosave: { enabled, interval, key }):変更の後、interval ミリ秒ごとに autosave イベントが発行され、指定した key のもとで localStorage にコピーが保存されます。loadDraft() と clearDraft()。
const notes = VibeFoxJSEditor.createEditor('#app2', {
  mentions: { items: async (q) => [{ id: 1, label: 'Alice' }, { id: 2, label: 'Bob' }].filter((u) => u.label.toLowerCase().startsWith(q.toLowerCase())) },
  autosave: { enabled: true, interval: 10000, key: 'notes-draft' },
  format: { fonts: ['Georgia, serif', { label: 'Mono', value: 'ui-monospace, monospace' }], fontSizes: ['12px', '16px', '24px'], indentStep: '1.5em' },
});
notes.on('autosave', (e) => fetch('/api/draft', { method: 'POST', body: e.html }));

書式設定のオプション

format:fonts(フォントメニュー:CSS のフォントリスト、または { label, value })、fontSizes、lineHeights、indentStep(既定値 '2em')、maxIndent(8)。リスト項目で Tab / Shift+Tab を押すと、項目を下位に入れる、または上位に戻します。indent と outdent は他のブロックのインデントを変更します。特殊文字と絵文字(約 230 文字と 480 個の絵文字。英語とロシア語の名前で検索できます)は、ツールバーから、または exec('specialChars') / exec('emoji') で開けます。値を指定すると挿入されます(イベント symbolInsert)。searchSymbols('emoji', 'smile') は一覧を検索します。

貼り付け

貼り付けられた HTML はクリーンアップされ(Word と Google ドキュメントのリスト、見出し、引用、表は、実際の構造として保持されます)、サニタイズされます。クリップボードの画像とファイルはアップロードされます。空の段落に貼り付けた YouTube / Vimeo の単独のリンクは埋め込みになります(embed.autoEmbed。Ctrl+Z でリンクに戻せます)。イベント:paste({ kind: 'html' | 'text' | 'image' | 'file' | 'embed' })。cleanExternalHtml(html) はこのクリーナーです。

ツールバーとモード

ツールバー

オプション toolbar には、プリセット名(既定値は 'full'、他に 'basic'。一覧は TOOLBAR_PRESETS)またはご自身のレイアウトを指定します。レイアウトは、グループ [['bold', 'italic'], ['ul', 'ol']]、または区切り文字 '|' を含むフラットなリストです。項目はコマンドに加え、undo、redo、blockFormat、source、focus、outline、fullscreen、accessibility、ai、pages、zoom、print、codeLanguage、そしてご自身のタイプの項目です。対応する機能がない項目(例:アップロードアダプターがない場合の file、AI アダプターがない場合の ai)は非表示になります。

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

その他の機能:stickyToolbar(スクロール中も表示されたままになります)、statusbar(語数と文字数)、HTML ソース表示(setMode('source')、getMode()、イベント modeChange)、全画面表示(toggleFullscreen())、現在のブロック以外を薄く表示するフォーカスモード(toggleFocusMode())、見出しのアウトライン(toggleOutline())。

クラシック、インライン、バルーン

オプション ui:'classic'(既定値。テキストの上にツールバーを表示)、'inline'(枠なし。要素はページのフォントと色を保持し、編集中はツールバーがブロックの上に浮かびます)、'balloon'(選択範囲の近くに小さなツールバーを表示し、空の段落には「+」ボタンを表示します。オプション balloon: { toolbar, plus })。インラインとバルーンのエディターは、要素の HTML を内容として読み込み、destroy() のときにその要素へ書き戻します。

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

複数のエディターで 1 つのツールバー

createSharedToolbar(target, { editors, toolbar, stickyToolbar }) は、フォーカスを持つエディターのツールバーを表示します。メソッド addEditor()、removeEditor()、getEditors()、getActive()、setActive()、イベント activeChange。

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

画像、ファイル、埋め込み

アップロード

アダプターを設定しない場合、画像はデータ URL として挿入され、その他のファイルは受け付けられません。オプション upload を指定すると、画像とファイルはご自身のストレージに送られます(ファイル選択、ドラッグ&ドロップ、クリップボードから)。アップロード中はプレースホルダーと進行状況が表示されます。アダプターは次のいずれかです:

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

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

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

メソッド:uploadFiles(files)、openFilePicker({ accept, multiple, images })、getUploads()、abortUpload(id)。イベント:uploadStart、uploadProgress、uploadDone、uploadError(reason:'type'、'size'、'failed'、'aborted')、drop、imageInsert、imageResize。画像には代替テキストとキャプションを付けられ(exec('imageAlt', text)、exec('imageCaption', text))、角のハンドルでサイズを変更できます。

埋め込み

insertEmbed(url)(またはツールバー、/video)は、YouTube と Vimeo のリンクをネットワークリクエストなしで埋め込みます。その他のリンクは、ご自身のリゾルバー(例:サーバー上の oEmbed プロキシ)を通ります。サニタイザーを通過するのは、許可リストに含まれる iframe のみです。エディター内では、プレーヤーの読み込みを許可するまで埋め込みはプレースホルダーになります。プレースホルダーの幅は最大で --vfjs-editor-embed-placeholder-width(480 px)、比率は --vfjs-editor-embed-ratio(16:9)です。読み込まれたプレーヤーは全幅になります。

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

embed オプション:allow(URL の接頭辞。サブドメインには https://*.example.com/、正規表現、または関数を指定できます)、providers(YouTube / Vimeo。既定値 true)、resolve、live(エディター内でプレーヤーを読み込む。既定値 false)、privacy(youtube-nocookie.com と Vimeo の dnt。既定値 true)、autoEmbed。イベント:embedInsert、embedError。ヘルパー:parseEmbedUrl(url)、iframeAllowed(src, allow)、DEFAULT_IFRAMES。

表

exec('table', { rows, cols, header }) は表を挿入します。表の中で右クリックすると、表のメニューが開きます。列の幅はボーダーをドラッグして変更します(colgroup で % 単位の幅。exec('columnWidths', [30, 70])、イベント columnResize)。行と列の挿入と削除は論理グリッド上で行われるため、結合セルは正しく保たれます。

文書内のすべての表には、クラス vfjs-editor-table と表のスタイル(罫線、余白、見出し行)が付与されます。これは、表の出所に関係なく同じです:表のコマンド、data、setData()、insertHTML()、貼り付け、Markdown または DOCX のインポート。HTML にクラスを書く必要はありません。getData() はこのクラスを持つ表を返しますが、ほかには何も追加されません。registerBlock() で登録したご自身のブロック内の表は、そのまま残ります。

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

コマンド:rowAbove、rowBelow、colBefore、colAfter(開始側/終了側)、colLeft、colRight(物理的な左側/右側)、deleteRow、deleteCol、deleteTable、headerRow、mergeCells(選択した矩形)、splitCell、mergeRight、mergeDown、cellBackground、cellAlign、cellVAlign、cellProps、columnWidths。イベント:tableInsert。

検索と置換

Ctrl+F で検索バー、Ctrl+H で置換付きのバーを開きます。コードからは次のように操作します:

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

オプション:caseSensitive、wholeWord、regex(置換文字列には $1、$<name>、$& を使えます)。メソッド:findNext()、findPrevious()、openFind({ replace })、closeFind()、isFindOpen()。イベント:find、replace。一致箇所は内容を変えずにハイライトされ、replaceAll は取り消し操作 1 回分です。

コードブロック

コードブロックは <pre><code class="language-js"> です。色はテキストの上に描画されるもので、HTML には決して書き込まれません。ブロック上のチップで言語を選びます。組み込みの言語:js、ts、json、html、xml、css、python、php、sql、bash、java、csharp、cpp、go、markdown、yaml(およびそのエイリアス)。

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

codeBlock オプション:highlight、detect(言語を推定し、「Auto: …」と表示)、languages(選択メニューの一覧)、defaultLanguage、picker、maxLength(500,000 文字)。codeBlock: false を指定すると、ハイライトと選択メニューが無効になります。exec('codeBlock', 'python')、exec('codeLanguage', 'sql')。イベント codeLanguageChange。ヘルパー:getCodeLanguages()、CODE_TOKEN_TYPES。コードブロック内への貼り付けはプレーンテキストです。

数式

数式は LaTeX で記述し、MathML として表示されます。正となるのは LaTeX のソースで、HTML に保持されます(MathML は読み込みのたびに作り直されます)。ツールバーの項目 math、/math、または数式のクリックで、プレビュー付きの数式ダイアログが開きます。

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

サポート対象:分数、根号、添字、極限付きの大型演算子、関数、行列と場合分けの環境、ギリシャ文字、約 200 種の演算子、関係記号と矢印、\left / \right、テキストと数式のフォント、アクセント、色、枠。メソッド:openMathDialog()。コマンド:math、mathBlock。イベント:mathInsert、mathUpdate、mathRemove。数式は Markdown では $…$、PDF ではベクターの図形、Word では Office Math として出力されます。スクリーンリーダーには読み上げ用のテキスト(speakMath)が渡されます。

変更の追跡

提案モードでは、すべての編集が作成者による変更になります:挿入、削除、書式、ブロック、表の行と列。変更は 1 件ずつ、またはまとめて承諾または却下できます。

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

trackChanges オプション:enabled、author(名前、または色スロット 0〜7 を指定する { id, name, color })、colors(作成者 ID ごとの色スロット)、output(getData() が返す内容:'markup'、'final'、'original')、announce。メソッド:setTrackChanges()、isTrackingChanges()、getChanges({ author, type })、acceptChange(id)、rejectChange(id)、acceptAllChanges()、rejectAllChanges()、nextChange()、previousChange()、goToChange(id)、toggleChangesPanel()、isChangesPanelOpen()。イベント:trackChangesToggle、changesUpdate、changeAccept、changeReject、changeFocus、changesPanelChange。変更は HTML に <ins> / <del> と data-vfjs-* 属性として保持されるため、保存した文書にも残ります。

コメント

コメントスレッドは選択範囲(または提案)に付けられ、返信、メンション、解決状態を持ちます。スレッドは JSON データで、サーバーに保存します。アンカーは HTML に保持されます。

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

comments オプション:enabled、author、colors、markup(getData() にアンカーを残す。false の場合はクリーンな HTML になり、スレッドは引用箇所からテキストを再検索します)、readonly(読み取り専用のエディターでのコメント)、permissions('own' または 'all')、mentions、announce。メソッド:updateComment()、removeComment()、reopenComment()、getComment(id)、nextComment()、previousComment()、goToComment(id)、toggleCommentsPanel()、isCommentsPanelOpen()、openCommentForm()。イベント:commentAdd、commentUpdate、commentRemove、commentResolve、commentOrphan(コメントされたテキストが削除された)、commentFocus、commentsChange、commentsPanelChange。コメントの追加や解決は、テキストの取り消し操作にはなりません。

バージョンと比較

バージョンは HTML(提案とコメントのアンカーを含む)の保存コピーです。2 つのバージョンは変更の追跡の形式で比較され、インラインまたは並べて表示されるか、レビュー用の提案としてテキストに挿入されます。

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

versions オプション:auto(内容の変更に伴う自動スナップショット)、interval(300,000 ミリ秒)、max(保持する自動バージョンの数:50)、author。メソッド:getVersions()、getVersion(id)、setVersions(list)、removeVersion(id)、compareVersions(from, to, { asChanges })、isCompareOpen()、toggleVersionsPanel()、isVersionsPanelOpen()。イベント:versionSave(HTML を含む。サーバーに保存してください)、versionRestore、versionRemove、compareChange、versionsPanelChange。

リアルタイム共同編集

collaborate(options) はセッションを開始します。すべての参加者の編集は競合なしでマージされ(CRDT)、他の参加者のカーソルと選択範囲が表示され、オフライン中の編集は送信待ちになって後から送られ、取り消し操作は自分の変更だけを取り消します。トランスポートはご自身で用意します(WebSocket、WebRTC、サーバーリレーなど)。指定しない場合は、1 つのブラウザーのタブ同士が BroadcastChannel を通じて連携します。

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

オプション:transport({ send, onMessage, onStatus, close }、または 'broadcast')、room、clientId、user({ name, color }:CSS の色、または 0〜7 のスロット)、initial('shared':全員が同じ内容から開始、'local':この内容をルームに送信、'remote':空から開始し、ルームの文書を取り込む)、connect、presence({ cursors, list, heartbeat, timeout, throttle }、または false)、persist({ key }、または { save, load })、gc、share({ comments, versions })。セッションのメソッド:getPeers()、setUser()、connect()、disconnect()、sync()、flush()、snapshot()、receive(msg)、undo()、redo()、destroy()。イベント:collabSend、remoteChange、collabStatus、peersChange。getCollaboration() はセッションを返します。

RtcDoc(Node でも利用可能)を使うと、サーバーでルームを保持できます。クライアントの操作を受け取り(receive(ops))、新しく参加した人に全体の状態を渡します(snapshot()、load()、toHTML())。

インポートとエクスポート

HTML と Markdown

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

Markdown のインポートは CommonMark と GFM(表、タスクリスト、取り消し線、自動リンク)、および $…$ の数式を読み取ります。エクスポートとインポートを行うと、同じ文書が戻ります。htmlToMarkdown(element) は任意の要素を変換します。イベント:import。

PDF

PDF はエディター自身が描画します。ベクターのページ、テキスト選択、リンク、見出しから作られるしおり、繰り返し見出し行を持つ表、コードの色、画像、数式を含みます。

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

オプション:pageSize('A4'、'A3'、'A5'、'Letter'、'Legal'、'Tabloid'、または pt 単位の [width, height])、orientation、margin、header、footer({page}、{pages}、{title}、{date} を含むテキスト、オブジェクト、または関数)、pageNumbers、title、author、subject、keywords、changes('final'(既定値)、'original'、'markup')、comments、colors('auto'、'editor'、'print')、images、highlight、dir、scale、outline、embedFonts、download、filename。ライブラリにはフォントファイルが含まれていません。フォントファイルは embedFonts(.ttf、.otf、.woff のいずれか)で指定するか、embedFonts: true でページの @font-face フォントを使用します。必要な文字を含むフォントを使うと、アラビア語、ヘブライ語、ヒンディー語のテキストは画面と同じ形で書き出されます。必要な箇所では右から左へ、アラビア文字は連結され、デーヴァナーガリー文字の音節は正しく組み立てられます。previewPDF(target) はブラウザーのビューアーで PDF を表示します。イベント:export。

Word(.docx)

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

エクスポートのオプションは PDF のオプションに加えて、font、monoFont、fontSize、lang、trackRevisions があります。changes: 'markup' は実際の Word の変更履歴を書き出します。comments: true は返信付きの Word コメントを書き出します。インポートのオプション:mode('replace' または 'insert')、changes、comments、images('inline'、false、またはご自身の保存関数。既定値:ご自身の upload アダプター)、pageBreaks('ignore' または 'marker')、footnotes、formatting('full' または 'basic')。docxToHtml(data) は DOM なしで変換します(Node やサーバー)。DOCX_MIME はメディアタイプです。

ページ表示と印刷

pages: true(またはオプション)を指定すると、ワードプロセッサーのように文書をシートで表示します。入力中に改ページが行われ、ヘッダーとフッター、ページ番号、ズームも使えます。PDF と DOCX のエクスポートは、表示のページ設定を引き継ぎます。

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

オプション:size、orientation、margin、header、footer、pageNumbers、firstPage、evenPages(先頭ページと偶数ページ用の個別の内容:{ header, footer, pageNumbers })、zoom(数値、'width'、または 'page')、repeatHeader(すべてのページで表の見出し行を繰り返す)、exportBreaks。メソッド:isPagesView()、goToPage(n)、setZoom()、print(options)。イベント:pagesChange、zoomChange、print。ページ表示はクラシックモードで動作します。

firstPage と evenPages は、指定したキーのみを変更します。省略したキーは、メインの header、footer、pageNumbers から取られます。null(pageNumbers の場合は false)を指定すると、そのページの該当部分だけが削除されます。したがって、上の firstPage: { header: null } は 1 ページ目のヘッダーを削除し、ページ番号は残します。これはビュー、印刷、PDF、DOCX のエクスポートのすべてに適用されます。内容のない先頭ページ(表紙)は firstPage: { header: null, footer: null, pageNumbers: false } です。

AI アシスタント

オプション ai は、AI アシスタントをご自身の言語モデルに接続します。エディター自身がモデルやサービスを呼び出すことはありません。ご自身のアダプターがプロンプトとコンテキストを受け取り、回答を返します。回答は文字列、ストリーム、非同期イテラブル、サーバーの Response、またはコールバックで送られた断片のいずれかです。回答はプレビューにストリーミング表示され、ユーザーが承諾(取り消し操作 1 回分)するか、破棄します。

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

コマンド:rewrite(tone:'formal'、'simple'、'shorter'、'longer')、grammar、translate(language)、summarize、continue、custom(prompt)、およびご自身のコマンド。コンテキストには command、instruction、system、messages(チャット API に対応した形式)、text(選択範囲または段落の Markdown)、before、after、locale、signal、push() / done() / error() があります。オプション:stream、resolve、commands、languages、prompts(英語の指示テンプレートを置き換えます)、suggest と author(回答を変更の追跡の提案として記録)、contextChars、contextMenu、slash、keys(Ctrl+J)、announce。メソッド:acceptAI()、rejectAI()、stopAI()、retryAI()、getAIState()、isAIAvailable()、openAIPanel()、closeAIPanel()。イベント:aiStart、aiChunk、aiDone、aiError、aiStop、aiRetry、aiAccept、aiReject、aiPanelChange。アダプターがなければ、すべての AI の項目は非表示になります。

アクセシビリティチェッカー

チェッカーは文書内のアクセシビリティの問題を見つけ、多くの問題を 1 クリックで修正します:代替テキストのない画像、空の見出しや飛ばされた見出し、2 つ目の H1、空の、または曖昧なリンク(「ここをクリック」)、テキストのコントラスト不足、見出し行のない表、lang のない別の言語のテキスト、タイトルのない iframe、長すぎる段落。

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

オプション accessibility(false にするとツールバー項目が非表示になります):rules(A11Y_RULES)、maxParagraphWords、lang、level('AA' または 'AAA')、live、vagueLinks。メソッド:goToAccessibilityIssue(id)、isAccessibilityPanelOpen()。contrastRatio(fg, bg)。イベント:accessibilityCheck、accessibilityFix、accessibilityFocus、accessibilityPanelChange。

独自のブロックとインラインノード

registerBlock(spec) と registerInline(spec) は、ご自身のコンテンツタイプを、そのコマンド、ツールバー項目、スラッシュメニューの項目、キー、Markdown、エクスポートとともに追加します。対象は、段落のコンテナー(コールアウト)、独自の UI を持つアイランド(ボタン、ウィジェット)、インラインノード(タグ、キーボードのキー)です。エディターを作成する前に登録してください。

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

仕様のフィールド:name、tag、className、content('blocks'、'text'、または 'none')、attrs(それぞれ attr、default、values、pattern、url、max、validate を持つ)、parse と parseAttrs(外部のマークアップを読み取る)、html(アイランドの保存された内容)、render(アイランドは UI を shadow root に描画し、{ update, destroy } を返します)、label、icon、commands、toolbar、slash、keys、markdown、exportHtml(PDF / DOCX 用の標準の HTML)、suggest、comments。宣言された属性だけがサニタイザーを通過します。unregisterType(name)、getInlineTypes()。ICONS は組み込みアイコンの一覧です。

テーマとスタイル

テーマ

すべての VibeFox JS コンポーネントには、CSS ファイルに組み込まれたテーマ light(既定値)、dark、high-contrast があります。オプションのファイル vibefox-js-themes.css はテーマパックを追加します:high-contrast-light、paper、paper-dark、glass、glass-dark、classic、classic-dark、ocean、ocean-dark、forest、forest-dark、sunset、sunset-dark、graphite、graphite-dark。同じファイルがすべての VibeFox JS ライブラリで使えます。

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

独自の theme を持たないコンポーネントは、テーマを持つ最も近いコンテナーに従い、その後にページに従います。setTheme(name, container) の後は、テーマ変数がコンテナー自身にも設定されるため、コンテナーの CSS でも使えます(#sidebar { background: var(--vfjs-bg); })。独自のテーマは registerTheme(name, vars) で、テーマ変数(bg、fg、border、accent、accent-fg、muted、surface、radius、font、shadow、palette-0 … palette-9、その他のトークン)を指定して登録します。登録すると、それを使うすべてのコンポーネントにすぐ適用されます。getTheme() はページのテーマを返し、themes は登録済みのテーマを一覧にします。イベント themeChange はテーマの切り替えを通知します。

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

CSS 変数

VibeFox JS Editor のすべての色、サイズ、間隔、フォント、角丸、影、アニメーション時間は CSS 変数です。そのため、どの設定も 1 か所で変更できます。変数は 3 つのレベルに分かれます:

  • すべての VibeFox JS コンポーネントで共有するテーマ変数:--vfjs-bg、--vfjs-fg、--vfjs-border、--vfjs-accent、--vfjs-accent-fg、--vfjs-muted、--vfjs-surface、--vfjs-radius、--vfjs-font、--vfjs-shadow、--vfjs-palette-0 … --vfjs-palette-9;
  • デザイントークン:間隔 --vfjs-space-1 … --vfjs-space-8、フォントサイズ --vfjs-font-size、--vfjs-font-size-sm など、角丸 --vfjs-radius-sm …、ステータスの色 --vfjs-danger、--vfjs-success、--vfjs-warning、--vfjs-info、サイズの単位 --vfjs-size-unit、アニメーション時間 --vfjs-motion-duration、フォーカスリングの --vfjs-focus-ring-color と --vfjs-focus-ring-width;
  • ライブラリ固有の変数 --vfjs-editor-*(既定値は上記のトークンを使います)。
/* all VibeFox JS components of the page */
.vfjs { --vfjs-accent: #0f766e; --vfjs-radius: 4px; }
/* only this editor */
#notes {
  --vfjs-editor-toolbar-bg: #f8fafc;
  --vfjs-editor-content-padding: 24px;
  --vfjs-editor-font-size: 17px;
}

エディターのライブラリ変数の主なグループ(名前はすべて --vfjs-editor- で始まります):枠(--vfjs-editor-bg、--vfjs-editor-fg、--vfjs-editor-font、--vfjs-editor-border、--vfjs-editor-radius、--vfjs-editor-shadow)、ツールバー(--vfjs-editor-toolbar-bg、--vfjs-editor-toolbar-padding、--vfjs-editor-toolbar-sticky-top)、ボタン(--vfjs-editor-btn-height、--vfjs-editor-btn-radius、--vfjs-editor-btn-hover-bg、--vfjs-editor-btn-active-bg)、テキスト(--vfjs-editor-content-bg、--vfjs-editor-content-padding、--vfjs-editor-content-max-width、--vfjs-editor-font-size、--vfjs-editor-line-height、--vfjs-editor-paragraph-space、--vfjs-editor-heading-fg、--vfjs-editor-link、--vfjs-editor-selection-bg)、引用(--vfjs-editor-quote-border)、表(--vfjs-editor-table-border、--vfjs-editor-table-header-bg)、コード(--vfjs-editor-code-bg、--vfjs-editor-code-font、--vfjs-editor-code-keyword、--vfjs-editor-code-string、ほかのトークン種別)、ステータスバー(--vfjs-editor-statusbar-bg)、ポップオーバー(--vfjs-editor-popover-bg)、変更の追跡とコメント(作成者の色 --vfjs-editor-track-a … --vfjs-editor-track-h、--vfjs-editor-track-ins-bg、--vfjs-editor-comment-bg)、数式(--vfjs-editor-math-font)、AI(--vfjs-editor-ai-*)、ページ表示(--vfjs-editor-page-*)、共同編集のカーソル(--vfjs-editor-peer-*)、埋め込み(--vfjs-editor-embed-width、--vfjs-editor-embed-ratio、--vfjs-editor-embed-bg、--vfjs-editor-embed-border、--vfjs-editor-embed-radius、--vfjs-editor-embed-label-bg、--vfjs-editor-embed-label-fg、--vfjs-editor-embed-selected、--vfjs-editor-embed-placeholder-width。プレーヤーが読み込まれていない場合のプレースホルダーの幅で、480 px です)。

JavaScript から設定する場合:オプション styleVars は、エディター要素に変数を設定します({ 'toolbar-bg': '#eef2ff' } は --vfjs-editor-toolbar-bg と同じ。完全な名前も使えます)。className は独自のクラスを追加します。

設定する場所::root、ページ内の任意のコンテナー(#checkout { --vfjs-accent: #0f766e; })、コンポーネントの要素自体、またはテーマ(registerTheme)。最も近い値が優先されます。独自のテーマ(オプション theme または component.setTheme(name))を持つコンポーネントは、変数を設定しているコンテナー内にあっても、そのテーマのテーマ変数を保持します。別のコンポーネントの内側にあるコンテナー(ダイアログやカードの中のフォームなど)は、ライブラリの変数をその中のコンポーネントにも渡します。共通のデザイントークン(--vfjs-space、--vfjs-danger、--vfjs-selected-bg …)だけは、そこを通過しません。その場合は、外側のコンポーネントの外にあるコンテナー、またはネストされたコンポーネント自体(#form .vfjs { … })に設定してください。<body> に配置されたポップアップ、メニュー、ダイアログは、コンポーネントのコンテナーの値ではなく、ページ(:root)に設定された値を使います。

既定値:テーマ変数は @property で登録されているため(初期値は light テーマ)、ページのすべての要素で値を持ちます。ライブラリの変数(--vfjs-editor-*)は、スタイルシート内の使用箇所で既定値を保持するため、設定していない変数は要素上で値を持ちません:

  • ご自身の CSS でライブラリの変数を使う場合は、ライブラリと同じようにフォールバックを指定します:var(--vfjs-editor-bg, var(--vfjs-bg))。またはテーマ変数を直接使います;
  • JavaScript からは、cssVar(element, '--vfjs-editor-font-size') で現在の値を読み取ります(ライブラリがエクスポートしており、コンポーネントが計算した既定値も返します)。getComputedStyle(element).getPropertyValue() は、誰も設定していないライブラリの変数に対して空文字列を返すことがあります。
/* your own element in the colors of the component */
.my-summary { background: var(--vfjs-editor-bg, var(--vfjs-bg)); color: var(--vfjs-fg); }
const el = document.querySelector('#orders');
console.log(VibeFoxJSEditor.cssVar(el, '--vfjs-editor-font-size'));                    // the value in use (also a default)
console.log(VibeFoxJSEditor.cssLength(el, 'var(--vfjs-editor-font-size)'));            // the same in pixels
console.log(getComputedStyle(el).getPropertyValue('--vfjs-editor-font-size'));  // can be '' unless you set it

ライブラリの CSS ファイルが CORS のない別のオリジンから来ている場合(crossorigin 属性のない <link>)、ブラウザーはスクリプトにスタイルシートの読み取りを許可しません。そのため、コンポーネントのルートに値のない変数では、cssVar() は空文字列を返します。ご自身のオリジンから読み込む場合、またはその属性を付けた場合は動作します。

スタイルシートはネイティブの CSS ネストで書かれています。読み込み方は変わらず、ご自身の CSS は任意の形式で書けます。

既製のスタイル

オプション style(フレームワークラッパーでは prop variant)で既製の見た目を選びます。すべてのスタイルは、すべてのテーマと密度で使えます。

スタイル見た目
'classic'既定値:枠があり、テキストの上に区切り線付きのツールバーと、ステータスバーがあります。
'minimal'枠なし。区切り線のない透明なツールバーと、控えめなボタン。
'floating'ツールバーは影付きの角丸のフローティングカードになります。テキスト領域も独自のカードです。
editor.setStyle('floating');                          // or the option style: 'floating'
editor.setStyle('minimal', { 'toolbar-bg': '#eef2ff' });   // with variables
editor.getStyle();                                    // 'minimal'

EDITOR_STYLES は名前の一覧です。setStyle は styleChange を発行します。それ以外の名前では、クラス vfjs-editor-style-<name> 用のご自身の CSS が使われます。

密度とサイズ

ページまたは任意のコンテナーに data-vfjs-density="compact"、"normal"、"comfortable" のいずれかを設定すると、その中のすべての VibeFox JS コンポーネントの高さと余白が追従します。--vfjs-size-unit(既定値 1px)を変えると、コンポーネントのすべてのサイズが一度にスケールします(例:#orders { --vfjs-size-unit: 1.25px; })。オプションに数値で指定したサイズはピクセルとして扱われ、スケールされません。

既定の高さ:エディターは内容の高さになり、少なくともオプション minHeight の高さになります。要素に高さを指定すると、固定の高さになります。

独自の CSS

ライブラリのすべてのルールはカスケードレイヤー @layer vfjs に含まれるため、ご自身の CSS は !important なしで常に優先されます。VibeFox JS Editor のクラス名はすべて vfjs-editor- で始まり(状態を表すクラスも同様。例:vfjs-editor-is-active)、ページ上の他の CSS フレームワークによってスタイルが変わることはありません。

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

ライブラリはフォントファイルを含みません。トークン --vfjs-font、--vfjs-font-mono、--vfjs-font-serif に設定されたシステムのフォントスタックを使います。必要であれば、ご自身のフォントに変更してください。アニメーションは prefers-reduced-motion に従い、色は forced-colors モード(Windows のハイコントラスト)に従います。

公開されるコンテンツ:getData() の HTML は vfjs-editor-table、vfjs-editor-figure、vfjs-editor-align-left、vfjs-editor-embed、vfjs-editor-math などのクラスを使います。コンテンツを表示するページでは、これらにスタイルを適用してください。

ローカライズと RTL

言語

VibeFox JS Editor には 14 種類のインターフェース言語があります。英語(en)はライブラリのファイルに組み込まれています。それ以外の言語はそれぞれ独立した言語ファイル(パッケージ内の dist/locales/vibefox-js-editor.<lang>.js)で、ページは使用するものだけを読み込みます:ロシア語(ru)、スペイン語(es)、ドイツ語(de)、フランス語(fr)、イタリア語(it)、ポルトガル語(ブラジル)(pt)、ウクライナ語(uk)、トルコ語(tr)、中国語(簡体字)(zh)、日本語(ja)、韓国語(ko)、ヒンディー語(hi)、アラビア語(ar)。locale オプションは 1 つのコンポーネントの言語を設定します。setLocale(lang) はページの既定の言語を設定し、独自の locale を持たないコンポーネントはこれに従います(変更時に再描画されます)。

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

上の例では、使用する言語のファイルが必要です。script タグを使う場合は、言語ファイルをライブラリの後に読み込んでください。順序が重要です。先に読み込むと、ファイルは言語を追加せず、コンソールに警告を出力します。

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

npm またはバンドラーを使う場合は、ライブラリの後に言語をインポートしてください。npm を使わない場合、ES モジュールのページは ./locales/vibefox-js-editor.ru.esm.js をインポートします。これは vibefox-js-editor.esm.js に言語を登録します。

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

.esm.js の言語ファイルは、圧縮版ビルド @vibefox/js-editor/min には適しません(ライブラリのコピーを 2 つ読み込むことになります)。そこでは .json ファイルを使ってください:

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

ファイルがない場合、locale: 'ru' は英語を表示し、コンソールに警告を 1 つ出力します。

言語コード:uk、ko、zh、pt が正式なコードです。ua と kr も使えます。これらはそれぞれ uk と ko の別名です。ライブラリは文字列ごとに、正確なコード、次に別名、基本の言語(pt-BR → pt、zh-CN → zh)、英語、最後にキー自体の順に探します。normalizeLocale(code) は別名の正式なコードを返します。

言語によって方向は設定されません。locale: 'ar' を指定するときは、コンテナーにも rtl: true または dir="rtl" を設定してください。

言語の追加

addLocale(lang, dictionary) は、言語に文字列を追加します(言語がなければ作成します)。独自の言語を作る場合や、言語ファイルの上に独自の表現を重ねる場合に使います。欠けているキーは上記の順で探されるため、一部だけの辞書でも動作します。addLocale('ua', …) は uk を埋めます。辞書は、それを使うコンポーネントを作成する前に追加するか、後から言語を切り替えてください。

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

VibeFox JS Editor のキーは editor. で始まります(約 360 個のキー:ツールバー、メニュー、ダイアログ、パネル、検索バー、AI アシスタント、アクセシビリティチェッカー、スクリーンリーダー向けのテキスト)。言語ファイルにはすべてのキーが並んでいます(locales/vibefox-js-editor.ru.json)。英語のテキストは読みやすいファイル vibefox-js-editor.esm.js にあります。{n} のような波かっこ内のプレースホルダーは、ライブラリが値を埋めます。t(key, params) はページの言語でキーを翻訳し、editor.t(key) はエディターの言語で翻訳します。getLocale() はページの言語を返し、onLocaleChange(fn) は変更を通知します。内容そのものはご自身のテキストであり、翻訳されません。

複数形:数を含むテキストには、キー <key>.zero、.one、.two、.few、.many、.other(Intl.PluralRules のカテゴリー)があります。.other は代替のため、辞書ではこの形だけを指定できます。{count} と {n} は値で埋められます。tPlural(key, count, params, lang) は形を選びます。メソッド editor.tPlural(key, count, params) は、コンポーネントの言語でこれを行います。

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

特殊文字と絵文字は、英語とロシア語の名前で検索されます。数式の読み上げテキストは、読み込まれている言語ファイルに関係なく、英語またはロシア語です。アクセシビリティチェックのメッセージはエディターの言語に従います。DOCX エクスポートの言語は、lang を指定しない限りロケールから取られます。コメント、変更、バージョンの日時は、エディターの言語で表示されます。

右から左へ(RTL)

オプション rtl: true は、コンポーネントを右から左にレイアウトします(その要素に dir="rtl" が付きます)。rtl: false は左から右を強制します。指定しない場合、コンポーネントはページまたはそのコンテナーに従います(<html dir="rtl">)。矢印キーは読み順に従います。isRtl(element) は要素の方向を返します。

VibeFox JS Editor では、オプション dir('ltr'、'rtl'、または null =ページの方向)が文書の方向を設定します。setDirection()、getDirection()、イベント directionChange。ツールバー、ポップオーバー、パネル、リスト、引用、変更のバーは左右が反転します。HTML ソース表示は左から右のままです。単独の段落は exec('rtl') / exec('ltr') で独自の方向を持ちます(エディターが右から左のときに表示されるツールバー項目)。PDF と DOCX のエクスポートは右から左の段落を書き出します。

アクセシビリティ

テキスト領域はラベル付きのリッチテキストフィールドです(要素に aria-label / aria-labelledby がない場合は「Rich text editor」)。すべてのツールバーは WAI-ARIA のツールバーパターンに従い、タブストップは 1 つです。スクリーンリーダーは、書式の変更、提案、コメントをキャレット位置で読み上げ、ナビゲーション、検索結果、アップロード、AI の回答も読み上げます。フォーカスは見えるようになっています(フォーカスリングは CSS 変数 --vfjs-focus-ring-color、--vfjs-focus-ring-width、--vfjs-focus-ring-offset、--vfjs-focus-ring-style で設定します)。ダイアログはフォーカスを内部に保ち、閉じるとフォーカスを戻します。high-contrast と high-contrast-light のテーマ、forced-colors モード、prefers-reduced-motion に対応しています。コンテンツについては、アクセシビリティチェッカーを参照してください。

キーボード

macOS では、Ctrl と記載されている箇所で Cmd を使えます。

キー操作
Ctrl+B、Ctrl+I、Ctrl+U、Ctrl+Shift+X太字、斜体、下線、取り消し線。
Ctrl+, , Ctrl+.下付き文字、上付き文字。
Ctrl+Kリンク。
Ctrl+Z、Ctrl+Y、Ctrl+Shift+Z元に戻す / やり直し。
Ctrl+F、Ctrl+H検索、検索と置換。Enter / Shift+Enter で次へ / 前へ、Esc で閉じます。
Tab、Shift+Tab(リスト項目)項目を下位に入れる / 上位に戻す。
Shift+Enter改行。
Ctrl+Enter改ページ。
/スラッシュメニュー(矢印キー、Enter または Tab、Esc)。
@メンション(オプション mentions)。
Alt+F10ツールバーへ移動(共有ツールバー、バルーン、またはご自身のツールバー)。Esc でテキストに戻ります。
矢印キー、Home、End(ツールバー)ボタン間を移動。
Ctrl+Shift+E提案モードのオン/オフ。
Alt+PageDown、Alt+PageUp次の変更/前の変更。
Ctrl+Alt+M選択範囲に新しいコメント。
Alt+Shift+PageDown、Alt+Shift+PageUp次のコメント/前のコメント。
A、R(変更の一覧)変更を承諾/却下。
Ctrl+Enter(コメント欄、数式ダイアログ、AI の回答)送信/挿入/承諾。
Ctrl+JAI アシスタント(オプション ai)。
Escポップオーバーまたはパネルを閉じる、AI の回答を停止または破棄する、全画面表示を終了する。

スクリーンリーダー

ツールバーには toolbar ロールがあり、aria-controls でテキストを指します。ボタンには名前があり、aria-pressed / aria-haspopup を持ちます。メニューは menu、記号のグリッドは listbox、検索バーは search のリージョン、パネルはリストを含むラベル付きの aside です。提案は実際の <ins> / <del> 要素です。数式には読み上げ用の alttext があります。共同編集のカーソルはスクリーンリーダーからは隠されています。変更の追跡、コメント、AI アシスタントの通知は、それぞれの announce オプションで無効にできます。

メソッド:focus()、blur()、focusToolbar()。ライブラリは、内部で使用するヘルパーもエクスポートしています:announce(message)、trapFocus、rovingFocus、setAria、prefersReducedMotion() など(API リファレンスを参照)。

他の VibeFox JS ライブラリとの併用

VibeFox JS Editor は単独で動作します。すべての VibeFox JS ライブラリは、共有コアの独自のコピーを持つ独立したファイルです。1 つのページで複数のライブラリを使っても競合は起きず、ライブラリごとにグローバル変数が 1 つ(VibeFoxJSEditor、VibeFoxJSCharts など)、クラス名はライブラリの接頭辞付き、ページのテーマは 1 つ、イベントも共通です。

link() によるコンポーネントの接続

link(source, event, target, method, transform) は、別のコンポーネントがイベントを発行するたびに、あるコンポーネントのメソッドを呼び出します。リンクを解除する関数を返します。connect(source, event, handler) は購読し、購読解除の関数を返します。bus は、ページ上のすべての VibeFox JS ライブラリで共有されるイベントチャネルです。

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

同じページに他のライブラリがある場合の動作

  • PDF のエクスポートと印刷は単独で動作します。VibeFox JS PDF もページにある場合、toPdfDocument()、addToPdfDocument()、および previewPDF() での VibeFox JS PDF ビューアーが使えます。
  • DOCX、HTML、Markdown へのエクスポート、および DOCX と Markdown のインポートは単独で動作します。

AI ツール

ライブラリは、主な操作を言語モデルの関数呼び出し用のツールとして記述します。エディター自身がモデルやサービスを呼び出すことはありません。説明をご自身のモデルに送り、モデルが要求した呼び出しを実行してください。

ツール機能
editor_get_content文書を Markdown、HTML、またはテキストとして返します。
editor_get_selection選択されたテキストを返します。
editor_insertキャレット位置、先頭、または末尾に内容を挿入します。
editor_replace_selection選択範囲を置き換えます。
editor_set_content文書を置き換えます。
editor_find_replaceテキストまたは正規表現のすべての一致を置き換えます。
editor_format書式設定コマンドを適用します。
editor_outline見出しを返します。
editor_stats語数、文字数、ページ数を返します。
const { describeTools, callTool, createToolKit } = VibeFoxJSEditor;
const tools = describeTools(editor, { format: 'openai' });   // 'plain' / 'anthropic', 'openai', 'webmcp'
const result = await callTool(editor, 'editor_get_content', { format: 'markdown' }); // { ok: true, result } or { ok: false, error }
const kit = createToolKit({ doc: editor });               // tool names get the prefix 'doc_'
const answer = await kit.ask('Add a short summary at the end', {
  format: 'anthropic',
  model: async (request) => (await fetch('/api/llm', { method: 'POST', body: JSON.stringify(request.body) })).json(),
});

callTool は、実行の前に引数をツールのスキーマと照合し、不正な入力に対して例外を投げることはありません。createToolKit(components, { webmcp, readOnly }) は、複数のコンポーネント(他の VibeFox JS ライブラリのものも含む)のツールを、一意の名前で 1 つにまとめます。kit.ask(prompt, { model, format, system, maxSteps, signal, onToolCall }) は、ご自身の model 関数を使って「モデル → ツール呼び出し → 結果」のループを実行します。kit.registerWebMCP() は、利用可能な場合にツールをブラウザーの navigator.modelContext に登録します。registerTools(target, provider) はご自身のツールを追加します。validateSchema(value, schema) はスキーマの検証です。

書き込み系のツールは suggest: true を指定すると、変更を AI の作成者による変更の追跡の提案として記録します。editor.getAITools({ format }) と editor.callAITool(name, args) は、同じツールを、コア機能を除いた形で提供します。これは、エディター内でユーザーのためにコマンドを実行する AI アシスタントとは別のものです。

API リファレンス

エクスポート一覧

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

共通のコア(すべての VibeFox JS ライブラリで同じ):setTheme、getTheme、registerTheme、themes、tokens、componentTokens、densities、cssVar、cssColor、cssLength、observeTokens、setLocale、getLocale、addLocale、normalizeLocale、t、tPlural、withLocale、onLocaleChange、link、connect、bus、Emitter、VibeFoxJSComponent、factory、toCSV、downloadFile、downloadCanvasPNG、createVectorContext、VectorContext、vectorToSVG、vectorToPDF、printSVG、createVectorImage、loadVectorImage、SVG_MIME、PDF_MIME、PDF_PAGE_SIZES、describeTools、callTool、createToolKit、registerTools、validateSchema、announce、trapFocus、rovingFocus、getFocusable、focusFirst、saveFocus、setAria、ensureId、addAriaRef、removeAriaRef、isRtl、mirrorArrow、prefersReducedMotion、prefersHighContrast、motionDuration、onPreferenceChange、injectStyles、ensureBaseStyles、formatNumber、formatDate、escapeHtml、createEl、deepMerge、isPlainObject、getPath、setPath、uid、clamp、debounce、throttle、VERSION。

オプション

すべての VibeFox JS コンポーネントは、theme、locale、rtl、on も受け付けます(基本概念を参照)。

オプション型既定値説明
datastring''初期 HTML(サニタイズ済み)。
placeholderstring''(ローカライズされたヒント)空のエディターのテキスト。
toolbarstring または array'full'プリセットまたはレイアウト。
stickyToolbarbooleantrueスクロール中もツールバーを表示したままにします。
statusbarbooleantrue語数/文字数のカウンター。
minHeight、maxHeightstring'180px'、''テキスト領域の高さ。
autosaveobject{ enabled: false, interval: 30000, key: '' }自動保存。
mentionsobject または nullnull@ メンション。
slashCommands、markdownShortcuts、typographybooleantrue入力の補助機能。
sanitizebooleantruesetData と貼り付けの HTML をサニタイズします。
spellcheckbooleantrueブラウザーのスペルチェック。
readonlybooleanfalse読み取り専用。
uploadobject または nullnullアップロードアダプター。
dir'ltr' | 'rtl' | nullnull文書の方向。
formatobject{}フォント、サイズ、行間のメニューとインデント。
embedobject{ allow: [], providers: true, resolve: null, live: false, privacy: true, autoEmbed: true }埋め込み。
codeBlockobject または false{ highlight: true, detect: false, languages: null, defaultLanguage: '', picker: true, maxLength: 500000 }コードブロック。
stylestring または nullnull(classic)既製のスタイル。
classNamestring または string[]''エディター要素の独自のクラス。
styleVarsobject または nullnullエディター要素の CSS 変数({ 'toolbar-bg': '#eef' })。
trackChangesobject または boolean{ enabled: false, author: null, colors: null, output: 'markup', announce: true }変更の追跡。
commentsobject または boolean{ enabled: true, author: null, colors: null, markup: true, readonly: true, permissions: 'own', mentions: null, announce: true }コメント。
versionsobject または boolean{ auto: false, interval: 300000, max: 50, author: null }バージョン履歴。
uistring'classic''classic'、'inline'、'balloon'。
balloonobject{ toolbar: 'balloon', plus: true }バルーンモード。
accessibilityobject または false{ rules: null, maxParagraphWords: 0, lang: null, level: 'AA', live: true, vagueLinks: null }アクセシビリティチェッカー。
aifunction、object、または nullnullAI アシスタントのアダプター。
pagesboolean または objectfalseページ表示。

イベント

イベントペイロード説明
ready、dataChange、optionsChange、themeChange、destroy基本概念を参照共通のイベント。
change{ html, source }内容が変更されました(source:'user'、'api'、'history'、'source'、'remote' など)。
selectionChange{ collapsed, text, block }選択範囲が移動しました。
wordCountChange{ words, chars, charsNoSpaces, readingTime }集計値が変更されました。
undo、redo、autosave{ html }、{ html, time, key }履歴、自動保存。
imageInsert、imageResize、linkInsert、tableInsert、mentionInsert、slashCommand、checklistToggle、symbolInsert挿入された内容挿入。
paste、drop{ kind, url }、{ kind, count }クリップボード、ドラッグ&ドロップ。
uploadStart、uploadProgress、uploadDone、uploadError{ id, file, … }アップロード。
embedInsert、embedError{ url, provider, src }、{ url, reason, error }埋め込み。
find、replace{ query, total, index }、{ query, replacement, count, all }検索と置換。
columnResize{ column, widths }表の列。
directionChange、styleChange、codeLanguageChange{ dir }、{ style, className }、{ language, previous }方向、見た目、コードの言語。
modeChange、fullscreenChange、focusModeChange、outlineChange{ mode }、{ fullscreen }、{ enabled }、{ open }表示。
trackChangesToggle、changesUpdate、changeAccept、changeReject、changeFocus、changesPanelChange{ enabled }、{ total, authors }、{ ids, changes, author }、{ change, index, total }、{ open }変更の追跡。
commentAdd、commentUpdate、commentRemove、commentResolve、commentOrphan、commentFocus、commentsChange、commentsPanelChange{ thread, comment, … }コメント。
versionSave、versionRestore、versionRemove、compareChange、versionsPanelChange{ version }、{ open, from, to, layout }バージョン。
export、import{ format, filename, pages }、{ format, mode, warnings }ファイル。
mathInsert、mathUpdate、mathRemove{ latex, display, previous }数式。
accessibilityCheck、accessibilityFix、accessibilityFocus、accessibilityPanelChange{ issues, counts }、{ issue, fix }、{ id, issue }、{ open }アクセシビリティチェッカー。
aiStart、aiChunk、aiDone、aiError、aiStop、aiRetry、aiAccept、aiReject、aiPanelChange{ command, text, delta, … }AI アシスタント。
pagesChange、zoomChange、print{ enabled, pages }、{ zoom, mode }、{ pages, window }ページ表示。
collabSend、remoteChange、collabStatus、peersChange{ seq, ops, queued }、{ client, seq, ops }、{ online, pending }、{ peers }共同編集。

メソッド

メソッド戻り値説明
setData、getData、setOptions、setOption、getOption、getState、setState、setTheme、on、once、off、use、t、destroy—共通のメソッド(基本概念を参照)。
getText、getWordCountstring / 集計値テキスト。
exec、isActive、transact、insertHTML、insertTextthis / booleanコマンド。
undo、redo、canUndo、canRedothis / boolean履歴。
focus、blur、focusToolbarthis / booleanフォーカス。
setMode、getMode、toggleFullscreen、isFullscreen、toggleFocusMode、isFocusMode、toggleOutline、isOutlineOpenthis / 値表示。
setDirection、getDirection、setStyle、getStylethis / 値方向、見た目。
uploadFiles、openFilePicker、getUploads、abortUpload、insertEmbedPromise / this / 一覧 / numberファイルと埋め込み。
find、findNext、findPrevious、replace、replaceAll、clearFind、openFind、closeFind、isFindOpen結果 / number / this検索と置換。
insertMath、openMathDialog、getFormulas結果 / 一覧数式。
setTrackChanges、isTrackingChanges、getChanges、acceptChange、rejectChange、acceptAllChanges、rejectAllChanges、nextChange、previousChange、goToChange、toggleChangesPanel、isChangesPanelOpenthis / 一覧 / boolean / number変更の追跡。
addComment、addReply、updateComment、removeComment、resolveComment、reopenComment、getComments、getComment、setComments、nextComment、previousComment、goToComment、toggleCommentsPanel、isCommentsPanelOpen、openCommentFormthread / boolean / 一覧コメント。
saveVersion、getVersions、getVersion、setVersions、removeVersion、restoreVersion、compareVersions、showCompare、hideCompare、isCompareOpen、toggleVersionsPanel、isVersionsPanelOpenversion / 一覧 / 比較結果バージョン。
exportHTML、exportMarkdown、importMarkdown、importDOCX、getPDF、exportPDF、toPdfDocument、addToPdfDocument、previewPDF、getDOCX、exportDOCXstring / Promiseインポートとエクスポート。
loadDraft、clearDraftboolean / this自動保存の下書き。
checkAccessibility、fixAccessibilityIssue、goToAccessibilityIssue、toggleAccessibilityPanel、isAccessibilityPanelOpen結果 / booleanアクセシビリティチェッカー。
runAI、acceptAI、rejectAI、stopAI、retryAI、getAIState、isAIAvailable、openAIPanel、closeAIPanel、getAITools、callAIToolPromise / boolean / stateAI。
setPages、isPagesView、getPageCount、getCurrentPage、goToPage、setZoom、getZoom、print、getPrintHtmlthis / number / Promise / stringページ表示。
collaborate、getCollaboration、getPeerssession / 一覧共同編集。

TypeScript の型宣言(vibefox-js-editor.d.ts)は、すべてのオプション、ペイロード、戻り値の型を詳しく定義しています:EditorOptions、EditorEvents、EditorState、EditorCommand、EditorUpload、EditorPdfOptions、EditorDocxOptions、EditorCommentThread、EditorAIOptions、EditorCollabOptions、EditorTypeSpec など。

トラブルシューティング

スタイルが適用されない

vibefox-js-editor.css をスクリプトと一緒に読み込んでください。読み込まないと、コンポーネントは動作しますがスタイルが付かず、コンソールに警告「VibeFox JS stylesheet is not loaded」が 1 つ表示されます。バンドラーでは @vibefox/js-editor/css をインポートしてください。フレームワークラッパーは CSS を自動では追加しません。

独自の CSS が適用されない、またはページの CSS フレームワークがコンポーネントを変更する

ライブラリの CSS は @layer vfjs に含まれるため、ご自身のルールは !important なしで優先されます。それでも適用されない場合は、クラス名を確認してください。状態のクラスにはライブラリの接頭辞が付いています(is-active ではなく vfjs-editor-is-active)。ライブラリは一般的なクラス名を使わないため、ページの CSS フレームワークによって変更されることはありません。

ES モジュールがディスクから読み込めない

ブラウザーが <script type="module"> を読み込めるのは http(s) 経由のみです。ローカルの Web サーバーを使うか、file:// からも動作する vibefox-js-editor.global.js を使ってください。

Content Security Policy

ライブラリは eval もインラインスクリプトも使わず、ネットワークからは何も読み込みません。要素のサイズと位置のためにインラインスタイルを設定するため、style-src を指定するポリシーでは、それを許可する必要があります(style 属性には 'unsafe-inline')。埋め込みのプレーヤーには、そのホストに対する frame-src が必要です(エディターで embed.live: true を設定した場合と、コンテンツを表示するページでのみ)。アップロード、AI アダプター、共同編集のトランスポートは、ご自身のリクエストです(connect-src)。画像には img-src が必要です(アップロードアダプターなしで画像を挿入する場合は、データ URL も必要です)。

PDF のテキストが指定したフォントで表示されない

ライブラリにはフォントが含まれていません。PDF は標準の PDF フォントを使い、それ以外のテキストは選択可能なままですが、代替フォントで描画されます。ご自身のフォントファイルは embedFonts(.ttf、.otf、.woff のいずれか)で指定するか、embedFonts: true でページの @font-face フォントを使用してください。

何も表示されない

createEditor の実行時に対象の要素が存在している必要があります(何も見つからないセレクターはエラーを投げます)。インラインまたはバルーンのエディターには枠がないため、フォーカスを得るまではページの通常のテキストのように見えます。

HTML の属性、クラス、スクリプトが失われる

サニタイザーが残すのは、エディターが認識するタグ、属性、クラスだけです。独自のブロックは registerBlock() / registerInline() で宣言してください(宣言された属性は残ります)。iframe のホストは embed.allow で許可します。sanitize: false はサニタイザーを無効にします。これは信頼できる HTML に対してのみ使ってください。

アップロードボタンまたは AI の項目が表示されない

file の項目は upload アダプターがある場合にのみ表示され、AI の項目は ai アダプターがある場合にのみ表示されます。

コードに色が付かない、検索の一致がハイライトされない

これらの色は CSS Custom Highlight API を使います。この API がないブラウザーでは、色なしでテキストが表示されます。非常に長いコードブロック(codeBlock.maxLength を超えるもの)には色が付きません。

getData() の内容に <ins>、<del> またはコメントの span が含まれる

提案とコメントのアンカーは内容の一部です。getData({ changes: 'final', comments: false }) は、すべての変更を承諾したクリーンなテキストを返します。

コピーと貼り付けが機能しない

ブラウザーがクリップボードへのアクセスを許可するのは、安全なページ(https または localhost)で、かつユーザーの操作の後だけです。

制限事項

  • リスト項目内の Tab は、その項目を下位に入れます。キーボードでエディターを離れるには、リストの外で Shift+Tab を押すか、Esc の後に Tab を押します。
  • ブロックのインデントは 1 単位(indentStep)を使います。別の単位で書かれた余白は、レベル 0 として扱われます。ライブプレーヤー(embed.live: true)はマウス操作を取り込みます。埋め込みは、そのキャプションまたは枠線で選択してください。
  • コードの色は色だけです(太字や斜体のトークンはありません)。言語の検出はヒューリスティックに基づきます。エディターを作成した後に addCodeLanguage() を呼ぶと、次の変更時にそのブロックに色が付きます。
  • 変更の追跡:構造的な変更は、その上にある他の提案を吸収します。別の作成者が挿入したブロック、行、列、段落区切りは、提案として削除できません(その中のテキストは削除できます)。HTML ソース表示は追跡されません。
  • コメントとバージョンはエディター内にあります。複数の人が同時に使う場合は、サーバー(イベントと setComments() / setVersions())または共同編集セッションが必要です。比較は保存された HTML に基づいて行われます。段落を分割した場合は変更された段落と挿入された段落として、移動したブロックは削除と挿入として表示されます。
  • PDF:ハイフネーションとテキストのシェイピングはありません(アラビア文字は連結されません)。embedFonts を指定しない場合、標準の PDF フォントが、エディターのフォントの文字幅で使われます。浮動画像はブロックとして配置されます。
  • DOCX のエクスポート:取得できない画像(CORS)は代替テキストとして書き出されます。フロートは行内配置になります。DOCX のインポート:浮動画像は行内になり、テキストボックスは段落になります。グラフ、SmartArt、図形、EMF 画像はスキップされます(警告付き)。番号の形式は単純な番号付きリストになり、ヘッダー、フッター、セクションはインポートされません。
  • 数式:ブラウザーは MathML Core で描画します(\cancel はありません)。PDF では 1 つのフォントが使われ、アクセントは概略の位置に配置されます。
  • フローティングツールバーは、エディター要素の内部に固定されています。transform または filter を持つ祖先要素は位置を変えます。overflow: hidden を持つ祖先要素は、ポップオーバーを切り取ることがあります。
  • アクセシビリティチェッカー:言語の規則はスクリプトで推定されます(同じスクリプトの言語は区別されません)。コントラストの規則は、背景画像の上にあるテキストは確認しません。
  • AI:エディターごとに、同時に処理できる回答は 1 つだけです。ページ表示:1 ページより高い表の行、行、画像は分割されません。ウィドウ/オーファンの制御はありません。印刷のヘッダーとフッターには、@page のマージンボックスのブラウザー対応が必要です。ヘッダーとフッターはオプションであり、シート上では編集できません。
  • 共同編集:2 人の参加者が同じリスト項目を互いの中へ同時に移動すると、再び移動されるまで、切り取られたブロックの表示内容が失われます。別の参加者が列を追加している間に行を追加した場合、その行は作成者だけが空のセルで埋めます。ソース表示での編集は、トップレベルのブロック全体を置き換えます。リモートの change イベントは最大 100 ms 遅れて届きます。
  • フレームワークラッパー:オプション内の関数は参照で比較されます。prop を削除しても、オプションは既定値にリセットされません。Vue は、オブジェクトの prop を浅く監視します。

Bug Report

改善へのご協力ありがとうございます。すべてのレポートを丁寧に確認していますが、個別の返信は行っておりません。レポートをもとに変更を行った場合は、レポート番号とともに製品の変更履歴に記載します。詳しくご相談したい場合は、 サポートチケットを作成してください。

スライドしてパズルを合わせる