Bilibili-Evolved/min/i18n.min.js
2019-03-31 22:44:11 +08:00

1 line
2.1 KiB
JavaScript

(()=>{return(e,t)=>{const a={"日本語":"ja-JP",English:"en-US",Deutsch:"de-DE"};class s{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=s.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 s of a){if(typeof s==="string"){t=s}else{const{text:a,selector:r,not:n}=s;if(this.getElement(e).matches(r)!==Boolean(n)){t=a}}}if(t!==null){this.setValue(e,t)}}else{const{text:t,selector:s,not:r}=a;if(this.getElement(e).matches(s)!==Boolean(r)){this.setValue(e,t)}}}static walk(e,t){const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null,false);let s=a.nextNode();while(s){t(s);s=a.nextNode()}}static translate(e){if(e.nodeType===Node.TEXT_NODE){s.textNode.translate(e);return}s.walk(e,e=>{for(const t of s.allTranslators){if(t.accepts(e)){t.translate(e)}}})}static translateCssMatches(){const e=s.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 r extends s{accepts(e){return e.nodeType===Node.TEXT_NODE}getElement(e){return e.parentElement}}class n extends s{getValue(e){return e.getAttribute("title")}setValue(e,t){e.setAttribute("title",t)}}class l extends s{accepts(e){return e.nodeName==="INPUT"&&e.type.toUpperCase()==="TEXT"||e.nodeName==="TEXTAREA"}getValue(e){return e.getAttribute("placeholder")}setValue(e,t){e.setAttribute("placeholder",t)}}s.textNode=new r;s.title=new n;s.placeholder=new l;s.allTranslators=[s.textNode,s.title,s.placeholder];(async()=>{const{map:r}=await t.importAsync(`i18n.${a[e.i18nLanguage]}`);s.map=r;s.translate(document.body);s.translateCssMatches();Observer.childListSubtree("body",e=>{e.forEach(e=>{if(e.addedNodes.length>0){s.translateCssMatches()}e.addedNodes.forEach(e=>{s.translate(e)})})})})();return{export:{Translator:s,TextNodeTranslator:r,TitleTranslator:n,PlaceholderTranslator:l}}}})();