문서

확장 객체 정의하기

속성이나 여러 명령, 다른 활성 상태가 필요하면 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')으로 툴바 상태를 연결하세요.

확장 검증하기