[javascript] Draft.js를 이용한 텍스트 검색 및 대체 기능 구현하기

이번 포스트에서는 Draft.js를 사용하여 텍스트 검색과 대체 기능을 구현하는 방법에 대해 알아보겠습니다. Draft.js는 React 기반의 오픈 소스 텍스트 편집기 라이브러리로, 강력한 기능과 다양한 확장성을 제공합니다.

준비 작업

먼저, 프로젝트에 Draft.js를 설치해야 합니다. 아래 명령어를 사용하여 필요한 패키지를 설치합니다.

npm install draft-js

그리고 필요한 컴포넌트를 import 합니다.

import React, { useState } from "react";
import { Editor, EditorState, ContentState } from "draft-js";

텍스트 검색 기능 구현하기

Draft.js에서 텍스트 검색 기능을 구현하기 위해서는 Editor 컴포넌트를 사용해야 합니다. EditorhandleBeforeInput 이벤트 핸들러를 사용하여 입력된 텍스트를 감지할 수 있습니다.

const SearchAndReplaceEditor = () => {
  const [editorState, setEditorState] = useState(
    EditorState.createEmpty() // 초기 EditorState를 설정합니다.
  );

  const handleBeforeInput = (chars, editorState) => {
    const contentState = editorState.getCurrentContent();
    const selectionState = editorState.getSelection();
    const currentText = contentState
      .getBlockForKey(selectionState.getStartKey())
      .getText();

    if (currentText.includes(chars)) {
      // 텍스트가 입력된 문자열을 포함하고 있다면 검색 결과를 표시합니다.
      // 여기에서는 텍스트를 강조하여 표시합니다.
      const newContentState = contentState.createEntity(
        "SEARCH_RESULT",
        "IMMUTABLE",
        { searchQuery: chars }
      );
      const entityKey = newContentState.getLastCreatedEntityKey();
      const newEditorState = EditorState.set(editorState, {
        currentContent: newContentState
      });
      setEditorState(
        RichUtils.toggleInlineStyle(newEditorState, "SEARCH_RESULT", entityKey)
      );
    }

    return "not-handled";
  };

  return (
    <Editor
      editorState={editorState}
      onChange={setEditorState}
      handleBeforeInput={handleBeforeInput}
    />
  );
};

위 코드에서는 handleBeforeInput 이벤트 핸들러를 사용하여 입력된 텍스트가 현재 에디터의 텍스트에 포함되어 있는지 확인하고, 포함되어 있다면 텍스트를 강조하여 표시하도록 구현되어 있습니다.

텍스트 대체 기능 구현하기

텍스트 대체 기능을 구현하기 위해서는 검색 기능과 마찬가지로 EditorhandleBeforeInput 이벤트 핸들러를 사용합니다. 다만, 텍스트를 대체하는 로직을 추가로 구현해야 합니다.

const SearchAndReplaceEditor = () => {
  const [editorState, setEditorState] = useState(
    EditorState.createEmpty() // 초기 EditorState를 설정합니다.
  );

  const handleBeforeInput = (chars, editorState) => {
    const contentState = editorState.getCurrentContent();
    const selectionState = editorState.getSelection();
    const currentText = contentState
      .getBlockForKey(selectionState.getStartKey())
      .getText();

    if (currentText.includes(chars)) {
      // 대체 기능을 구현합니다.
      const newEditorState = EditorState.push(
        editorState,
        ContentState.createFromText(currentText.replace(chars, ""))
      );
      setEditorState(newEditorState);
    }

    return "not-handled";
  };

  return (
    <Editor
      editorState={editorState}
      onChange={setEditorState}
      handleBeforeInput={handleBeforeInput}
    />
  );
};

위 코드에서는 handleBeforeInput 이벤트 핸들러에서 입력된 텍스트가 현재 에디터의 텍스트에 포함되어 있다면 해당 부분을 제거하고, 새로운 EditorState를 설정하여 텍스트를 대체하는 로직을 구현하였습니다.

결론

이번 포스트에서는 Draft.js를 사용하여 텍스트 검색 및 대체 기능을 구현하는 방법을 알아보았습니다. Draft.js의 다양한 기능과 확장성을 활용하여 원하는 기능을 구현할 수 있습니다.

더 자세한 내용은 Draft.js 공식 문서를 참고하시기 바랍니다.