Scrapboxでcursor下のリンクを取得する
code:script.js
import {cursor} from '/api/code/takker/scrapbox-cursor-position-2/script.js'
export function getLinkIncludingCursor(){
return cursor().charDOM?.closest('a.page-link') ?? undefined;
}
/icons/hr.icon
code:script.old.js
export function getLinkIncludingCursor(){
const cursor = document.getElementById('text-input');
const editor = document.getElementById('editor');
const cursorLine = editor.getElementsByClassName('cursor-line')0; if(!cursor || !editor || !cursorLine) return undefined;
// 現在行からリンクを探す
const links = cursorLine.getElementsByClassName('page-link');
// cursorを含むlinkを抽出して返す
for (const link of links) {
const startLeft = getLeftPosition(link.firstElementChild, cursorLine);// '['の右端の座標
const endLeft = getLeftPosition(link.lastElementChild, cursorLine);// ']'の左端の座標
const cursorLeft = parseInt(cursor.style.left);// cursorの左端の座標
if (startLeft <= cursorLeft && cursorLeft <= endLeft) return link;
}
return undefined;
}
座標取得は少し工夫が必要
/icons/firefox.icon対策
code:script.old.js
// 要素の左端の相対座標を取得する
function getLeftPosition(targetElement, cursorLine){
return targetElement.getBoundingClientRect().left
- cursorLine.getBoundingClientRect().left;
}