userscriptUtils
code:test.js
import { run, it } from '/api/code/jyori112/testUserscript/script.js';
| CursorのあるLinkを獲得する
code:script.js
function getCenter(elm) {
const bound = elm.getBoundingClientRect();
return bound.x + bound.width / 2;
}
function selectPageLink(cursor_x, page_links) {
for (let page_link of page_links) {
const bound = page_link.getBoundingClientRect();
const xMin = bound.x;
const xMax = bound.x + bound.width;
if (xMin < cursor_x && cursor_x < xMax) {
return page_link;
}
}
}
export function getLinkAtCursor() {
const cursor_elm = document.getElementsByClassName('cursor')0; const cursor_x = getCenter(cursor_elm);
const cursor_line = document.getElementsByClassName('cursor-line')0; if (!cursor_line) {
return;
}
const pagelinks = cursor_line.getElementsByClassName('page-link');
return selectPageLink(cursor_x, pagelinks);
}
| PageをAPIから獲得する
code:script.js
export function loadPage(scrapboxURL) {
return new Promise((resolve) => {
const req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == XMLHttpRequest.DONE) {
resolve(JSON.parse(req.responseText));
}
};
req.open('GET', /api/pages/${scrapboxURL}, true);
req.send(null);
});
}
code:test.js
import { loadPage } from '/api/code/jyori112/userscriptUtils/script.js';
it("loads test", async (ctx) => {
const pageData = await loadPage("/jyori112/test");
console.log(pageData);
ctx.assertEqual(pageData.title, "test");
ctx.assertEqual(pageData.lines.length, 2);
ctx.assertEqual(pageData.lines0.text, "test"); ctx.assertEqual(pageData.lines1.text, "this is pen"); });
code:test.js
run();