Fix kbin Code Blocks

Fix for kbin code blocks federated from Lemmy. Strips out the weird <span> tags on each line.

目前为 2023-11-21 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Fix kbin Code Blocks
  3. // @namespace pamasich-kbin
  4. // @version 1.2
  5. // @description Fix for kbin code blocks federated from Lemmy. Strips out the weird <span> tags on each line.
  6. // @author Pamasich
  7. // @match https://kbin.social/*
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=kbin.social
  9. // @license MIT
  10. // @grant none
  11. // ==/UserScript==
  12.  
  13. const testPattern = /\n?<span style="color:#323232;">(.+\n)+<\/span>\n?/;
  14. const startTagPattern = /^\n?<span style="color:#323232;">/g;
  15. const endTagPattern = /<\/span>\n?$/g;
  16. const combinedPattern = /^<\/span><span style="color:#323232;">/gm;
  17.  
  18. function fixCodeBlock(code) {
  19. if (testPattern.test(code.innerText)) {
  20. code.innerText = code.innerText
  21. .replace(startTagPattern, "")
  22. .replaceAll(combinedPattern, "")
  23. .replace(endTagPattern, "");
  24. }
  25. }
  26.  
  27. // used to ensure the code blocks in the thread body itself, not just the comments, are replaced
  28. // unlike the blockquote for comments, it doesn't seem like the MutationObserver is picking up any article elements or anything nearby I could use
  29. document.querySelectorAll("pre code").forEach(fixCodeBlock);
  30.  
  31. const observer = new MutationObserver(mutations => {
  32. const codeBlocks = mutations.flatMap(mutation => Array.from(mutation.addedNodes))
  33. // only do something if new comments were added (BLOCKQUOTE) or a thread is opened while in turbo mode (BODY)
  34. .filter(node => node.nodeName == "BLOCKQUOTE" || node.nodeName == "BODY")
  35. .map(node => Array.from(node.querySelectorAll("pre code")))
  36. .flat(1);
  37. // codeBlocks at this point might contain the same node twice, so the Set constructor is used to get unique nodes
  38. new Set(codeBlocks).forEach(fixCodeBlock);
  39. });
  40. // observing the entire document because of turbo mode
  41. observer.observe(document, { childList: true, subtree: true });