mirror of
https://github.com/the1812/Bilibili-Evolved.git
synced 2025-11-04 21:22:45 +08:00
1 line
2.3 KiB
JavaScript
1 line
2.3 KiB
JavaScript
(()=>{return(e,t)=>{const s={"日本語":"ja-JP",English:"en-US",Deutsch:"de-DE"};class a{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 s=a.map.get(t.trim());if(s===undefined){const s=a.regex.find(([e])=>e.test(t));if(s){const[a,r]=s;this.setValue(e,t.replace(a,r))}}else if(typeof s==="string"){this.setValue(e,s)}else if(Array.isArray(s)){let t=null;for(const a of s){if(typeof a==="string"){t=a}else{const{text:s,selector:r,not:l}=a;if(this.getElement(e).matches(r)!==Boolean(l)){t=s}}}if(t!==null){this.setValue(e,t)}}else{const{text:t,selector:a,not:r}=s;if(this.getElement(e).matches(a)!==Boolean(r)){this.setValue(e,t)}}}static walk(e,t){const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null,false);let a=s.nextNode();while(a){t(a);a=s.nextNode()}}static translate(e){if(e.nodeType===Node.TEXT_NODE){a.textNode.translate(e);return}a.walk(e,e=>{for(const t of a.allTranslators){if(t.accepts(e)){t.translate(e)}}})}static translateCssMatches(){const e=a.map.get("*");if(!e){return}for(const{selector:t,text:s}of e){const e=document.querySelector(t);if(e){[...e.childNodes].filter(e=>e.nodeType===Node.TEXT_NODE).forEach(e=>e.nodeValue=s)}}}}class r extends a{accepts(e){return e.nodeType===Node.TEXT_NODE}getElement(e){return e.parentElement}}class l extends a{getValue(e){return e.getAttribute("title")}setValue(e,t){e.setAttribute("title",t)}}class n extends a{getValue(e){return e.getAttribute("placeholder")}setValue(e,t){e.setAttribute("placeholder",t)}}a.textNode=new r;a.title=new l;a.placeholder=new n;a.allTranslators=[a.textNode,a.title,a.placeholder];(async()=>{const r=s[e.i18nLanguage];const{map:l,regex:n}=await t.importAsync(`i18n.${r}`);document.documentElement.setAttribute("lang",r);a.map=l;a.regex=[...n.entries()];a.translate(document.body);a.translateCssMatches();Observer.observe("body",e=>{e.forEach(e=>{if(e.type==="childList"){if(e.addedNodes.length>0){a.translateCssMatches()}e.addedNodes.forEach(e=>{a.translate(e)})}else if(e.type==="characterData"){a.textNode.translate(e.target)}})},{characterData:true,childList:true,subtree:true})})();return{export:{Translator:a,TextNodeTranslator:r,TitleTranslator:l,PlaceholderTranslator:n}}}})(); |