文档

定义扩展对象

需要属性、多条命令或自定义激活状态时,使用 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') 同步工具栏状态。

验证扩展