script.jsconst GREP_C_NUMBER = 4;
const locationHostname = location.hostname;
const body = document.querySelector("body");
const className = "gyolink-div";
let timer;
let isLinkMouseEnter = false;
let isDivMouseEnter = false;
const onClick = () => {
[...document.querySelectorAll(".page-link")]
.filter((link) =>
new RegExp(`^https://${locationHostname}/.+#[^#]+$`).test(link.href)
)
.forEach((link, linkIndex) => {
const url = new URL(link.href);
url.pathname = `/api/pages${url.pathname}`;
// `#`とる
const hash = url.hash.slice(1);
fetch(url.href)
.then((res) => res.json())
.then((json) => {
const lines = json.lines;
lines.forEach((line, index) => {
if (line.id === hash) {
const since = Math.max(index - GREP_C_NUMBER, 0);
const until = Math.min(lines.length, index + GREP_C_NUMBER + 1);
const text = lines
.slice(since, until)
.map((textLine) => textLine.text)
.join("\n");
const div = document.createElement("div");
div.classList.add(className);
body.appendChild(div);
Object.entries({
display: "none",
width: "70%",
position: "fixed",
top: "4em",
right: "1em",
"z-index": "999",
background: "white",
overflow: "hidden",
padding: "3px 0 0",
}).forEach(([key, value]) => div.style.setProperty(key, value));
const a = document.createElement("a");
a.href = link.href;
a.insertAdjacentText(
"beforeend",
decodeURIComponent(`${a.pathname}${a.hash}`)
);
div.appendChild(a);
Object.entries({
display: "block",
color: "black",
"text-decoration": "underline",
"margin-left": "3px",
}).forEach(([key, value]) => a.style.setProperty(key, value));
const pre = document.createElement("pre");
pre.insertAdjacentText("beforeend", text);
div.appendChild(pre);
pre.style.setProperty("margin", "0");
const checkVisibility = () => {
clearTimeout(timer);
if (isLinkMouseEnter || isDivMouseEnter) {
// 今からdiv出すので出てるdivは消す
Array.from(
document.querySelectorAll(`.${className}`)
).forEach((otherDiv) =>
otherDiv.style.setProperty("display", "none")
);
div.style.setProperty("display", "block");
} else {
timer = setTimeout(() => {
div.style.setProperty("display", "none");
}, 400);
}
};
link.addEventListener("mouseenter", () => {
isLinkMouseEnter = true;
checkVisibility();
});
link.addEventListener("mouseleave", () => {
isLinkMouseEnter = false;
checkVisibility();
});
div.addEventListener("mouseenter", () => {
isDivMouseEnter = true;
checkVisibility();
});
div.addEventListener("mouseleave", () => {
isDivMouseEnter = false;
checkVisibility();
});
}
});
});
});
};
scrapbox.PageMenu.addMenu({
title: "行リンクをプレビューする",
image:
"https://user-images.githubusercontent.com/12870472/107356132-c47cdc80-6b13-11eb-83c9-5c40a0b1fedc.png",
onClick,
});