Bilibili-Evolved/min/i18n.min.js
2019-04-04 22:25:27 +08:00

1 line
2.1 KiB
JavaScript

(()=>{return(e,t)=>{const a={"日本語":"ja-JP",English:"en-US",Deutsch:"de-DE"};class r{accepts(e){return e.nodeType===Node.ELEMENT_NODE}getValue(e){return e.nodeValue}setValue(e,t){e.nodeValue=t}getElement(e){return e}translate(e){const t=this.getValue(e);if(!t||typeof t!=="string"||t==="*"){return}const a=r.map.get(t.trim());if(a===undefined){return}if(typeof a==="string"){this.setValue(e,a)}else if(Array.isArray(a)){let t=null;for(const r of a){if(typeof r==="string"){t=r}else{const{text:a,selector:s,not:l}=r;if(this.getElement(e).matches(s)!==Boolean(l)){t=a}}}if(t!==null){this.setValue(e,t)}}else{const{text:t,selector:r,not:s}=a;if(this.getElement(e).matches(r)!==Boolean(s)){this.setValue(e,t)}}}static walk(e,t){const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null,false);let r=a.nextNode();while(r){t(r);r=a.nextNode()}}static translate(e){if(e.nodeType===Node.TEXT_NODE){r.textNode.translate(e);return}r.walk(e,e=>{for(const t of r.allTranslators){if(t.accepts(e)){t.translate(e)}}})}static translateCssMatches(){const e=r.map.get("*");if(!e){return}for(const{selector:t,text:a}of e){const e=document.querySelector(t);if(e){[...e.childNodes].filter(e=>e.nodeType===Node.TEXT_NODE).forEach(e=>e.nodeValue=a)}}}}class s extends r{accepts(e){return e.nodeType===Node.TEXT_NODE}getElement(e){return e.parentElement}}class l extends r{getValue(e){return e.getAttribute("title")}setValue(e,t){e.setAttribute("title",t)}}class n extends r{getValue(e){return e.getAttribute("placeholder")}setValue(e,t){e.setAttribute("placeholder",t)}}r.textNode=new s;r.title=new l;r.placeholder=new n;r.allTranslators=[r.textNode,r.title,r.placeholder];(async()=>{const{map:s}=await t.importAsync(`i18n.${a[e.i18nLanguage]}`);r.map=s;r.translate(document.body);r.translateCssMatches();Observer.observe("body",e=>{e.forEach(e=>{if(e.type==="childList"){if(e.addedNodes.length>0){r.translateCssMatches()}e.addedNodes.forEach(e=>{r.translate(e)})}else if(e.type==="characterData"){r.textNode.translate(e.target)}})},{characterData:true,childList:true,subtree:true})})();return{export:{Translator:r,TextNodeTranslator:s,TitleTranslator:l,PlaceholderTranslator:n}}}})();