ドキュメント API
ドキュメント API は、ストーリードキュメント(本文)の読み取りと操作のための API です。ドキュメントを変更するメソッドは、スクリプトに documentEdit 権限が必要です。
ドキュメント構造を理解する
Sections(セクション)
ドキュメントは「セクション」に分割されており、これは段落を表します。現時点のセクション型は “text” のみですが、将来的に増える可能性があります。ここでは “section” と “paragraph” を同じ意味として扱います。
セクションの構造は次のとおりです。
{
text: string
origin: { position: number; length: number; data: string }[]
formatting: { position: number; length: number; data: string }[]
source: string | undefined
}
text は段落の生テキストです。origin と formatting は、テキストの一部範囲に対して「由来」や「装飾」を記録する配列です。source は段落の種類を表し、テキストアドベンチャー入力や指示(instructions)などの特別セクションで使われます。
Selections(選択範囲)
選択範囲(selection)は、ドキュメント内のテキスト範囲を表します。形は次のとおりです。
{
from: { sectionId: number; offset: number }
to: { sectionId: number; offset: number }
anchor: { sectionId: number; offset: number }
head: { sectionId: number; offset: number }
}
from と to が選択範囲の開始/終了です。anchor と head は「固定側」と「動く側」を表しますが、一般的には from と to を使えば十分です。
sectionId はセクションの数値 ID、offset はそのセクション内の文字オフセットです。
ドキュメント内容を読む
テキストの取得
ドキュメントのテキストを読むには api.v1.document.scan を使えます。この関数は、各セクションごとに呼ばれるコールバックを受け取れます(引数は sectionId、section オブジェクト、index)。また、Promise の返り値として全セクション配列も返します。
例:
let allSections = await api.v1.document.scan((sectionId, section, index) => {
api.v1.log(`Section ${index} (ID: ${sectionId}): ${section.text}`);
});
選択範囲のテキスト
選択範囲オブジェクトからテキストを得るには textFromSelection を使います。from と to を持つオブジェクトを渡すと、その範囲の文字列が返ります。
例:
let selectionText = await api.v1.document.textFromSelection({
from: selection.from,
to: selection.to
});
api.v1.log(`Selected text: ${selectionText}`);
ドキュメント内容を変更する
末尾への追加
末尾にテキストを追加するには、append / appendParagraph / appendParagraphs を使えます。
append は最も簡単で、追加したい文字列を渡します。
api.v1.document.append('This text will be added to the end of the document.');
必要に応じて自動で新しい段落を作成します。この方法では formatting や origin は指定できません。
appendParagraph と appendParagraphs は 1 つ以上のセクションオブジェクトを追加でき、text/formatting/origin/source を細かく制御できます。
例:
api.v1.document.appendParagraph({
text: 'This is a new paragraph with custom formatting.',
origin: [{ position: 0, length: 4, data: 'user' }],
formatting: [{ position: 10, length: 4, data: 'bold' }],
source: undefined
});
挿入
特定位置に挿入するには insertParagraphAfter / insertParagraphsAfter を使います。挿入先として「どの sectionId の後に入れるか」と、挿入するセクション(1 つ以上)を渡します。
0 は特別扱いで、「ドキュメント先頭に挿入」を意味します。
例:
api.v1.document.insertParagraphAfter(0, {
text: 'This paragraph was inserted at the start of the document.',
});
段落の削除
セクションを削除するには removeParagraph / removeParagraphs を使います。
例:
api.v1.document.removeParagraph(2115805536300901);
段落の更新
既存セクションを更新するには updateParagraph / updateParagraphs を使います。更新したい sectionId と、変更したいフィールドだけを渡します(指定していないフィールドは維持されます)。
例:
api.v1.document.updateParagraphs([
{
sectionId: 2115805536300901,
section: {
text: 'This paragraph has been updated with new text.',
}
}
])
履歴(History)
ドキュメント API は api.v1.document.history から履歴にもアクセスできます。undo/redo や履歴状態の取得などのメソッドが提供されます。
参考
- API リファレンス - API 全体(英語)
- 権限(Permissions) - スクリプト権限について