Created
May 23, 2023 02:29
-
-
Save danieltharp/05a260393c97baac13099336cf44db42 to your computer and use it in GitHub Desktop.
Minified furigana renderer
This file contains hidden or 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
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)}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For a toggle (and the unminified version) as well as example usage, see https://gist.github.com/danieltharp/c6733be49cafc62562f182c4d5fa2a00?permalink_comment_id=4576395#gistcomment-4576395