拡張オブジェクトを定義する
属性、複数のコマンド、独自の適用状態が必要な場合は Extension オブジェクトを使います。この例では数値の識別子を <cite> に保存します。
@Ada を選んで メンションを追加 を押します。HTML の出力に <cite data-id="42">@Ada</cite> が表示されます。
実行例
適用結果
import { EditorContent, EditorProvider, useEditor, type Extension } from 'yurich';
export const Mention: Extension = {
name: 'mention',
marks: [{
tag: 'cite',
type: 'mention',
attrs: {
'data-id': value => value && /^\d+$/.test(value) ? value : null,
},
}],
commands: {
setMention(editor, value) {
if (typeof value === 'string' && /^\d+$/.test(value)) {
editor.setMark('cite', { 'data-id': value });
}
},
removeMention(editor) {
editor.removeMark('cite');
},
},
isActive: editor => editor.isMarkActive('cite'),
};
export function MentionEditor() {
const editor = useEditor({
extensions: [Mention],
initialValue: "<p>@Ada に太字ボタンを試してもらいましょう。</p>",
});
return (
<EditorProvider editor={editor}>
<button
type="button"
onMouseDown={event => event.preventDefault()}
onClick={() => editor.execute('setMention', '42')}
>
メンションを追加
</button>
<EditorContent ariaLabel="エディター" />
</EditorProvider>
);
}
Mention を拡張一覧に追加します。文字を選択し、editor.execute('setMention', '42') を呼び出します。結果は editor.getHTML() で確認し、useIsActive(editor, 'mention') でツールバーの状態を同期できます。