Scrapboxでcursor下のリンクを取得する
2020-12-24 04:56:17 こんなことせずとも、Element.closest()を使えば簡単に取得できた
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;
}
cf. ScrapBindings-settings#5fe39ce61280f0000065b208
/icons/hr.icon
LinkObserverなどで使っている処理
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対策
cf. カーソル行の座標と文字列の座標を表示するテスト#5f41ff551280f00000c0366b
code:script.old.js
// 要素の左端の相対座標を取得する
function getLeftPosition(targetElement, cursorLine){
return targetElement.getBoundingClientRect().left
- cursorLine.getBoundingClientRect().left;
}
#2020-11-12 00:37:08