gc_i18n 1.6.1 → 1.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/gc_i18n.es.js +2 -1
- package/lib/gc_i18n.umd.js +1 -1
- package/package.json +2 -2
- package/packages/index.js +3 -7
package/lib/gc_i18n.es.js
CHANGED
|
@@ -3137,7 +3137,8 @@ class X {
|
|
|
3137
3137
|
}, this.tokenResolveVersion = 0, this.manualAuthScope = a || (r ? Ot(r) : ""), this.authUnsubscribe = null, this.authVersion = 0, this.languageVersion = 0, this.activeCacheScope = this.manualAuthScope || "guest", this.loadI18n = !0, this.appCode = o, this.router = n, this.locale = this.normalizeLocale(
|
|
3138
3138
|
d || x.get("I18N_LANGUAGE") || navigator.language || "zh-CN"
|
|
3139
3139
|
), this._isRTL = ke(this.locale), this.persistI18nConfig(), this.name = "", this.messages = On(s || {}), this.translationKeys = [], this.translationKeySet = /* @__PURE__ */ new Set(), this.loginRouteName = c || "login", this.login = i, this.loginTranslationKeys = [], this.keyboard = u || "ctrl+shift+l", this.vueInstances = /* @__PURE__ */ new Set(), this.editKeyboard = e.editKeyboard || "ctrl+shift+e", this.applyAuthState(this.resolveAuthState(), { silent: !0 }), this.initI18n(e), this.router && this.initRouterGuards(), mt.bind(this.keyboard, (_) => {
|
|
3140
|
-
_.preventDefault()
|
|
3140
|
+
if (_.preventDefault(), this.name === this.loginRouteName)
|
|
3141
|
+
return;
|
|
3141
3142
|
const $ = Array.from(this.translationKeySet);
|
|
3142
3143
|
this.translationKeys = Array.from(
|
|
3143
3144
|
/* @__PURE__ */ new Set([...this.translationKeys || [], ...$])
|
package/lib/gc_i18n.umd.js
CHANGED
|
@@ -111,4 +111,4 @@ https://sweetalert2.github.io/#ajax-request`),Cr(t),typeof t.title=="string"&&(t
|
|
|
111
111
|
${y}
|
|
112
112
|
</div>
|
|
113
113
|
</div>
|
|
114
|
-
`,showCloseButton:!0,showConfirmButton:!1,width:"500px",customClass:{container:"i18n-earth-modal-container",popup:"i18n-earth-modal-popup",title:"i18n-earth-modal-title",htmlContainer:"i18n-earth-modal-content"}})},T=()=>{t.request&&typeof t.request=="function"?I():B()};return M.onMounted(()=>{a(),c(),window.addEventListener("message",w),S()}),{currentValue:u,openModal:T}},render(){const{editable:t,width:e,className:n}=this,o=e!==null?{width:e+"px"}:{},s=n?`earth ${n}`:"earth";return M.h("div",{class:s},[M.h("input",{class:"input",type:"text",value:this.currentValue,readonly:!t,disabled:!t,placeholder:"",style:o}),M.h("svg",{class:"icon earth-icon",viewBox:"0 0 24 24",width:"20",height:"20",fill:"currentColor",onClick:this.openModal},[M.h("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"})])])}};function ye(t){if(!t||typeof t!="string")return t;const e=t.toLowerCase();return{"zh-cn":"zh-CN","zh-tw":"zh-TW","zh-hk":"zh-HK","zh-mo":"zh-MO","en-us":"en-US"}[e]||t}function $n(t={}){const e=Object.entries(t||{});return e.some(([,o])=>o&&typeof o=="object"&&!Array.isArray(o)&&Object.keys(o).some(s=>s.includes("-")))?e.reduce((o,[s,r])=>(!r||typeof r!="object"||Array.isArray(r)||Object.entries(r).forEach(([a,c])=>{const i=ye(a);o[i]=o[i]||{},o[i][s]=c}),o),{}):e.reduce((o,[s,r])=>(o[ye(s)]=r,o),{})}function Bn(t,e){return t[e]||t[ye(e)]||t[String(e||"").toLowerCase()]||{}}function ve(t,e){if(typeof t!="string"||!e||typeof e!="object"||Array.isArray(e))return t;const n=Object.entries(e);return t.replace(/\\?\$\{\s*([^}]+?)\s*\}/g,(o,s)=>{const r=String(s||"").trim(),a=n.find(([i])=>i===r||r==="this."+i||r==="_vm."+i||r==="_ctx."+i||r==="$setup."+i||i===r.replace(/^(?:this|_vm|_ctx|\$setup)\./,""));if(!a)return o;const c=a[1];return c!=null?String(c):o})}function Pn(t,e){return e===void 0&&t&&typeof t=="object"&&!Array.isArray(t)?{defaultValue:void 0,values:t}:{defaultValue:t,values:e}}function Hr(t){const{locale:e="zh-CN",messages:n={}}=t,o=$n(n),s=M.ref(e),r=M.ref(0),a=ft(),c=pt()&&a&&typeof a.observable=="function"?a.observable({locale:e,messageVersion:0}):null,i=()=>c?c.locale:s.value,u=w=>{s.value=w,c&&(c.locale=w)},d=()=>{r.value+=1,c&&(c.messageVersion+=1)},h={locale:{get value(){return i()},set value(w){u(w)}},t(w,x,S){const I=Pn(x,S);x=I.defaultValue,S=I.values,r.value,c&&c.messageVersion;const B=i();if(B==="zh-CN"&&!w.startsWith("i.")&&!w.startsWith("pro."))return ve(x||w,S);const T=Bn(o,B);let g=T[w];return g===void 0&&w.includes(".")&&(g=w.split(".").reduce((v,C)=>v&&typeof v=="object"?v[C]:void 0,T)),ve(g&&typeof g=="string"&&g!==w?g:x||w,S)},setLocaleMessage(w,x){return o[ye(w)]={...x},d(),o[ye(w)]},getLocaleMessage(w){return Bn(o,w)}};return h.global=h,h}const _n=Ve.create({timeout:8e3});_n.interceptors.request.use(t=>{const n=(k.get("I18N_CONFIG")||{}).token;return n&&(t.headers.Authorization=`Bearer ${n}`),t});function Dr(t={}){const n=JSON.stringify({alg:"HS512"}),o=JSON.stringify(t);return Nn.jws.JWS.sign("HS512",n,o,"")}function qr(t){if(!t||typeof t!="string")return"";const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(e.length+(4-e.length%4)%4,"=");try{if(typeof atob=="function")return decodeURIComponent(Array.from(atob(n),o=>`%${o.charCodeAt(0).toString(16).padStart(2,"0")}`).join(""))}catch{}return""}function Fr(t){if(!t||typeof t!="string")return null;const e=t.split(".");if(e.length!==3)return null;try{return JSON.parse(qr(e[1]))}catch{return null}}function Kr(t){const e=Fr(t);return!!(e&&(e.mainAppCode&&e.userCode&&e.deviceType||e.appCode&&e.orgCode&&e.userCode&&e.i18n_token))}function Mn(t){if(!t)return"";const e=String(t);let n=0;for(let o=0;o<e.length;o++)n=(n<<5)-n+e.charCodeAt(o),n|=0;return`user_${Math.abs(n)}`}function Ce(t,...e){if(typeof t=="function")return t(...e)}function ft(t){return t&&(t.version||t.prototype||t.config)?t:(M.Vue&&M.Vue.version,M.Vue)}function pt(t){if(t&&t.config&&t.config.globalProperties)return!1;const e=ft(t),n=e&&e.version;return typeof n=="string"?n.split(".")[0]==="2":!!(e&&e.prototype)}function On(t,e=new Set){if(!t||e.has(t))return;e.add(t),typeof t.$forceUpdate=="function"&&t.$forceUpdate(),(t.$children||[]).forEach(o=>On(o,e))}class Y{constructor(e={}){const{router:n,appCode:o,messages:s,token:r,orgCode:a,loginRouteName:c,login:i,keyboard:u,locale:d,env:h,dev:w,i18nTokenRequest:x,auth:S}=e;this.env=h||"local",this.baseUrl=h==="dev"||w===!0?"https://test.ihotel.cn":!h||h==="local"?"":"https://trans.ihotel.cn",this.i18nTokenRequest=x||null,this.baseToken=r||(k.get("I18N_CONFIG")||{}).token||k.get("token"),this.token=this.baseToken,this.auth=S||null,this.authInfo={appCode:o,orgCode:a||"",userCode:""},this.tokenResolveVersion=0,this.manualAuthScope=a||(r?Mn(r):""),this.authUnsubscribe=null,this.authVersion=0,this.languageVersion=0,this.activeCacheScope=this.manualAuthScope||"guest",this.loadI18n=!0,this.appCode=o,this.router=n,this.locale=this.normalizeLocale(d||k.get("I18N_LANGUAGE")||navigator.language||"zh-CN"),this._isRTL=ke(this.locale),this.persistI18nConfig(),this.name="",this.messages=$n(s||{}),this.translationKeys=[],this.translationKeySet=new Set,this.loginRouteName=c||"login",this.login=i,this.loginTranslationKeys=[],this.keyboard=u||"ctrl+shift+l",this.vueInstances=new Set,this.editKeyboard=e.editKeyboard||"ctrl+shift+e",this.applyAuthState(this.resolveAuthState(),{silent:!0}),this.initI18n(e),this.router&&this.initRouterGuards(),se.bind(this.keyboard,I=>{I.preventDefault();const B=Array.from(this.translationKeySet);this.translationKeys=Array.from(new Set([...this.translationKeys||[],...B]));const T={name:this.name,token:this.token,appCode:this.appCode,env:this.env,translationKeys:this.translationKeys},g=this.encodeQueryParams(T),y=`${this.baseUrl}/i18n-admin-front/#/config?data=${g}`;this.swalInstance=z.fire({titleText:"多语言管理",padding:"0px",backdrop:!1,allowOutsideClick:!1,heightAuto:!1,showCloseButton:!0,showConfirmButton:!1,width:"1000px",customClass:{container:"gc_i18n_container",title:"gc_i18n_title",closeButton:"gc_i18n_close_button",htmlContainer:"gc_i18n_html_container"},html:`<iframe src="${y}" style="width: 100%; height: 100%;border: none;min-height: 480px;"></iframe>`})}),se.bind(this.editKeyboard,I=>{I.preventDefault(),Pr.toggle()}),this.setupLanguageChangeListener(),this.setupAuthListener(),this.setupMessageListener()}normalizeLocale(e){return e?e==="zh-TW"||e==="zh-HK"||e==="zh-MO"?e:e.startsWith("zh-")?"zh-CN":e.startsWith("en-")?"en-US":{zh:"zh-CN",en:"en-US"}[e]||e:"zh-CN"}setupLanguageChangeListener(){"onlanguagechange"in window&&window.addEventListener("languagechange",()=>{const e=this.normalizeLocale(navigator.language);e!==this.locale&&this.setLanguage(e)})}resolveAuthState(){const e=this.auth||{},n=Ce(e.getToken)??"",o=Ce(e.getScope)??Ce(e.getUserScope)??"",s=Ce(e.getOrgCode)??"",r=Ce(e.getUserCode)??"",a=typeof e.isAuthenticated=="function"?!!e.isAuthenticated():!!n,c=a?String(o||Mn(n)||this.manualAuthScope||"user"):"guest";return{token:n,scope:c,orgCode:s,userCode:r,isAuthenticated:a}}normalizeAuthInfo(e={}){const n={appCode:e.appCode||this.appCode,orgCode:e.orgCode||"",userCode:e.userCode||""};return this.authInfo=n,n}persistI18nConfig(e={}){k.set("I18N_CONFIG",{...k.get("I18N_CONFIG")||{},baseUrl:this.baseUrl,appCode:this.appCode,token:this.token,locale:this.locale,env:this.env,cacheScope:this.activeCacheScope,...e})}async createI18nToken(e,n={}){if(!e)return"";if(Kr(e))return e;const o={appCode:n.appCode||this.appCode,orgCode:n.orgCode||"",userCode:n.userCode||""};if(!o.orgCode||!o.userCode)return console.warn("非 JWT token 需要通过 setToken(token, { orgCode, userCode }) 提供鉴权信息"),e;try{const s=await Dn({request:this.i18nTokenRequest,appCode:o.appCode||this.appCode,orgCode:o.orgCode,userCode:o.userCode,token:e});return s?Dr({appCode:o.appCode||this.appCode,orgCode:o.orgCode,userCode:o.userCode,i18n_token:s}):(console.warn("获取 i18n_token 失败,继续使用原 token"),e)}catch(s){return console.warn("获取 i18n_token 失败,继续使用原 token",s),e}}resolveAndApplyI18nToken(e,n={},{refresh:o=!0}={}){const s=++this.tokenResolveVersion;return this.createI18nToken(e,n).then(r=>{if(s!==this.tokenResolveVersion||!r)return!1;const a=this.token!==r;return this.token=r,k.set("I18N_TOKEN",this.token),this.persistI18nConfig(),a&&o?this.refreshLanguageForCurrentAuth():a})}applyAuthState(e={},{silent:n=!1}={}){const o=this.token,s=this.activeCacheScope,r=e.token??"",a=e.isAuthenticated?e.scope||"user":"guest";return this.userToken=r,this.token=e.isAuthenticated?r||this.baseToken:this.baseToken,this.activeCacheScope=a,k.set("I18N_TOKEN",this.token),this.persistI18nConfig(),n?!1:o!==this.token||s!==this.activeCacheScope}async refreshLanguageForCurrentAuth(){const e=++this.authVersion,n=this.locale,o=this.activeCacheScope||"guest";return await this.setLanguage(n,{cacheScope:o,authVersion:e})}setupAuthListener(){!this.auth||this.authUnsubscribe||typeof this.auth.subscribe=="function"&&(this.authUnsubscribe=this.auth.subscribe(e=>{const n={token:(e==null?void 0:e.token)??this.resolveAuthState().token,scope:(e==null?void 0:e.scope)??(e==null?void 0:e.userScope)??(e==null?void 0:e.orgCode)??"",orgCode:(e==null?void 0:e.orgCode)??"",userCode:(e==null?void 0:e.userCode)??"",appCode:(e==null?void 0:e.appCode)??this.appCode,isAuthenticated:typeof(e==null?void 0:e.isAuthenticated)=="boolean"?e.isAuthenticated:!!((e==null?void 0:e.token)??this.resolveAuthState().token)};this.applyAuthState(n)&&this.refreshLanguageForCurrentAuth()}))}setupMessageListener(){if(!(this.messageListenerRegistered||typeof window>"u")){this.messageListenerRegistered=!0;try{const e=o=>{!o.origin||o.origin==="null"||(o.data&&o.data.type==="updateLanguage"?(this.setLanguage(this.locale,{cacheScope:this.activeCacheScope,authVersion:this.authVersion}),o.data.close!==!1&&z.close()):o.data&&o.data.type==="closeModal"&&z.close())},n=[window];try{window.parent&&window.parent!==window&&n.push(window.parent)}catch{}try{window.top&&window.top!==window&&window.top!==window.parent&&n.push(window.top)}catch{}this._messageTargets=n,Array.from(new Set(n)).forEach(o=>{o.addEventListener("message",e)})}catch{}}}setRouter(e){return this.router=e,this.initRouterGuards(),this}initRouterGuards(){this.router&&(Y._routerGuardRegistered||(Y._routerGuardRegistered=!0,this.router.beforeEach(async(e,n,o)=>{var c,i;const{language:s,token:r}=e.query;if(this.configInstance&&this.configInstance.closeModal(),this.name=e.name,this.translationKeySet=new Set,r&&await this.setToken(r),this.loadI18n)try{await this.setLanguage(s||this.locale,{cacheScope:this.activeCacheScope})}catch(u){console.error("初始化语言失败,已跳过阻塞:",u)}this.loadI18n=!1;const a=this.router.getRoutes().find(u=>u.name===this.loginRouteName||u.path===`/${this.loginRouteName}`);if(a&&a.components){let u=(c=a.components)==null?void 0:c.default;if(typeof u=="function"&&u.toString().includes("import("))try{u=await u(),u=u.default}catch(h){console.error("加载异步组件时出错:",h),o();return}const d=dt(u);this.loginTranslationKeys=d}if(e.matched.length>0)try{const u=[];for(const d of e.matched){let h=(i=d.components)==null?void 0:i.default;if(typeof h=="function"&&h.toString().includes("import(")&&(h=await h(),h=h.default),h){const w=dt(h);u.push(...w)}}this.translationKeys=u}catch(u){console.error("加载异步组件时出错:",u),o();return}o()}),Y._afterEachGuardRegistered||(Y._afterEachGuardRegistered=!0,this.router.afterEach(async()=>{var r,a;await M.nextTick();const e=Array.from(this.translationKeySet),n=Array.from(new Set([...this.translationKeys||[],...e]));this.translationKeys=n;const o=(r=this.router)==null?void 0:r.currentRoute,s=(a=(o==null?void 0:o.value)??o)==null?void 0:a.name;if(s===this.loginRouteName&&(this.loginTranslationKeys=n),s){this.name=s;const c=k.get("I18N_CONFIG")||{};k.set("I18N_CONFIG",{...c,routerName:s})}}))))}initI18n(e){this.i18n=Hr({locale:this.locale,messages:e.messages||{}}),this.keyValueMap={},globalThis.__I18N_ALL_KEYS__=new Set;const n=this;globalThis.$t=(o,s,r)=>{var h,w;const a=Pn(s,r);if(s=a.defaultValue,r=a.values,typeof o=="string"&&(n.translationKeySet.add(o),globalThis.__I18N_ALL_KEYS__&&globalThis.__I18N_ALL_KEYS__.add(o)),n.i18n.global.locale.value==="zh-CN"&&typeof o=="string"&&!o.startsWith("i.")&&!o.startsWith("pro."))return ve(s||o,r);const i=(h=n.router)==null?void 0:h.currentRoute,u=(w=(i==null?void 0:i.value)??i)==null?void 0:w.name;let d;if(u){const x=`${u}.${o}`,S=n.i18n.t(x,void 0,r);if(S!==x&&!A.isEmpty(S))d=S;else{const I=`common.${o}`,B=n.i18n.t(I,void 0,r);B!==I?d=B:d=n.i18n.t(o,void 0,r)}}else d=n.i18n.t(o,void 0,r);return d===o&&typeof s=="string"&&s&&(d=s),d=ve(d,r),typeof o=="string"&&typeof d=="string"&&(n.keyValueMap[d]=o,globalThis.__I18N_KEY_VALUE_MAP__||(globalThis.__I18N_KEY_VALUE_MAP__={}),globalThis.__I18N_KEY_VALUE_MAP__[d]=o),d},this.t=globalThis.$t,globalThis.$deepScan=function(o){return o},globalThis.$clearI18n=this.clearI18n=()=>{Fn({appCode:this.appCode,cacheScope:this.activeCacheScope})},globalThis.$changeLocale=this.changeLocale=this.i18n.global.changeLocale=async o=>{await this.setLanguage(o||this.locale,{cacheScope:this.activeCacheScope})},globalThis.$isRTL=()=>this._isRTL,this.i18n.global.isRTL=()=>this._isRTL,this.updateDocumentDir()}isRTL(){return this._isRTL}static checkRTL(e){return ke(e)}encodeTranslationKeys(e){if(!e||e.length===0)return"";const n=JSON.stringify(e);return Ue.compressToEncodedURIComponent(n)}encodeQueryParams(e){if(!e)return"";const n=JSON.stringify(e);return Ue.compressToEncodedURIComponent(n)}static decodeTranslationKeys(e){if(!e)return[];try{const n=Ue.decompressFromEncodedURIComponent(e);return n?JSON.parse(n):[]}catch(n){return console.error("解码 translationKeys 失败:",n),[]}}static decodeQueryParams(e){if(!e)return{};try{const n=Ue.decompressFromEncodedURIComponent(e);return n?JSON.parse(n):{}}catch(n){return console.error("解码 query 参数失败:",n),{}}}updateDocumentDir(){typeof document<"u"&&(document.documentElement.dir=this._isRTL?"rtl":"ltr",document.documentElement.lang=this.locale)}notifyLanguageChanged(e,n){pt()&&this.vueInstances&&this.vueInstances.size>0&&M.nextTick(()=>{this.vueInstances.forEach(o=>{On(o)})}),typeof window<"u"&&typeof CustomEvent=="function"&&window.dispatchEvent(new CustomEvent("gc-i18n-language-changed",{detail:{language:e,changed:n}}))}setToken(e,n={}){const o=this.normalizeAuthInfo(n);return this.baseToken=e||"",this.token=this.baseToken,k.set("I18N_TOKEN",this.token),this.persistI18nConfig(),this.resolveAndApplyI18nToken(this.baseToken,o)}async getLanguages(e=!1){return await gt({baseUrl:this.baseUrl,token:this.token,appCode:this.appCode,isRemote:e})}async setLanguage(e="zh-CN",n={}){e=this.normalizeLocale(e);const o=n.cacheScope||this.activeCacheScope||"guest",s=n.authVersion||this.authVersion,r=++this.languageVersion,a="I18N_MESSAGES_COMMON_"+e;let c=k.get(a);if(A.isEmpty(c))try{const i=await _n.get(`https://cdn.ihotel.cn/i18n_messages/${e}.json`);if(i){const{data:u}=i;c=u,k.set(a,u)}}catch(i){console.warn(`公共语言包 ${e} 加载失败,继续使用业务语言数据`,i),c={}}try{const i=await qn({baseUrl:this.baseUrl,appCode:this.appCode,language:e||this.locale,token:this.token,routerName:this.name,cacheScope:o});if(s!==this.authVersion||r!==this.languageVersion)return!1;if(i&&Array.isArray(i)){const u=jn(i),d=A.assign({},c,A.get(this.messages,e),u);this.i18n.global.setLocaleMessage(e,d)}else{const u=A.assign({},c,A.get(this.messages,e));this.i18n.global.setLocaleMessage(e,u)}return this.locale=e,this._isRTL=ke(e),this.i18n.global.locale.value=e,k.set("I18N_LANGUAGE",e),this.updateDocumentDir(),this.notifyLanguageChanged(e,!0),!0}catch(i){if(console.error(`设置语言 ${e} 失败,使用本地消息继续运行:`,i),s!==this.authVersion||r!==this.languageVersion)return!1;const u=A.assign({},c,A.get(this.messages,e));return this.i18n.global.setLocaleMessage(e,u),this.locale=e,this._isRTL=ke(e),this.i18n.global.locale.value=e,k.set("I18N_LANGUAGE",e),this.updateDocumentDir(),this.notifyLanguageChanged(e,!1),!1}}install(e,n={}){if(pt(e)){const o=ft(e);if(o.prototype.$t=this.t||globalThis.$t,o.prototype.$i18n=this.i18n,!Y._vue2UpdateMixinRegistered&&o.mixin){Y._vue2UpdateMixinRegistered=!0;const s=this;o.mixin({beforeCreate(){s.vueInstances.add(this)},beforeDestroy(){s.vueInstances.delete(this)}})}}else e.config.globalProperties.$t=this.t||globalThis.$t,e.config.globalProperties.$i18n=this.i18n;e.component("i18n-earth",{...In,props:{...In.props,baseUrl:{type:String,default:this.baseUrl}}}),this.setupMessageListener()}}V.I18n=Y,V.default=Y,Object.defineProperties(V,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
114
|
+
`,showCloseButton:!0,showConfirmButton:!1,width:"500px",customClass:{container:"i18n-earth-modal-container",popup:"i18n-earth-modal-popup",title:"i18n-earth-modal-title",htmlContainer:"i18n-earth-modal-content"}})},T=()=>{t.request&&typeof t.request=="function"?I():B()};return M.onMounted(()=>{a(),c(),window.addEventListener("message",w),S()}),{currentValue:u,openModal:T}},render(){const{editable:t,width:e,className:n}=this,o=e!==null?{width:e+"px"}:{},s=n?`earth ${n}`:"earth";return M.h("div",{class:s},[M.h("input",{class:"input",type:"text",value:this.currentValue,readonly:!t,disabled:!t,placeholder:"",style:o}),M.h("svg",{class:"icon earth-icon",viewBox:"0 0 24 24",width:"20",height:"20",fill:"currentColor",onClick:this.openModal},[M.h("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"})])])}};function ye(t){if(!t||typeof t!="string")return t;const e=t.toLowerCase();return{"zh-cn":"zh-CN","zh-tw":"zh-TW","zh-hk":"zh-HK","zh-mo":"zh-MO","en-us":"en-US"}[e]||t}function $n(t={}){const e=Object.entries(t||{});return e.some(([,o])=>o&&typeof o=="object"&&!Array.isArray(o)&&Object.keys(o).some(s=>s.includes("-")))?e.reduce((o,[s,r])=>(!r||typeof r!="object"||Array.isArray(r)||Object.entries(r).forEach(([a,c])=>{const i=ye(a);o[i]=o[i]||{},o[i][s]=c}),o),{}):e.reduce((o,[s,r])=>(o[ye(s)]=r,o),{})}function Bn(t,e){return t[e]||t[ye(e)]||t[String(e||"").toLowerCase()]||{}}function ve(t,e){if(typeof t!="string"||!e||typeof e!="object"||Array.isArray(e))return t;const n=Object.entries(e);return t.replace(/\\?\$\{\s*([^}]+?)\s*\}/g,(o,s)=>{const r=String(s||"").trim(),a=n.find(([i])=>i===r||r==="this."+i||r==="_vm."+i||r==="_ctx."+i||r==="$setup."+i||i===r.replace(/^(?:this|_vm|_ctx|\$setup)\./,""));if(!a)return o;const c=a[1];return c!=null?String(c):o})}function Pn(t,e){return e===void 0&&t&&typeof t=="object"&&!Array.isArray(t)?{defaultValue:void 0,values:t}:{defaultValue:t,values:e}}function Hr(t){const{locale:e="zh-CN",messages:n={}}=t,o=$n(n),s=M.ref(e),r=M.ref(0),a=ft(),c=pt()&&a&&typeof a.observable=="function"?a.observable({locale:e,messageVersion:0}):null,i=()=>c?c.locale:s.value,u=w=>{s.value=w,c&&(c.locale=w)},d=()=>{r.value+=1,c&&(c.messageVersion+=1)},h={locale:{get value(){return i()},set value(w){u(w)}},t(w,x,S){const I=Pn(x,S);x=I.defaultValue,S=I.values,r.value,c&&c.messageVersion;const B=i();if(B==="zh-CN"&&!w.startsWith("i.")&&!w.startsWith("pro."))return ve(x||w,S);const T=Bn(o,B);let g=T[w];return g===void 0&&w.includes(".")&&(g=w.split(".").reduce((v,C)=>v&&typeof v=="object"?v[C]:void 0,T)),ve(g&&typeof g=="string"&&g!==w?g:x||w,S)},setLocaleMessage(w,x){return o[ye(w)]={...x},d(),o[ye(w)]},getLocaleMessage(w){return Bn(o,w)}};return h.global=h,h}const _n=Ve.create({timeout:8e3});_n.interceptors.request.use(t=>{const n=(k.get("I18N_CONFIG")||{}).token;return n&&(t.headers.Authorization=`Bearer ${n}`),t});function Dr(t={}){const n=JSON.stringify({alg:"HS512"}),o=JSON.stringify(t);return Nn.jws.JWS.sign("HS512",n,o,"")}function qr(t){if(!t||typeof t!="string")return"";const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.padEnd(e.length+(4-e.length%4)%4,"=");try{if(typeof atob=="function")return decodeURIComponent(Array.from(atob(n),o=>`%${o.charCodeAt(0).toString(16).padStart(2,"0")}`).join(""))}catch{}return""}function Fr(t){if(!t||typeof t!="string")return null;const e=t.split(".");if(e.length!==3)return null;try{return JSON.parse(qr(e[1]))}catch{return null}}function Kr(t){const e=Fr(t);return!!(e&&(e.mainAppCode&&e.userCode&&e.deviceType||e.appCode&&e.orgCode&&e.userCode&&e.i18n_token))}function Mn(t){if(!t)return"";const e=String(t);let n=0;for(let o=0;o<e.length;o++)n=(n<<5)-n+e.charCodeAt(o),n|=0;return`user_${Math.abs(n)}`}function Ce(t,...e){if(typeof t=="function")return t(...e)}function ft(t){return t&&(t.version||t.prototype||t.config)?t:(M.Vue&&M.Vue.version,M.Vue)}function pt(t){if(t&&t.config&&t.config.globalProperties)return!1;const e=ft(t),n=e&&e.version;return typeof n=="string"?n.split(".")[0]==="2":!!(e&&e.prototype)}function On(t,e=new Set){if(!t||e.has(t))return;e.add(t),typeof t.$forceUpdate=="function"&&t.$forceUpdate(),(t.$children||[]).forEach(o=>On(o,e))}class Y{constructor(e={}){const{router:n,appCode:o,messages:s,token:r,orgCode:a,loginRouteName:c,login:i,keyboard:u,locale:d,env:h,dev:w,i18nTokenRequest:x,auth:S}=e;this.env=h||"local",this.baseUrl=h==="dev"||w===!0?"https://test.ihotel.cn":!h||h==="local"?"":"https://trans.ihotel.cn",this.i18nTokenRequest=x||null,this.baseToken=r||(k.get("I18N_CONFIG")||{}).token||k.get("token"),this.token=this.baseToken,this.auth=S||null,this.authInfo={appCode:o,orgCode:a||"",userCode:""},this.tokenResolveVersion=0,this.manualAuthScope=a||(r?Mn(r):""),this.authUnsubscribe=null,this.authVersion=0,this.languageVersion=0,this.activeCacheScope=this.manualAuthScope||"guest",this.loadI18n=!0,this.appCode=o,this.router=n,this.locale=this.normalizeLocale(d||k.get("I18N_LANGUAGE")||navigator.language||"zh-CN"),this._isRTL=ke(this.locale),this.persistI18nConfig(),this.name="",this.messages=$n(s||{}),this.translationKeys=[],this.translationKeySet=new Set,this.loginRouteName=c||"login",this.login=i,this.loginTranslationKeys=[],this.keyboard=u||"ctrl+shift+l",this.vueInstances=new Set,this.editKeyboard=e.editKeyboard||"ctrl+shift+e",this.applyAuthState(this.resolveAuthState(),{silent:!0}),this.initI18n(e),this.router&&this.initRouterGuards(),se.bind(this.keyboard,I=>{if(I.preventDefault(),this.name===this.loginRouteName)return;const B=Array.from(this.translationKeySet);this.translationKeys=Array.from(new Set([...this.translationKeys||[],...B]));const T={name:this.name,token:this.token,appCode:this.appCode,env:this.env,translationKeys:this.translationKeys},g=this.encodeQueryParams(T),y=`${this.baseUrl}/i18n-admin-front/#/config?data=${g}`;this.swalInstance=z.fire({titleText:"多语言管理",padding:"0px",backdrop:!1,allowOutsideClick:!1,heightAuto:!1,showCloseButton:!0,showConfirmButton:!1,width:"1000px",customClass:{container:"gc_i18n_container",title:"gc_i18n_title",closeButton:"gc_i18n_close_button",htmlContainer:"gc_i18n_html_container"},html:`<iframe src="${y}" style="width: 100%; height: 100%;border: none;min-height: 480px;"></iframe>`})}),se.bind(this.editKeyboard,I=>{I.preventDefault(),Pr.toggle()}),this.setupLanguageChangeListener(),this.setupAuthListener(),this.setupMessageListener()}normalizeLocale(e){return e?e==="zh-TW"||e==="zh-HK"||e==="zh-MO"?e:e.startsWith("zh-")?"zh-CN":e.startsWith("en-")?"en-US":{zh:"zh-CN",en:"en-US"}[e]||e:"zh-CN"}setupLanguageChangeListener(){"onlanguagechange"in window&&window.addEventListener("languagechange",()=>{const e=this.normalizeLocale(navigator.language);e!==this.locale&&this.setLanguage(e)})}resolveAuthState(){const e=this.auth||{},n=Ce(e.getToken)??"",o=Ce(e.getScope)??Ce(e.getUserScope)??"",s=Ce(e.getOrgCode)??"",r=Ce(e.getUserCode)??"",a=typeof e.isAuthenticated=="function"?!!e.isAuthenticated():!!n,c=a?String(o||Mn(n)||this.manualAuthScope||"user"):"guest";return{token:n,scope:c,orgCode:s,userCode:r,isAuthenticated:a}}normalizeAuthInfo(e={}){const n={appCode:e.appCode||this.appCode,orgCode:e.orgCode||"",userCode:e.userCode||""};return this.authInfo=n,n}persistI18nConfig(e={}){k.set("I18N_CONFIG",{...k.get("I18N_CONFIG")||{},baseUrl:this.baseUrl,appCode:this.appCode,token:this.token,locale:this.locale,env:this.env,cacheScope:this.activeCacheScope,...e})}async createI18nToken(e,n={}){if(!e)return"";if(Kr(e))return e;const o={appCode:n.appCode||this.appCode,orgCode:n.orgCode||"",userCode:n.userCode||""};if(!o.orgCode||!o.userCode)return console.warn("非 JWT token 需要通过 setToken(token, { orgCode, userCode }) 提供鉴权信息"),e;try{const s=await Dn({request:this.i18nTokenRequest,appCode:o.appCode||this.appCode,orgCode:o.orgCode,userCode:o.userCode,token:e});return s?Dr({appCode:o.appCode||this.appCode,orgCode:o.orgCode,userCode:o.userCode,i18n_token:s}):(console.warn("获取 i18n_token 失败,继续使用原 token"),e)}catch(s){return console.warn("获取 i18n_token 失败,继续使用原 token",s),e}}resolveAndApplyI18nToken(e,n={},{refresh:o=!0}={}){const s=++this.tokenResolveVersion;return this.createI18nToken(e,n).then(r=>{if(s!==this.tokenResolveVersion||!r)return!1;const a=this.token!==r;return this.token=r,k.set("I18N_TOKEN",this.token),this.persistI18nConfig(),a&&o?this.refreshLanguageForCurrentAuth():a})}applyAuthState(e={},{silent:n=!1}={}){const o=this.token,s=this.activeCacheScope,r=e.token??"",a=e.isAuthenticated?e.scope||"user":"guest";return this.userToken=r,this.token=e.isAuthenticated?r||this.baseToken:this.baseToken,this.activeCacheScope=a,k.set("I18N_TOKEN",this.token),this.persistI18nConfig(),n?!1:o!==this.token||s!==this.activeCacheScope}async refreshLanguageForCurrentAuth(){const e=++this.authVersion,n=this.locale,o=this.activeCacheScope||"guest";return await this.setLanguage(n,{cacheScope:o,authVersion:e})}setupAuthListener(){!this.auth||this.authUnsubscribe||typeof this.auth.subscribe=="function"&&(this.authUnsubscribe=this.auth.subscribe(e=>{const n={token:(e==null?void 0:e.token)??this.resolveAuthState().token,scope:(e==null?void 0:e.scope)??(e==null?void 0:e.userScope)??(e==null?void 0:e.orgCode)??"",orgCode:(e==null?void 0:e.orgCode)??"",userCode:(e==null?void 0:e.userCode)??"",appCode:(e==null?void 0:e.appCode)??this.appCode,isAuthenticated:typeof(e==null?void 0:e.isAuthenticated)=="boolean"?e.isAuthenticated:!!((e==null?void 0:e.token)??this.resolveAuthState().token)};this.applyAuthState(n)&&this.refreshLanguageForCurrentAuth()}))}setupMessageListener(){if(!(this.messageListenerRegistered||typeof window>"u")){this.messageListenerRegistered=!0;try{const e=o=>{!o.origin||o.origin==="null"||(o.data&&o.data.type==="updateLanguage"?(this.setLanguage(this.locale,{cacheScope:this.activeCacheScope,authVersion:this.authVersion}),o.data.close!==!1&&z.close()):o.data&&o.data.type==="closeModal"&&z.close())},n=[window];try{window.parent&&window.parent!==window&&n.push(window.parent)}catch{}try{window.top&&window.top!==window&&window.top!==window.parent&&n.push(window.top)}catch{}this._messageTargets=n,Array.from(new Set(n)).forEach(o=>{o.addEventListener("message",e)})}catch{}}}setRouter(e){return this.router=e,this.initRouterGuards(),this}initRouterGuards(){this.router&&(Y._routerGuardRegistered||(Y._routerGuardRegistered=!0,this.router.beforeEach(async(e,n,o)=>{var c,i;const{language:s,token:r}=e.query;if(this.configInstance&&this.configInstance.closeModal(),this.name=e.name,this.translationKeySet=new Set,r&&await this.setToken(r),this.loadI18n)try{await this.setLanguage(s||this.locale,{cacheScope:this.activeCacheScope})}catch(u){console.error("初始化语言失败,已跳过阻塞:",u)}this.loadI18n=!1;const a=this.router.getRoutes().find(u=>u.name===this.loginRouteName||u.path===`/${this.loginRouteName}`);if(a&&a.components){let u=(c=a.components)==null?void 0:c.default;if(typeof u=="function"&&u.toString().includes("import("))try{u=await u(),u=u.default}catch(h){console.error("加载异步组件时出错:",h),o();return}const d=dt(u);this.loginTranslationKeys=d}if(e.matched.length>0)try{const u=[];for(const d of e.matched){let h=(i=d.components)==null?void 0:i.default;if(typeof h=="function"&&h.toString().includes("import(")&&(h=await h(),h=h.default),h){const w=dt(h);u.push(...w)}}this.translationKeys=u}catch(u){console.error("加载异步组件时出错:",u),o();return}o()}),Y._afterEachGuardRegistered||(Y._afterEachGuardRegistered=!0,this.router.afterEach(async()=>{var r,a;await M.nextTick();const e=Array.from(this.translationKeySet),n=Array.from(new Set([...this.translationKeys||[],...e]));this.translationKeys=n;const o=(r=this.router)==null?void 0:r.currentRoute,s=(a=(o==null?void 0:o.value)??o)==null?void 0:a.name;if(s===this.loginRouteName&&(this.loginTranslationKeys=n),s){this.name=s;const c=k.get("I18N_CONFIG")||{};k.set("I18N_CONFIG",{...c,routerName:s})}}))))}initI18n(e){this.i18n=Hr({locale:this.locale,messages:e.messages||{}}),this.keyValueMap={},globalThis.__I18N_ALL_KEYS__=new Set;const n=this;globalThis.$t=(o,s,r)=>{var h,w;const a=Pn(s,r);if(s=a.defaultValue,r=a.values,typeof o=="string"&&(n.translationKeySet.add(o),globalThis.__I18N_ALL_KEYS__&&globalThis.__I18N_ALL_KEYS__.add(o)),n.i18n.global.locale.value==="zh-CN"&&typeof o=="string"&&!o.startsWith("i.")&&!o.startsWith("pro."))return ve(s||o,r);const i=(h=n.router)==null?void 0:h.currentRoute,u=(w=(i==null?void 0:i.value)??i)==null?void 0:w.name;let d;if(u){const x=`${u}.${o}`,S=n.i18n.t(x,void 0,r);if(S!==x&&!A.isEmpty(S))d=S;else{const I=`common.${o}`,B=n.i18n.t(I,void 0,r);B!==I?d=B:d=n.i18n.t(o,void 0,r)}}else d=n.i18n.t(o,void 0,r);return d===o&&typeof s=="string"&&s&&(d=s),d=ve(d,r),typeof o=="string"&&typeof d=="string"&&(n.keyValueMap[d]=o,globalThis.__I18N_KEY_VALUE_MAP__||(globalThis.__I18N_KEY_VALUE_MAP__={}),globalThis.__I18N_KEY_VALUE_MAP__[d]=o),d},this.t=globalThis.$t,globalThis.$deepScan=function(o){return o},globalThis.$clearI18n=this.clearI18n=()=>{Fn({appCode:this.appCode,cacheScope:this.activeCacheScope})},globalThis.$changeLocale=this.changeLocale=this.i18n.global.changeLocale=async o=>{await this.setLanguage(o||this.locale,{cacheScope:this.activeCacheScope})},globalThis.$isRTL=()=>this._isRTL,this.i18n.global.isRTL=()=>this._isRTL,this.updateDocumentDir()}isRTL(){return this._isRTL}static checkRTL(e){return ke(e)}encodeTranslationKeys(e){if(!e||e.length===0)return"";const n=JSON.stringify(e);return Ue.compressToEncodedURIComponent(n)}encodeQueryParams(e){if(!e)return"";const n=JSON.stringify(e);return Ue.compressToEncodedURIComponent(n)}static decodeTranslationKeys(e){if(!e)return[];try{const n=Ue.decompressFromEncodedURIComponent(e);return n?JSON.parse(n):[]}catch(n){return console.error("解码 translationKeys 失败:",n),[]}}static decodeQueryParams(e){if(!e)return{};try{const n=Ue.decompressFromEncodedURIComponent(e);return n?JSON.parse(n):{}}catch(n){return console.error("解码 query 参数失败:",n),{}}}updateDocumentDir(){typeof document<"u"&&(document.documentElement.dir=this._isRTL?"rtl":"ltr",document.documentElement.lang=this.locale)}notifyLanguageChanged(e,n){pt()&&this.vueInstances&&this.vueInstances.size>0&&M.nextTick(()=>{this.vueInstances.forEach(o=>{On(o)})}),typeof window<"u"&&typeof CustomEvent=="function"&&window.dispatchEvent(new CustomEvent("gc-i18n-language-changed",{detail:{language:e,changed:n}}))}setToken(e,n={}){const o=this.normalizeAuthInfo(n);return this.baseToken=e||"",this.token=this.baseToken,k.set("I18N_TOKEN",this.token),this.persistI18nConfig(),this.resolveAndApplyI18nToken(this.baseToken,o)}async getLanguages(e=!1){return await gt({baseUrl:this.baseUrl,token:this.token,appCode:this.appCode,isRemote:e})}async setLanguage(e="zh-CN",n={}){e=this.normalizeLocale(e);const o=n.cacheScope||this.activeCacheScope||"guest",s=n.authVersion||this.authVersion,r=++this.languageVersion,a="I18N_MESSAGES_COMMON_"+e;let c=k.get(a);if(A.isEmpty(c))try{const i=await _n.get(`https://cdn.ihotel.cn/i18n_messages/${e}.json`);if(i){const{data:u}=i;c=u,k.set(a,u)}}catch(i){console.warn(`公共语言包 ${e} 加载失败,继续使用业务语言数据`,i),c={}}try{const i=await qn({baseUrl:this.baseUrl,appCode:this.appCode,language:e||this.locale,token:this.token,routerName:this.name,cacheScope:o});if(s!==this.authVersion||r!==this.languageVersion)return!1;if(i&&Array.isArray(i)){const u=jn(i),d=A.assign({},c,A.get(this.messages,e),u);this.i18n.global.setLocaleMessage(e,d)}else{const u=A.assign({},c,A.get(this.messages,e));this.i18n.global.setLocaleMessage(e,u)}return this.locale=e,this._isRTL=ke(e),this.i18n.global.locale.value=e,k.set("I18N_LANGUAGE",e),this.updateDocumentDir(),this.notifyLanguageChanged(e,!0),!0}catch(i){if(console.error(`设置语言 ${e} 失败,使用本地消息继续运行:`,i),s!==this.authVersion||r!==this.languageVersion)return!1;const u=A.assign({},c,A.get(this.messages,e));return this.i18n.global.setLocaleMessage(e,u),this.locale=e,this._isRTL=ke(e),this.i18n.global.locale.value=e,k.set("I18N_LANGUAGE",e),this.updateDocumentDir(),this.notifyLanguageChanged(e,!1),!1}}install(e,n={}){if(pt(e)){const o=ft(e);if(o.prototype.$t=this.t||globalThis.$t,o.prototype.$i18n=this.i18n,!Y._vue2UpdateMixinRegistered&&o.mixin){Y._vue2UpdateMixinRegistered=!0;const s=this;o.mixin({beforeCreate(){s.vueInstances.add(this)},beforeDestroy(){s.vueInstances.delete(this)}})}}else e.config.globalProperties.$t=this.t||globalThis.$t,e.config.globalProperties.$i18n=this.i18n;e.component("i18n-earth",{...In,props:{...In.props,baseUrl:{type:String,default:this.baseUrl}}}),this.setupMessageListener()}}V.I18n=Y,V.default=Y,Object.defineProperties(V,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gc_i18n",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./lib/gc_i18n.umd.js",
|
|
6
6
|
"module": "./lib/gc_i18n.es.js",
|
|
@@ -56,4 +56,4 @@
|
|
|
56
56
|
"vue-router": "^4.5.0"
|
|
57
57
|
},
|
|
58
58
|
"packageManager": "pnpm@10.15.1+sha512.34e538c329b5553014ca8e8f4535997f96180a1d0f614339357449935350d924e22f8614682191264ec33d1462ac21561aff97f6bb18065351c162c7e8f6de67"
|
|
59
|
-
}
|
|
59
|
+
}
|
package/packages/index.js
CHANGED
|
@@ -433,13 +433,9 @@ class I18n {
|
|
|
433
433
|
|
|
434
434
|
keyboardJS.bind(this.keyboard, (e) => {
|
|
435
435
|
e.preventDefault();
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
// this.configInstance = this.createModal(this.name);
|
|
440
|
-
// // 打开弹窗
|
|
441
|
-
// this.configInstance.openModal({ name: this.name });
|
|
442
|
-
// }
|
|
436
|
+
if (this.name === this.loginRouteName) {
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
443
439
|
const runtimeKeys = Array.from(this.translationKeySet);
|
|
444
440
|
this.translationKeys = Array.from(
|
|
445
441
|
new Set([...(this.translationKeys || []), ...runtimeKeys])
|