오늘의 목표
수행 내역
// finding cursor position for modal
const getCursorPosition = () => {
const scrollOffset = scrollTopRef.current;
const textarea = markdownRef.current;
const mirror = mirrorRef.current;
const start = textarea.selectionStart;
// Get the text content before the cursor
const textBeforeCursor = textarea.value.substring(0, start);
// Update the mirror content to match the textarea's
mirror.textContent = textBeforeCursor;
// Create a temporary span to represent the cursor and measure its position
const cursorSpan = document.createElement('span');
cursorSpan.textContent = '|'; // A single character to measure position
mirror.appendChild(cursorSpan);
// Get the position of the cursor span relative to the viewport
const cursorRect = cursorSpan.getBoundingClientRect();
const textareaRect = textarea.getBoundingClientRect();
// Calculate final position relative to the textarea wrapper
const top = cursorRect.top - textareaRect.top + textarea.offsetTop - scrollOffset;
const left = cursorRect.left - textareaRect.left + textarea.offsetLeft;
// Clean up the mirror
setModalPosition({ top: top, left: left });
mirror.textContent = '';
};
문제 및 이슈
- 툴바의 버튼을 클릭해 내용이 추가되었을 때, markdown 의 state를 업데이트 하면서 내용물을 새로 입력한 것으로 되어 textarea를 리렌더링 하게 됨. 이로 인해 scrollTop의 위치가 맨 위, 맨 아래로 초기화 되는 현상 발생
- insertMarkdown을 하기 전 scrollTop 값을 저장하고, recoverScrollTop 함수를 구현해 타임아웃을 통해 원래 스크롤 위치를 유지하도록 함.
const recoverScrollTop = () => {
if (markdownRef.current) {
markdownRef.current.scrollTop = scrollTopRef.current;
}
};
참고자료
지원요청