[javascript] Draft.js로 구현된 에디터를 이용한 문서 내보내기 및 가져오기 기능 구현하기

Draft.js는 React 기반의 강력한 텍스트 에디팅 라이브러리로서, 다양한 텍스트 에디터 기능을 구현할 수 있습니다. 이번에는 Draft.js를 사용하여 문서의 내용을 내보내고 가져오는 기능을 구현하는 방법에 대해 알아보겠습니다.

문서 내보내기 기능 구현하기

문서 내보내기 기능은 사용자가 작성한 문서의 내용을 파일로 저장하는 기능입니다. 다음은 Draft.js를 사용하여 문서 내보내기를 구현하는 방법입니다.

  1. “저장” 버튼을 눌렀을 때 exportDocument 함수를 호출합니다.
  2. exportDocument 함수에서는 현재 Draft.js 에디터에 입력된 문서의 내용을 가져옵니다.
  3. 가져온 문서의 내용을 텍스트 파일로 변환합니다. 이때, 해당 파일의 확장자는 .txt로 지정합니다.
  4. 변환된 텍스트 파일을 다운로드하도록 유저에게 제공합니다.
import { EditorState, convertToRaw } from 'draft-js';

const exportDocument = () => {
  const editorState = getCurrentEditorState(); // Draft.js 에디터의 현재 상태 가져오기
  const contentState = editorState.getCurrentContent();
  const rawContentState = convertToRaw(contentState);

  const contentAsString = JSON.stringify(rawContentState);

  const filename = 'exported-document.txt';
  const blob = new Blob([contentAsString], { type: 'text/plain;charset=utf-8' });

  if (navigator.msSaveBlob) {
    // IE10+
    navigator.msSaveBlob(blob, filename);
  } else {
    const link = document.createElement('a');
    if (link.download !== undefined) {
      // Browsers that support HTML5 download attribute
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', filename);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
};

위 코드에서 getCurrentEditorState 함수는 현재 Draft.js 에디터의 상태를 가져오는 함수입니다. 이 함수는 개발자가 자체적으로 구현해야 합니다.

문서 가져오기 기능 구현하기

문서 가져오기 기능은 저장한 문서 파일을 업로드하여 Draft.js 에디터에 표시하는 기능입니다. 다음은 Draft.js를 사용하여 문서 가져오기를 구현하는 방법입니다.

  1. “불러오기” 버튼을 눌렀을 때 importDocument 함수를 호출합니다.
  2. 사용자가 선택한 파일을 읽습니다.
  3. 읽은 파일의 내용을 JSON 형식으로 파싱합니다.
  4. 파싱된 JSON을 Draft.js에서 사용하는 형식으로 변환합니다.
  5. 변환된 내용을 사용하여 Draft.js 에디터를 업데이트합니다.
import { EditorState, convertFromRaw } from 'draft-js';

const importDocument = (file) => {
  const reader = new FileReader();

  reader.onload = (event) => {
    const contentAsString = event.target.result;
    const rawContentState = JSON.parse(contentAsString);
    const contentState = convertFromRaw(rawContentState);

    const editorState = EditorState.createWithContent(contentState);
    updateEditorState(editorState); // Draft.js 에디터 상태 업데이트
  };

  reader.readAsText(file);
};

위 코드에서 updateEditorState 함수는 Draft.js 에디터의 상태를 업데이트하는 함수입니다. 이 함수도 개발자가 자체적으로 구현해야 합니다.

참고 자료