Skip to content

Instantly share code, notes, and snippets.

@danieltharp
Created May 23, 2023 02:29
Show Gist options
  • Save danieltharp/05a260393c97baac13099336cf44db42 to your computer and use it in GitHub Desktop.
Save danieltharp/05a260393c97baac13099336cf44db42 to your computer and use it in GitHub Desktop.
Minified furigana renderer
const R=/{((?:[\u2E80-\uA4CF\uFF00-\uFFEF])+)((?:\|[^ -\/{-~:-@\[-`]*)+)}/gm,T="p, h1, h2, h3, h4, h5, h6, ol, ul, table";function cF(e){let t=Array.from(e.textContent.matchAll(R)),n=e;for(let l of t){let r=l[2].split("|").slice(1),h=1===r.length?[l[1]]:l[1].split("");if(h.length===r.length){let o=document.createElement("ruby");o.classList.add("furigana"),h.forEach((e,t)=>{o.insertAdjacentHTML("beforeend",e+"<rt>"+r[t]+"</rt>")});let a=n.splitText(n.textContent.indexOf(l[0]));n=a.splitText(l[0].length),a.replaceWith(o)}}return e}function rF(e){let t=e.querySelectorAll(T);0!==t.length&&t.forEach(e=>{!function e(t){let n=[];t.childNodes.forEach(t=>{3===t.nodeType?n.push(t):t.hasChildNodes()&&"CODE"!==t.nodeName&&"RUBY"!==t.nodeName&&e(t)}),n.forEach(e=>{e.replaceWith(cF(e))})}(e)})}window.onload=function(){rF(document.body)};
@danieltharp
Copy link
Author

danieltharp commented May 23, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment