Scrapboxのcursorの位置を監視する
実装

.cursor
の属性変化を監視する
テストコード
developper toolから使える
jsconst observer = new MutationObserver(mutations =>
mutations.forEach(mutation => console.log(mutation.target.style)));
observer.observe(document.getElementsByClassName('cursor')?.[0], {attributes: true});
cursorが位置している文字の行数と列数を取得する
DOMではなく行数と列数を保持する
script.old.jsimport {scrapboxDOM} from '/api/code/takker/scrapbox-dom-accessor/script.js';
import {cursor} from '/api/code/takker/scrapbox-cursor-position-2/script.js';
const observer = new MutationObserver(() =>
console.log({index: cursor().index, line: cursor().line.id})
);
observer.observe(scrapboxDOM.cursor, {attributes: true});
行数とcursorの縦棒の位置を取得するように変更した
test1.jsimport {scrapboxDOM} from '/api/code/takker/scrapbox-dom-accessor/script.js';
import {line as l} from '/api/code/takker/scrapbox-line-info-2/script.js';
import {cursor} from '/api/code/takker/scrapbox-cursor-position-3/script.js';
const observer = new MutationObserver(() =>
console.log({index: cursor().index, line: l(cursor().line).index})
);
observer.observe(scrapboxDOM.cursor, {attributes: true});
classを作り、cursorの状態を持たせるようにする
script.jsimport {scrapboxDOM} from '/api/code/takker/scrapbox-dom-accessor/script.js';
import {line as l} from '/api/code/takker/scrapbox-line-info-2/script.js';
import {cursor} from '/api/code/takker/scrapbox-cursor-position-3/script.js';
class CursorObserver {
constructor() {
this._index = 0;
this._lineNo = 0;
this._observer = new MutationObserver(() => {
const {index, line} = cursor();
this._index = index;
this._lineNo = l(line).index;
});
this._observing = false;
}
start() {
this._observer.observe(scrapboxDOM.cursor, {attributes: true});
this._observing = true;
}
stop() {
this._observer.disconnect();
this._observing = false;
}
get index() {
return this._index;
}
get lineNo() {
return this._lineNo;
}
get isObserving() {
return this._observing;
}
}
export const cursorObserver = new CursorObserver();
テストコード

test2.jsimport {cursorObserver as c} from '/api/code/takker/Scrapboxのcursorの位置を監視する/script.js';
window.cursorObserver = c;
document.addEventListener('keydown', () =>console.log({index: c.index, lineNo: c.lineNo, isObserving: c.isObserving}));
06:51:56 問題なさそう
別ページにコードを書く