[javascript] Draft.js를 사용한 텍스트 에디터의 문법 강조 기능 구현하기

텍스트 에디터는 사용자가 텍스트를 입력하고 편집할 수 있는 도구입니다. 사용자는 에디터를 사용하여 문서를 작성하거나 메모를 만들 수 있습니다. 텍스트 에디터에는 다양한 기능이 있지만, 이번에는 문법 강조 기능을 구현하는 방법에 대해 알아보겠습니다.

Draft.js 소개

Draft.js는 Facebook에서 개발한 React 기반의 텍스트 에디터 라이브러리입니다. Draft.js를 사용하면 리치 텍스트를 다루기 쉬워지며, 커스텀 에디터를 빠르게 구축할 수 있습니다.

문법 강조 기능 구현하기

문법 강조 기능은 텍스트 에디터에서 특정 단어 또는 문법 요소를 강조하여 표시하는 기능입니다. 예를 들어, 코드 블록을 입력할 때 코드 영역이 강조되어 보여지는 것이 문법 강조 기능의 하나입니다.

Draft.js에서 문법 강조를 구현하기 위해서는 다음과 같은 단계를 따를 수 있습니다.

1. Draft.js 설치하기

npm install draft-js

2. EditorState 생성하기

import { EditorState } from 'draft-js';

const editorState = EditorState.createEmpty();

3. 문법 강조 스타일 정의하기

import { Editor, EditorState, RichUtils } from 'draft-js';

const styleMap = {
  'CODE': {
    backgroundColor: '#f7f7f7',
    fontFamily: 'monospace',
    padding: '0.5rem',
    borderRadius: '0.25rem',
  },
};

function getBlockStyle(block) {
  switch (block.getType()) {
    case 'code-block':
      return 'CODE';
    default:
      return null;
  }
}

function SyntaxHighlightEditor() {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());

  const handleChange = (newEditorState) => {
    setEditorState(newEditorState);
  };

  const handleKeyCommand = (command) => {
    const newState = RichUtils.handleKeyCommand(editorState, command);
    if (newState) {
      handleChange(newState);
      return 'handled';
    }
    return 'not-handled';
  };

  return (
    <Editor
      editorState={editorState}
      onChange={handleChange}
      handleKeyCommand={handleKeyCommand}
      customStyleMap={styleMap}
      blockStyleFn={getBlockStyle}
    />
  );
}

export default SyntaxHighlightEditor;

결론

Draft.js를 사용하여 텍스트 에디터의 문법 강조 기능을 구현하는 방법을 알아보았습니다. Draft.js의 풍부한 기능을 활용하여 사용자 친화적인 텍스트 편집 환경을 구현할 수 있습니다. 직접 코드를 작성해보고, 다양한 스타일링 옵션을 적용해보세요!