[javascript] Draft.js를 이용한 텍스트 에디터의 커서 위치 제어하기

Draft.js는 리액트 기반의 텍스트 에디터 라이브러리로써, 풍부한 텍스트 편집 기능을 제공합니다. 그 중에서도 사용자가 원하는 위치에 커서를 이동시키는 기능은 매우 중요합니다. 이번 글에서는 Draft.js를 이용하여 텍스트 에디터의 커서 위치를 제어하는 방법을 알아보겠습니다.

커서 위치 가져오기

Draft.js에서 현재 커서의 위치를 가져오기 위해서는 EditorState 객체의 getSelection() 메서드를 사용합니다. 아래는 커서의 위치와 관련된 정보들을 추출하는 예제 코드입니다.

const editorState = EditorState.createEmpty();
const selectionState = editorState.getSelection();
const currentOffset = selectionState.getAnchorOffset();
const currentBlockKey = selectionState.getAnchorKey();

참고: getAnchorOffset()는 커서의 현재 위치를, getAnchorKey()는 현재 커서의 위치가 있는 블록의 식별자를 반환합니다.

커서 위치 이동하기

Draft.js에서 커서의 위치를 이동하려면 EditorState 객체를 업데이트해야 합니다. EditorState 객체의 moveFocusToEnd() 또는 moveFocusToStart() 메서드를 사용하여 커서를 블록의 끝 또는 시작 위치로 이동시킬 수 있습니다. 아래는 커서를 블록의 끝으로 이동시키는 예제 코드입니다.

const editorState = EditorState.createEmpty();
const content = editorState.getCurrentContent();
const blockMap = content.getBlockMap();
const firstBlock = blockMap.first();
const lastBlock = blockMap.last();

const moveCursorToEnd = () => {
  const selectionState = SelectionState.createEmpty(firstBlock.getKey());
  const updatedSelection = selectionState.merge({
    focusKey: lastBlock.getKey(),
    focusOffset: lastBlock.getLength()
  });
  
  const updatedEditorState = EditorState.moveFocusToEnd(editorState, updatedSelection);
  
  return updatedEditorState;
}

참고: moveFocusToEnd() 또는 moveFocusToStart()EditorState 객체를 반환하기 때문에, 커서 이동 후에는 이 반환된 객체를 사용해야 합니다.

커서 위치 업데이트하기

Draft.js에서 사용자가 텍스트를 입력할 때마다 커서의 위치를 업데이트할 수 있습니다. 이를 위해서는 EditorState 객체를 업데이트하는 onChange() 핸들러를 사용해야 합니다. 아래는 텍스트 입력 시 커서를 항상 블록의 끝으로 이동시키는 예제 코드입니다.

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

const handleTextChange = (contentState) => {
  const updatedEditorState = EditorState.push(editorState, contentState);
  
  const updatedSelection = editorState.getSelection().merge({
    anchorKey: contentState.getLastBlock().getKey(),
    anchorOffset: contentState.getLastBlock().getLength(),
    focusKey: contentState.getLastBlock().getKey(),
    focusOffset: contentState.getLastBlock().getLength()
  });
  
  const finalEditorState = EditorState.acceptSelection(updatedEditorState, updatedSelection);
  
  setEditorState(finalEditorState);
}

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

위의 예제 코드에서 handleTextChange() 함수는 onChange() 핸들러로 전달되며, 사용자가 텍스트를 입력할 때마다 호출됩니다. push() 메서드를 사용하여 EditorState를 업데이트하고, acceptSelection() 메서드를 사용하여 커서의 위치를 업데이트합니다. 마지막으로 업데이트된 EditorStatesetEditorState() 함수를 통해 저장합니다.

Draft.js를 이용하여 텍스트 에디터의 커서 위치를 제어하는 방법을 알아보았습니다. 이를 통해 사용자 친화적이고 유연한 텍스트 편집 환경을 구현할 수 있습니다. 더 자세한 정보는 Draft.js의 공식 문서를 참고하시기 바랍니다.