Skip to content

Instantly share code, notes, and snippets.

@arcatdmz
Created February 13, 2022 05:41
Show Gist options
  • Save arcatdmz/fa1552c8af5efe7c0ccf972394cbeb00 to your computer and use it in GitHub Desktop.
Save arcatdmz/fa1552c8af5efe7c0ccf972394cbeb00 to your computer and use it in GitHub Desktop.
Parse code blocks in Scrapbox pages
const traverseCodeBlock = ({ fileNamePattern, perLine, preBlock, postBlock }) => [...document.querySelectorAll(".code-block")].filter(el => el.children[1].firstChild.className === "code-start" && fileNamePattern.test(el.textContent)).map(el => {
let line = el.parentElement, classList;
preBlock && preBlock(line);
line = line.nextSibling;
while (line && [...line.children[1].classList].indexOf("code-block") >= 0) {
perLine && perLine(line); line = line.nextSibling;
}
postBlock && postBlock(line);
});
const getScripts = (fileNamePattern) => {
let content, scripts = [];
traverseCodeBlock({
fileNamePattern,
preBlock() { content = []; },
perLine(line) { content.push(line.textContent); },
postBlock() { scripts.push(content.join("\n")); }
});
return scripts;
}
const json = getScripts(/.+\.json$/).map(script => {
try { return JSON.parse(script); }
catch (e) { return {}; }
});
console.log("json data:", json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment