scrapbox-cursor-position-2
Next version [scrapbox-cursor-position-3][/icons/hr.icon]scrapboxのcursorがいる行と文字のDOMを返す函数cursorの縦棒の左側の文字を取得する
cursor
: div.cursor
を入れる lines
: div.lines
を入れる {id, column}
id
:cursorがいる 行のid column
cursorの右側の文字の位置 {error: 'The cursor doesn\'t has a focus.'}
export function getCursorInfo({lines, cursor}) {
// cursorのいる行を取得する
const cursorLine = lines.getElementsByClassName('cursor-line')?.[0];
if (!cursorLine) return {error: 'The cursor doesn\'t has a focus.'};
// 行内の文字を<span>のまま取得する
const chars = [...cursorLine.querySelectorAll('span[class^="c-"]')];
// cursorのいる<span>を検索する
const cursorLeft = Math.round(cursor.getBoundingClientRect().left);
const targetChar = chars.find(char => {
const {left, right} = char.getBoundingClientRect();
return Math.round(left) <= cursorLeft && cursorLeft < Math.round(right);});
return {
id: cursorLine.id,
column: targetChar?
parseInt(targetChar.className.replace(/c-(\d+)/,'$1')) :
chars.length, // 改行文字として、最後の文字より一つ後ろの番号を返す
};
}