mirror of
https://github.com/the1812/Bilibili-Evolved.git
synced 2025-11-04 21:22:45 +08:00
1 line
2.6 KiB
JavaScript
1 line
2.6 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){let t=this.getValue(e);if(!t||typeof t!=="string"||t==="*"){return}t=t.trim();const a=r.map.get(t);if(a===undefined){const a=r.regex.find(([e])=>e.test(t));if(a){const[r,s]=a;this.setValue(e,t.replace(r,s))}}else 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}const t=e=>{for(const t of r.allTranslators){if(t.accepts(e)){t.translate(e)}}};t(e);r.walk(e,t)}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];const o=async()=>{const s=a[e.i18nLanguage];const{map:l,regex:n}=await t.importAsync(`i18n.${s}`);document.documentElement.setAttribute("lang",s);r.map=l;r.regex=[...n.entries()];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)}else if(e.type==="attributes"){if(e.attributeName==="title"){r.title.translate(e.target)}else if(e.attributeName==="placeholder"){r.placeholder.translate(e.target)}}})},{characterData:true,childList:true,subtree:true,attributes:true})};o();return{export:{Translator:r,TextNodeTranslator:s,TitleTranslator:l,PlaceholderTranslator:n},dropdown:{key:"i18nLanguage",items:[`日本語`]}}}})(); |