본문 바로가기

카테고리 없음

tinyMCE 커스텀 툴바 버튼과 다이얼로그 만들기

생각보다 tinyMCE관련 포스팅이 조회수가 높아 계속해서 후속 포스팅을 작성합니다. 이번 포스팅은 tinyMCE에서 커스텀 툴바 버튼과 다이얼로그를 만드는 방법을 설명합니다.

커스텀 툴바 버튼 생성

버튼 생성은 addButton함수를 사용하면 됩니다. 보통 셋업 단계에서 버튼 추가를 하기 때문에 setup에 세팅해 주시면 됩니다. 공식 문서의 예제를 축약하면 다음과 같습니다.

tinymce.init({
  setup: (editor) => {
    editor.ui.registry.addButton('customInsertButton', {
      text: 'My Button',
      onAction: (_) => editor.insertContent(`&nbsp;<strong>It's my button!</strong>&nbsp;`)
    });
});

위 예제의 옵션 중 onAction 에서 버튼 클릭 시 동작을 정의할 수 있습니다. 이번 포스팅에서는 다이얼로그를 생성해야 하기 때문에 다이얼로그를 먼저 생성한 후, onAction에 다이얼로그를 여는 함수를 연결하겠습니다.

커스텀 다이얼로그 생성

tinyMCE에서 다이얼로그는 object로 정의됩니다. 공식 문서의 예제를 인용하면 다음과 같습니다.

const dialogConfig =  {
  title: 'Pet Name Machine',
  body: {
    type: 'panel',
    items: [
      {
        type: 'input',
        name: 'catdata',
        label: 'enter the name of a cat'
      },
      {
        type: 'checkbox',
        name: 'isdog',
        label: 'tick if cat is actually a dog'
      }
    ]
  },
  buttons: [
    {
      type: 'cancel',
      name: 'closeButton',
      text: 'Cancel'
    },
    {
      type: 'submit',
      name: 'submitButton',
      text: 'Do Cat Thing',
      buttonType: 'primary'
    }
  ],
  initialData: {
    catdata: 'initial Cat',
    isdog: false
  },
  onSubmit: (api) => {
    const data = api.getData();
    const pet = data.isdog ? 'dog' : 'cat';

    tinymce.activeEditor.execCommand('mceInsertContent', false, `<p>My ${pet}'s name is: <strong>${data.catdata}</strong></p>`);
    api.close();
  }
};

title, body, button, initialData, onSubmit등 각 옵션 세부사항에 대해서는 공식 문서 링크를 참조해주세요. 다이얼로그 객체를 만들었으면 이제 앞서 설명드렸던 onAction에 다이얼로그를 여는 함수를 추가해 줍니다. 다이얼로그를 여는 함수는 editor.windowManager.open 함수입니다. 

tinymce.init({
  setup: (editor) => {
    editor.ui.registry.addButton('customInsertButton', {
      text: 'My Button',
      onAction: (_) => editor.windowManager.open({...DialogObject})
    });
});