デコレーション(Decorations)API
デコレーション API は、ドキュメントエディター上に装飾(デコレーション)を作成・管理するための API です。装飾は、ハイライト、下線、あるいは埋め込み型の UI など、テキストに重ねて表示される視覚要素です。デコレーションの作成には "editorDecorations" 権限が必要です。
概要
デコレーション API は api.v1.decorations から利用できます(実際の作成/登録は api.v1.editor.decorations 経由で行います)。ドキュメント内のデコレーションには主に 3 種類があります。
- Rules:正規表現に一致したテキスト範囲/段落へスタイルを適用
- Markers:ドキュメント内の位置を指定してスタイルを適用
- Widgets:指定位置に埋め込むカスタム UI コンポーネント
Rules
Rules は、正規表現に一致したテキストへ視覚スタイルを適用します。スタイル、正規表現パターン、大小文字の扱いなどのオプションを指定できます。
例:
api.v1.editor.decorations.registerRules([{
id: "alice-highlight",
type: "inline",
match: /\bAlice\b/,
style: { backgroundColor: "rgba(255, 255, 0, 0.3)" }
}]);
この例では、“Alice” という単語を黄色い背景でハイライトします。
Markers
Markers は、ドキュメント内の位置(セクション/段落など)を指定して、特定範囲へスタイルを適用します。
例:
const pos = await api.v1.editor.selection.get();
if (pos.from === null) {
return "No selection!";
}
const fromSection = pos.from.sectionId;
await api.v1.editor.decorations.createMarker({
type: "node",
sectionId: fromSection,
style: { borderLeft: "4px solid #66ccff", paddingLeft: "4px" }
});
この例では、カーソルがある段落の左側に青いボーダーを追加します。
Widgets
Widgets は、段落内の指定位置または段落間に、カスタム UI を埋め込みます。
例:
const sections = await api.v1.document.scan();
if (!sections.length) {
return "Document is empty!";
}
const lastSection = sections[sections.length - 1];
await api.v1.editor.decorations.createWidgets([{
type: "node",
sectionId: lastSection.sectionId,
side: "after",
content: [{
type: "box",
style: { width: '100%' },
content: [
{ type: "text", markdown: true, text: "🎉 **Congrats!** This widget was added by a script." },
{ type: "button", text: "Click Me", callback: () => api.v1.ui.toast("Widget button clicked!", { type: "success" }) }
]
}]
}]);
この例では、ドキュメント最後の段落の下に、お祝いメッセージとボタンを持つウィジェットを追加します。
デコレーションの管理
Rules は ID を使って更新/削除できます。Markers と Widgets は作成時にハンドルが返り、更新や破棄(dispose)に使えます。さらに、Markers と Widgets にはオプションとして onChange コールバックを渡せます。これは、ドキュメント編集でデコレーション位置が変わったときや、折りたたみ/削除などで破棄されたときに呼ばれます。
参考
- ドキュメント API - ドキュメント内容の読み書き
- UI パーツ - カスタム UI の構築
- API リファレンス - API 全体(英語)