Last active
September 25, 2017 14:29
-
-
Save cking/8557b26538bd2c7d19b05df660e4ac09 to your computer and use it in GitHub Desktop.
Mastodon Markdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Markdown | |
// @namespace Paars | |
// @author Kura | |
// @version 1.1.1 | |
// @match *://niu.moe/web/* | |
// @require https://cdn.rawgit.com/chjj/marked/8f9d0b72/marked.min.js | |
// @run-at document-end | |
// @grant GM_addStyle | |
// ==/UserScript== | |
marked.setOptions({ breaks: false }) | |
GM_addStyle(` | |
i, em { font-style: italic; } | |
b, strong{ font-weight: bold; } | |
u { text-decoration: underline; } | |
.status > div:nth-child(2) { white-space: inherit; } | |
`) | |
function attributesToString(attr) { | |
return Array.from(attr).map(a => `${a.name}="${a.value}"`).join(" ") | |
} | |
function nodeToString(n) { | |
let data = "" | |
for (let idx = 0; idx < n.childNodes.length; idx++) { | |
const c = n.childNodes[idx] | |
if (c.nodeType === Node.TEXT_NODE) { | |
data += c.nodeValue | |
continue | |
} | |
switch (c.nodeName) { | |
case "IMG": | |
case "BR": | |
data += "<" + c.nodeName.toLowerCase() + " " + attributesToString(c.attributes) + " />" | |
continue | |
case "P": | |
break | |
default: | |
data += "<" + c.nodeName.toLowerCase() + " " + attributesToString(c.attributes) + ">" | |
} | |
data += nodeToString(c) | |
switch (c.nodeName) { | |
case "P": | |
data += "\n\n"; | |
break | |
default: | |
data += "</" + c.nodeName.toLowerCase() + ">"; | |
break | |
} | |
} | |
return data | |
} | |
const observer = new MutationObserver(records => { | |
records.forEach(r => { | |
if (!r.addedNodes.length) { | |
return | |
} | |
r.addedNodes.forEach(n => { | |
if (n.nodeName !== "ARTICLE" && !(n.classList && n.classList.contains("detailed-status__wrapper"))) { | |
return | |
} | |
const status = n.querySelector(".status > div:nth-child(2), .detailed-status > div:nth-child(2)") | |
if (!status) { | |
return | |
} | |
const txt = nodeToString(status) | |
const md = marked(txt) | |
const frag = document.createRange().createContextualFragment(md) | |
while (status.firstChild) status.removeChild(status.firstChild) | |
status.appendChild(frag) | |
}) | |
}) | |
}) | |
Array.from(document.querySelectorAll("#mastodon")).forEach(list => observer.observe(list, { | |
childList: true, | |
attributes: false, | |
characterData: false, | |
subtree: true | |
})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍