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 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){const a=s.regex.find(([e])=>e.test(t));if(a){const[s,r]=a;this.setValue(e,t.replace(s,r))}}else 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:l}=s;if(this.getElement(e).matches(r)!==Boolean(l)){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 l extends s{getValue(e){return e.getAttribute("title")}setValue(e,t){e.setAttribute("title",t)}}class n extends s{getValue(e){return e.getAttribute("placeholder")}setValue(e,t){e.setAttribute("placeholder",t)}}s.textNode=new r;s.title=new l;s.placeholder=new n;s.allTranslators=[s.textNode,s.title,s.placeholder];(async()=>{const{map:r,regex:l}=await t.importAsync(`i18n.${a[e.i18nLanguage]}`);s.map=r;s.regex=[...l.entries()];s.translate(document.body);s.translateCssMatches();Observer.observe("body",e=>{e.forEach(e=>{if(e.type==="childList"){if(e.addedNodes.length>0){s.translateCssMatches()}e.addedNodes.forEach(e=>{s.translate(e)})}else if(e.type==="characterData"){s.textNode.translate(e.target)}})},{characterData:true,childList:true,subtree:true})})();return{export:{Translator:s,TextNodeTranslator:r,TitleTranslator:l,PlaceholderTranslator:n}}}})(); |