Skip to content

Instantly share code, notes, and snippets.

@gijigae
Created November 12, 2022 01:39
Show Gist options
  • Select an option

  • Save gijigae/e07a0bc71e8bc7d94128262f9428477c to your computer and use it in GitHub Desktop.

Select an option

Save gijigae/e07a0bc71e8bc7d94128262f9428477c to your computer and use it in GitHub Desktop.
JavaScript file for Newsela to Roam without Lexile
const roamfy = (d) => {
const ord = (n) => n + (n > 0 ? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10] : '');
const year = d.getFullYear();
const month = d.toLocaleString('en-us', { month: 'long' });
const date = ord(d.getDate());
return `${month} ${date}, ${year}`
}
const title = document.querySelector("#article-title").textContent;
const topic = document.querySelector("h2[data-qa-selector=article_label_text]").textContent;
const wordCount = document.querySelector("div span[data-qa-selector=word_count]").textContent;
// const lexile = document.querySelector("#toggle-level-menu-button > span.css-1kpr3n6-Yo > span.css-1xa972w-Yo > span").textContent;
const imageSrc = document.querySelector("article img").getAttribute("src");
const publishedDateDOMRes = document.evaluate("//span[text()='Published:']", document, null, XPathResult.ANY_TYPE, null);
const publishedDateDOM = publishedDateDOMRes.iterateNext();
const publishedDate = new Date(publishedDateDOM.nextElementSibling.textContent);
const published = roamfy(publishedDate);
const articleTexts = document.querySelectorAll("div[data-qa-selector=article_text] p,div[data-qa-selector=article_text] h2");
let source = location.href;
try {
source = document.querySelector("link[rel='canonical']").getAttribute("href") ;
} catch (e) {
console.log("canonical url is not found.");
}
const attributes = [
//`- Lexile: ${lexile}`,
`- Topic: #[[${topic}]]`,
//`Published: [[${published}]]`,
`Words: ${wordCount}`,
`Source: ${source}`,
`![](${imageSrc})\n- `
];
let res = attributes.join("\n- ");
let inParagraph = false;
const putIndent = (inParagraph) => {
const indent = inParagraph ? 4 : 2;
return " ".repeat(indent);
}
articleTexts.forEach((n) => {
const isH2 = n.tagName === "H2"
const hasImage = n.querySelector("img") !== null;
if (isH2) {
inParagraph = false;
}
let text = isH2 ? `## ${n.textContent}` : n.textContent; // Boldの始まり
if (hasImage) {
const imageSrc = n.querySelector("img").getAttribute("src");
text = `![](${imageSrc})\n- ${text}`;
}
res += `${putIndent(inParagraph)} ${text}\n- `;
if (isH2) {
inParagraph = true;
}
});
navigator.clipboard.writeText(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment