[javascript] MediumEditor에서 에디터 툴바 버튼에 이미지 캡션 추가하기

MediumEditor는 사용자가 쉽게 컨텐츠를 편집할 수 있는 WYSIWYG(What You See Is What You Get) 에디터입니다. 이 에디터에서 이미지를 추가할 때, 이미지에 캡션을 추가하는 기능을 구현해 보려고 합니다. 이미지 캡션은 사용자가 이미지에 대한 설명을 추가할 수 있는 텍스트입니다.

플러그인 설치

먼저, MediumEditor에 이미지 캡션을 추가하기 위한 플러그인을 설치해야 합니다. 다음 명령을 실행하여 필요한 패키지를 설치합니다.

npm install medium-editor-insert-plugin --save

플러그인 사용

플러그인을 설치한 후에는 에디터에서 사용할 수 있도록 설정해야 합니다. 다음과 같이 플러그인을 추가하는 코드를 작성해보겠습니다.

import MediumEditor from 'medium-editor';
import 'medium-editor-insert-plugin';

const editor = new MediumEditor('.editable', {
  toolbar: {
    buttons: ['bold', 'italic', 'underline', 'anchor', 'insertImage'],
  },
  extensions: {
    'insertImage': new MediumEditorInsertPlugin({
      insertButtonOptions: {
        label: '<span class="medium-editor-insert-images" style="position:relative;"><img class="medium-insert-images" src="insert-images.png"></span>',
        actions: {
          append: {
            label: 'Add Caption',
            callback: function() {
              // 이미지 캡션을 추가하는 로직을 작성합니다
            }
          }
        }
      }
    })
  }
});

위의 코드에서 insertButtonOptions 객체의 actions 속성을 이용하여 이미지 삽입 버튼 옆에 “Add Caption” 버튼을 추가했습니다.

이미지 캡션 추가 로직

이제 이미지 캡션을 추가하는 로직을 작성해보겠습니다. “Add Caption” 버튼을 클릭하면, 해당 이미지에 대한 캡션 입력 창이 나타나야 합니다. 다음과 같이 callback 함수를 작성하여 로직을 구현할 수 있습니다.

callback: function() {
  const imageElement = this.base.getSelectedParentElement().querySelector('img');
  const captionInput = document.createElement('input');
  captionInput.type = 'text';
  captionInput.placeholder = 'Enter caption...';

  const saveButton = document.createElement('button');
  saveButton.textContent = 'Save';
  saveButton.addEventListener('click', function() {
    const caption = captionInput.value;
    // 캡션을 이미지와 연결하는 로직을 작성합니다
  });

  const cancelButton = document.createElement('button');
  cancelButton.textContent = 'Cancel';
  cancelButton.addEventListener('click', function() {
    // 입력 취소 시 처리할 로직을 작성합니다
  });

  const captionForm = document.createElement('div');
  captionForm.appendChild(captionInput);
  captionForm.appendChild(saveButton);
  captionForm.appendChild(cancelButton);

  imageElement.parentNode.insertBefore(captionForm, imageElement.nextSibling);
}

위의 코드에서는 이미지의 상위 요소에 접근하여 이미지 엘리먼트를 찾고, 입력 폼과 저장 버튼, 취소 버튼을 동적으로 생성하여 캡션 입력 창을 만듭니다. 사용자가 캡션을 입력하고 저장 버튼을 클릭하면, 캡션과 이미지를 연결하는 로직을 작성해야 합니다.

결론

MediumEditor에 이미지 캡션을 추가하기 위해서는 medium-editor-insert-plugin을 설치하고 사용해야 합니다. 위의 예시 코드를 참고하여 원하는 기능을 구현해보세요. 캡션 입력, 저장, 취소 처리는 각각의 요구사항에 맞게 구현해야합니다.