web-internationalization 2.0.32 → 2.0.34
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/index.d.ts +89 -6
- package/index.js +1 -1
- package/package.json +1 -1
- package/type.d.ts +2 -2
package/index.d.ts
CHANGED
|
@@ -52,7 +52,7 @@ export declare const log: Logger;
|
|
|
52
52
|
* @property lock - Lock instance when updating dom noes.
|
|
53
53
|
* @property _domNodesToFade - Saves all dom nodes that should be animated.
|
|
54
54
|
* @property _replacements - Saves all text nodes that should be replaced.
|
|
55
|
-
* @property
|
|
55
|
+
* @property _domNodesWithKnownTranslation - Saves a mapping of known text
|
|
56
56
|
* snippets to their corresponding $-extended dom nodes.
|
|
57
57
|
*/
|
|
58
58
|
export declare class WebInternationalization<TElement = HTMLElement, ExternalProperties extends Mapping<unknown> = Mapping<unknown>, InternalProperties extends Mapping<unknown> = Mapping<unknown>> extends Web<TElement, ExternalProperties, InternalProperties> {
|
|
@@ -70,7 +70,7 @@ export declare class WebInternationalization<TElement = HTMLElement, ExternalPro
|
|
|
70
70
|
lock: Lock<string | undefined>;
|
|
71
71
|
_domNodesToFade: Array<HTMLElement>;
|
|
72
72
|
_replacements: Array<Replacement>;
|
|
73
|
-
|
|
73
|
+
_domNodesWithKnownTranslation: Mapping<Array<HTMLItem>>;
|
|
74
74
|
/**
|
|
75
75
|
* Defines dynamic getter and setter interface and resolves a configuration
|
|
76
76
|
* object. Initializes the map implementation.
|
|
@@ -134,7 +134,49 @@ export declare class WebInternationalization<TElement = HTMLElement, ExternalPro
|
|
|
134
134
|
* @param ensure - Indicates if the whole dom should be checked again
|
|
135
135
|
* current language to ensure every text node has right content.
|
|
136
136
|
*/
|
|
137
|
-
|
|
137
|
+
_collectDomNodesToReplace(language: string, ensure: boolean): void;
|
|
138
|
+
/**
|
|
139
|
+
* Determines whether a given dom node should be skipped during
|
|
140
|
+
* translation collection.
|
|
141
|
+
* @param domNode - The dom node to evaluate.
|
|
142
|
+
* @param nodeTextContent - Pre-computed text content of the node.
|
|
143
|
+
* @param currentDomNodeToTranslate - The currently tracked translation
|
|
144
|
+
* ancestor node.
|
|
145
|
+
* @returns Returns true if the node should be skipped.
|
|
146
|
+
*/
|
|
147
|
+
_shouldSkipDomNode(domNode: Node, nodeTextContent: Array<string>, currentDomNodeToTranslate: HTMLItem | null): boolean;
|
|
148
|
+
/**
|
|
149
|
+
* Processes an alternative dom node by finding its active sibling,
|
|
150
|
+
* ensuring it has the necessary attributes and registering it for
|
|
151
|
+
* replacement.
|
|
152
|
+
* @param domNode - The alternative language dom node.
|
|
153
|
+
* @param language - New language to use.
|
|
154
|
+
* @param ensure - Indicates if current language should be ensured again
|
|
155
|
+
* every text node content.
|
|
156
|
+
* @param currentLanguageDomNode - The currently tracked language indicator
|
|
157
|
+
* node.
|
|
158
|
+
*/
|
|
159
|
+
_processAlternativeDomNode(domNode: HTMLItem, language: string, ensure: boolean, currentLanguageDomNode: HTMLItem | null): void;
|
|
160
|
+
_initializeCurrentLanguageDomNode(domNode: Element, ensure: boolean): void;
|
|
161
|
+
/**
|
|
162
|
+
* Processes a replacement dom node like comment or lang-replacement
|
|
163
|
+
* element and updates translation state accordingly.
|
|
164
|
+
* @param domNode - The replacement dom node.
|
|
165
|
+
* @param nodeName - Lowercase node name of the replacement node.
|
|
166
|
+
* @param language - New language to use.
|
|
167
|
+
* @param ensure - Indicates if current language should be ensured again
|
|
168
|
+
* every text node content.
|
|
169
|
+
* @param currentDomNodeToTranslate - The currently tracked node whose
|
|
170
|
+
* content is to be replaced.
|
|
171
|
+
* @param currentLanguageDomNode - The currently tracked language indicator
|
|
172
|
+
* node.
|
|
173
|
+
* @returns Updated references for the tracked translation and language
|
|
174
|
+
* indicator nodes.
|
|
175
|
+
*/
|
|
176
|
+
_processReplacementDomNode(domNode: HTMLItem, nodeName: string, language: string, ensure: boolean, currentDomNodeToTranslate: HTMLItem, currentLanguageDomNode: HTMLItem | null): {
|
|
177
|
+
domNodeToTranslate: HTMLItem | null;
|
|
178
|
+
languageDomNode: HTMLItem | null;
|
|
179
|
+
};
|
|
138
180
|
/**
|
|
139
181
|
* Iterates all text nodes in language known area with known translations.
|
|
140
182
|
*/
|
|
@@ -153,14 +195,14 @@ export declare class WebInternationalization<TElement = HTMLElement, ExternalPro
|
|
|
153
195
|
_determineUsefulLanguage(): string;
|
|
154
196
|
/**
|
|
155
197
|
* Registers a text node to change its content with a given replacement.
|
|
156
|
-
* @param
|
|
198
|
+
* @param domNodeToTranslate - Text node with content to
|
|
157
199
|
* translate.
|
|
158
|
-
* @param
|
|
200
|
+
* @param domNodeToReplaceWith - A node with replacement content.
|
|
159
201
|
* @param textToReplaceWith - Text content to use as replacement.
|
|
160
202
|
* @param currentLanguageDomNode - A potential given text node indicating
|
|
161
203
|
* the language of given text node.
|
|
162
204
|
*/
|
|
163
|
-
_registerTextNodeToChange(
|
|
205
|
+
_registerTextNodeToChange(domNodeToTranslate: HTMLItem, domNodeToReplaceWith: HTMLItem | null, textToReplaceWith: string, currentLanguageDomNode: HTMLItem | null): void;
|
|
164
206
|
/**
|
|
165
207
|
* Checks if the last text node has a language indication comment node.
|
|
166
208
|
* This function is called after each parsed dom text node.
|
|
@@ -179,6 +221,47 @@ export declare class WebInternationalization<TElement = HTMLElement, ExternalPro
|
|
|
179
221
|
* @param language - The new language to switch to.
|
|
180
222
|
*/
|
|
181
223
|
_switchLanguage(language: string): void;
|
|
224
|
+
/**
|
|
225
|
+
* Returns the current text content of a dom node, preferring innerHTML
|
|
226
|
+
* over textContent when available.
|
|
227
|
+
* @param domNode - The dom node to read the text content from.
|
|
228
|
+
* @returns The current text content of the dom node.
|
|
229
|
+
*/
|
|
230
|
+
_getCurrentNodeText(domNode: HTMLItem): string;
|
|
231
|
+
/**
|
|
232
|
+
* Resolves the current language dom node for a given replacement. If the
|
|
233
|
+
* node was not set initially it is determined by iterating through the
|
|
234
|
+
* siblings and cached on the replacement object.
|
|
235
|
+
* @param replacement - The replacement whose language dom node should be
|
|
236
|
+
* resolved.
|
|
237
|
+
* @returns The resolved language indicator dom node or null.
|
|
238
|
+
*/
|
|
239
|
+
_resolveCurrentLanguageDomNode(replacement: Replacement): HTMLItem;
|
|
240
|
+
/**
|
|
241
|
+
* Creates a backup node for the current dom node content before the
|
|
242
|
+
* replacement is applied. Returns either a comment node or an element
|
|
243
|
+
* node depending on `nodeName`.
|
|
244
|
+
* @param nodeName - Lowercase node name of the replacement node.
|
|
245
|
+
* @param currentLanguage - Current language string used as prefix.
|
|
246
|
+
* @param currentText - Text content of the node to back up.
|
|
247
|
+
* @param domNodeToTranslate - The dom node whose children are moved into
|
|
248
|
+
* the backup element (for non-comment nodes).
|
|
249
|
+
* @returns The created backup node.
|
|
250
|
+
*/
|
|
251
|
+
_createBackupNode(nodeName: string, currentLanguage: string, currentText: string, domNodeToTranslate: HTMLItem): Comment | HTMLElement;
|
|
252
|
+
/**
|
|
253
|
+
* Applies the actual text replacement to the target dom node. Moves
|
|
254
|
+
* child nodes from the replacement node or sets innerHTML/textContent
|
|
255
|
+
* directly depending on the node type.
|
|
256
|
+
* @param replacement - Replacement object containing source, target and
|
|
257
|
+
* replacement text information.
|
|
258
|
+
*/
|
|
259
|
+
_applyTextReplacement(replacement: Replacement): void;
|
|
260
|
+
/**
|
|
261
|
+
* Updates all dom nodes that have a known translation to their translated
|
|
262
|
+
* text content.
|
|
263
|
+
*/
|
|
264
|
+
_updateKnownTextNodes(): void;
|
|
182
265
|
/**
|
|
183
266
|
* Switches the current language indicator in language switch triggered dom
|
|
184
267
|
* nodes.
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";if("undefined"!=typeof module&&null!==module&&"undefined"!==eval("typeof require")&&null!==eval("require")&&"main"in eval("require")&&"undefined"!==eval("typeof require.main")&&null!==eval("require.main")){var ORIGINAL_MAIN_MODULE=module;module!==eval("require.main")&&"paths"in module&&"paths"in eval("require.main")&&"undefined"!=typeof __dirname&&null!==__dirname&&(module.paths=eval("require.main.paths").concat(module.paths.filter((function(path){return eval("require.main.paths").includes(path)}))))}if(null==window)var window="undefined"==typeof global||null===global?{}:global;!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("@babel/runtime/helpers/initializerDefineProperty"),require("@babel/runtime/helpers/applyDecoratedDescriptor"),require("@babel/runtime/helpers/initializerWarningHelper"),require("clientnode"),require("clientnode/property-types"),require("web-component-wrapper/decorator"),require("web-component-wrapper/Web"));else if("function"==typeof define&&define.amd)define(["@babel/runtime/helpers/initializerDefineProperty","@babel/runtime/helpers/applyDecoratedDescriptor","@babel/runtime/helpers/initializerWarningHelper","clientnode","clientnode/property-types","web-component-wrapper/decorator","web-component-wrapper/Web"],t);else{var n="object"==typeof exports?t(require("@babel/runtime/helpers/initializerDefineProperty"),require("@babel/runtime/helpers/applyDecoratedDescriptor"),require("@babel/runtime/helpers/initializerWarningHelper"),require("clientnode"),require("clientnode/property-types"),require("web-component-wrapper/decorator"),require("web-component-wrapper/Web")):t(e["@babel/runtime/helpers/initializerDefineProperty"],e["@babel/runtime/helpers/applyDecoratedDescriptor"],e["@babel/runtime/helpers/initializerWarningHelper"],e.clientnode,e["clientnode/property-types"],e["web-component-wrapper/decorator"],e["web-component-wrapper/Web"]);for(var o in n)("object"==typeof exports?exports:e)[o]=n[o]}}(this,((e,t,n,o,i,a,s)=>(()=>{var r=[,t=>{t.exports=e},e=>{e.exports=t},e=>{e.exports=n},e=>{e.exports=o},e=>{e.exports=i},e=>{e.exports=a},e=>{e.exports=s}],l={};function c(e){var t=l[e];if(void 0!==t)return t.exports;var n=l[e]={exports:{}};return r[e](n,n.exports,c),n.exports}c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},c.d=(e,t)=>{for(var n in t)c.o(t,n)&&!c.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var p={};c.r(p),c.d(p,{WebInternationalization:()=>E,api:()=>k,default:()=>q,log:()=>O});var u,h,d,g,m,f,b,w,N,x,T,y,L=c(1),_=c.n(L),D=c(2),C=c.n(D),v=(c(3),c(4)),P=c(5),A=c(6),S=c(7);const O=new v.Logger({name:"web-internationalization"});let E=(u=(0,A.property)({type:P.object}),h=(0,A.property)({type:P.func}),d=(0,A.property)({type:P.func}),g=(0,A.property)({type:P.func}),m=(0,A.property)({type:P.func}),y=class e extends S.Web{constructor(){super(),this.self=e,_()(this,"options",b,this),_()(this,"onEnsure",w,this),_()(this,"onSwitch",N,this),_()(this,"onEnsured",x,this),_()(this,"onSwitched",T,this),this.switchLanguageButtonDomNodes=null,this.currentLanguage="enUS",this.knownTranslations={},this.lock=new v.Lock,this._domNodesToFade=[],this._replacements=[],this._textNodesWithKnownTranslation={},this.defineGetterAndSetterInterface()}async onUpdateAttribute(e,t){await super.onUpdateAttribute(e,t),"options"===e&&this._extendOptions()}async render(e="unknown",t=!0){await super.render(e,!1),0===Object.keys(this.options).length&&this._extendOptions(),this.options.preReplacementLanguagePattern=(0,v.format)(this.options.preReplacementLanguagePattern,this.options.replacementLanguagePattern.substring(1,this.options.replacementLanguagePattern.length-1)),this.options.lockDescription=(0,v.format)(this.options.lockDescription,this.self._name),this.options.sessionDescription=(0,v.format)(this.options.sessionDescription,this.self._name),await this.waitForNestedComponentRendering(),this.switchLanguageButtonDomNodes=this.hostDomNode.querySelectorAll(`a[href^="#${this.options.languageHashPrefix}"]`),this._movePreReplacementNodes(),this.currentLanguage=this._normalizeLanguage(this.options.default);const n=this._determineUsefulLanguage(),o=0===this.options.selection.length;for(const e of this.switchLanguageButtonDomNodes){o&&this.options.selection.push(e.getAttribute("href").substring(`#${this.options.languageHashPrefix}`.length));const t=e=>{e.preventDefault();const t=e.target?.getAttribute("href");t&&this.switch(t.substring(this.options.languageHashPrefix.length+1))};this.addSecureEventListener(e,"click",t)}this.currentLanguage===n?this._switchCurrentLanguageIndicator(n):await this.switch(n,!0),await this.resolveRenderingPromiseIfSet(e,t)}async switch(e,t=!1){if(!0===e||!this.options.selection.length||this.options.selection.includes(e)){if(await this.lock.acquire(this.options.lockDescription),!0===e?(t=!0,e=this.currentLanguage):e=this._normalizeLanguage(e),t&&e!==this.options.default||this.currentLanguage!==e){let n="Switch to";return t&&(n="Ensure"),O.debug(`${n} "${e}".`),this._switchCurrentLanguageIndicator(e),t?await this.onEnsure(e):await this.onSwitch(this.currentLanguage,e),this._domNodesToFade=[],this._replacements=[],this._collectTextNodesToReplace(e,t),void await this._handleSwitchEffect(e,t)}O.debug(`"${e}" is already current selected language.`),this.lock.release(this.options.lockDescription)}else O.debug(`"${e}" isn't one of the allowed languages.`)}refresh(){return this._movePreReplacementNodes(),this.switch(!0)}_extendOptions(){this.setPropertyValue("options",(0,v.extend)(!0,{},this.self._defaultOptions,this.options))}async _handleSwitchEffect(e,t){const n=this.currentLanguage;if(!t&&this.options.useEffect&&this._domNodesToFade.length>0)return await Promise.all(this._domNodesToFade.map((e=>{const t=(0,v.fadeOut)(e);return t.then((()=>{t.resetStyles()}))}))),this._switchLanguage(e),await Promise.all(this._domNodesToFade.map((e=>{const t=(0,v.fadeIn)(e);return t.then((()=>{t.resetStyles()}))}))),this.onSwitched(n,e),void this.lock.release(this.options.lockDescription);this._switchLanguage(e),t?this.onEnsured(e):this.onSwitched(n,e),this.lock.release(this.options.lockDescription)}_movePreReplacementNodes(){for(const e of(0,v.getAll)(this.hostDomNode)){const t=e.nodeName.toLowerCase();if(this.options.replacementDomNodeNames.includes(t)){["#comment","#text"].includes(t)||e.classList.add(this.options.selectors.hideClassName);const n=new RegExp(this.options.preReplacementLanguagePattern),o=e.textContent?.match(n);if(e.textContent&&o&&o[0]&&(e.textContent=e.textContent.replace(n,o[1]),e.parentElement)){let t=!1;for(const n of(0,v.getAll)(e.parentElement)){if(t&&(0,v.getText)(n,!0).length>0){n.appendChild(e);break}e===n&&(t=!0)}}}}}_collectTextNodesToReplace(e,t){let n=null,o=null;this.knownTranslations={};for(const i of(0,v.getAll)(this.hostDomNode)){const a=i.nodeName.toLowerCase();if((0!==(0,v.getText)(i,!0).length||i.nodeType===Node.COMMENT_NODE&&""!==(i.nodeValue||"").trim())&&!n?.contains(i)&&!(0,v.closest)(i,this.options.replaceDomNodeNames.concat(this.options.replacementDomNodeNames).join(","),!0))if(this.options.replaceDomNodeNames.includes(a))n=i;else if(this.options.alternativeDomNodeNames.includes(a)&&i.getAttribute("lang")===e){let e=null;for(const t of i.parentElement.querySelectorAll(this.options.alternativeDomNodeNames.join(",")))if(t.hasAttribute("active")||!t.hasAttribute("lang")){e=t;break}if(!e)continue;if(e.hasAttribute("active")||e.setAttribute("active",""),!e.hasAttribute("lang")){let n=this.currentLanguage;t&&(n=this.options.default||this.currentLanguage),e.setAttribute("lang",n)}this._registerTextNodeToChange(e,i,i.innerHTML,o)}else if(n){if(this.options.replacementDomNodeNames.includes(a)){const s="#comment"===a?i.textContent:i.innerHTML,r=s?.match(new RegExp(this.options.replacementLanguagePattern));Array.isArray(r)&&r[1]===e?(this.knownTranslations[(0,v.getText)(n,!0).join(" ")]=r[2].trim(),o=this._ensureLastTextNodeHavingLanguageIndicator(n,o,t),this._registerTextNodeToChange(n,i,r[2],o),n=null,o=null):i.textContent?.match(new RegExp(this.options.currentLanguagePattern))&&(o=i);continue}n=null,o=null}}this._registerKnownTextNodes()}_registerKnownTextNodes(){this._textNodesWithKnownTranslation={};for(const e of this.hostDomNode.querySelectorAll(this.options.selectors.knownTranslation))for(const t of(0,v.getAll)(e)){const e=(0,v.getText)(t).join(" ");e&&!this.options.replaceDomNodeNames.includes(t.nodeName.toLowerCase())&&!(0,v.closest)(t,this.options.replaceDomNodeNames.join(","),!0)&&Object.prototype.hasOwnProperty.call(this.knownTranslations,e)&&(this._domNodesToFade.push(t.parentElement),Object.prototype.hasOwnProperty.call(this._textNodesWithKnownTranslation,this.knownTranslations[e])?this._textNodesWithKnownTranslation[this.knownTranslations[e]].push(t):this._textNodesWithKnownTranslation[this.knownTranslations[e]]=[t])}}_normalizeLanguage(e){for(const[t,n]of Object.entries(this.options.languageMapping))if(n.includes(t.toLowerCase())||n.push(t.toLowerCase()),n.includes(e.toLowerCase()))return t;return this.options.default}_determineUsefulLanguage(){let e;return this.options.initial?e=this.options.initial:Object.prototype.hasOwnProperty.call(v.globalContext,"window")&&(v.globalContext.window?.localStorage.getItem(this.options.sessionDescription)?(e=v.globalContext.window.localStorage.getItem(this.options.sessionDescription),O.debug(`Determine "${e}", because of local storage`,"information.")):v.globalContext.window?.navigator.language&&(e=v.globalContext.window.navigator.language,O.debug(`Determine "${e}", because of browser settings.`))),e||(e=this.options.default,O.debug(`Determine "${e}", because of default option.`)),e=this._normalizeLanguage(e),this.options.selection.length&&!this.options.selection.includes(e)&&(O.debug(`"${e}" isn't one of the allowed languages. Set`,`language to "${this.options.selection[0]}".`),e=this.options.selection[0]),v.globalContext.window?.localStorage&&v.globalContext.window.localStorage.setItem(this.options.sessionDescription,e),e}_registerTextNodeToChange(e,t,n,o){this._domNodesToFade.push(e.parentElement),t&&this._replacements.push({textNodeToTranslate:e,nodeToReplaceWith:t,textToReplaceWith:n,currentLanguageDomNode:o})}_ensureLastTextNodeHavingLanguageIndicator(e,t,n){if(e&&!t){let o=this.currentLanguage;n&&(o=this.options.default||this.currentLanguage),(t=v.globalContext.document?.createComment(o)||null)&&e.after(t)}return t}_switchLanguage(e){for(const t of this._replacements){const n="innerHTML"in t.textNodeToTranslate?t.textNodeToTranslate.innerHTML:t.textNodeToTranslate.textContent,o=n.trim();if(!this.options.templateDelimiter||!o.endsWith(this.options.templateDelimiter.post)&&this.options.templateDelimiter.post){let o=t.currentLanguageDomNode;if(!o){o=document.body;let e=!1;for(const n of(0,v.getAll)(t.textNodeToTranslate.parentElement)){if(e){t.currentLanguageDomNode=o=n;break}n===t.textNodeToTranslate&&(e=!0)}}const i=o.textContent;i&&e===i&&O.warn(`Text node "${t.textToReplaceWith}" is`,`marked as "${i}" and has same`,"translation language as it already is.");const a=t.nodeToReplaceWith.nodeName.toLowerCase();let s;if(this.options.alternativeDomNodeNames.includes(a)){t.nodeToReplaceWith.setAttribute("active",""),t.textNodeToTranslate.removeAttribute("active");continue}if("#comment"===a)s=v.globalContext.document.createComment(`${i}:${n}`);else{s=v.globalContext.document.createElement(a),s.appendChild(v.globalContext.document.createTextNode(`${i}:`)),s.classList.add(this.options.selectors.hideClassName);for(const e of Array.from(t.textNodeToTranslate.childNodes))s.appendChild(e)}if(t.textNodeToTranslate.after(s),t.textNodeToTranslate.after(v.globalContext.document.createComment(e)),"innerHTML"in t.textNodeToTranslate)if("#comment"===t.nodeToReplaceWith.nodeName.toLowerCase())t.textNodeToTranslate.innerHTML=t.textToReplaceWith;else{let e=!1;for(const n of Array.from(t.nodeToReplaceWith.childNodes))e||(n.textContent=n.textContent.replace(/^[a-z]{2}[A-Z]{2}:/,""),e=!0),t.textNodeToTranslate.appendChild(n)}else t.textNodeToTranslate.textContent=t.textToReplaceWith;o.remove(),t.nodeToReplaceWith.remove()}}for(const[e,t]of Object.entries(this._textNodesWithKnownTranslation))for(const n of t)n.textContent=e;v.globalContext.localStorage&&v.globalContext.localStorage.setItem(this.options.sessionDescription,e),this.currentLanguage=e}_switchCurrentLanguageIndicator(e){for(const e of this.hostDomNode.querySelectorAll(`a[href="#${this.options.languageHashPrefix}${this.currentLanguage}"].`+this.options.currentLanguageIndicatorClassName))e.classList.remove(this.options.currentLanguageIndicatorClassName);for(const t of this.hostDomNode.querySelectorAll(`a[href="#${this.options.languageHashPrefix}${e}"]`))t.classList.add(this.options.currentLanguageIndicatorClassName)}},y._name="WebInternationalization",y._defaultOptions={currentLanguageIndicatorClassName:"current",currentLanguagePattern:"^[a-z]{2}[A-Z]{2}$",default:"enUS",useEffect:!0,initial:null,languageHashPrefix:"lang-",languageMapping:{deDE:["de","de_de","de-de","german","deutsch"],enUS:["en","en_us","en-us"],enEN:["en_en","en-en","english"],frFR:["fr","fr_fr","fr-fr","french"]},lockDescription:"{1}Switch",preReplacementLanguagePattern:"^\\|({1})$",alternativeDomNodeNames:["lang-alternative"],replaceDomNodeNames:["#text","lang-replace"],replacementDomNodeNames:["#comment","lang-replacement"],replacementLanguagePattern:"^([a-z]{2}[A-Z]{2}):((.|\\s)*)$",selection:[],selectors:{knownTranslation:".web-internationalization-generated-content",hideClassName:"wi-hide"},sessionDescription:"{1}",templateDelimiter:{pre:"{{",post:"}}"}},f=y,b=C()(f.prototype,"options",[u],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return{}}}),w=C()(f.prototype,"onEnsure",[h],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return v.NOOP}}),N=C()(f.prototype,"onSwitch",[d],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return v.NOOP}}),x=C()(f.prototype,"onEnsured",[g],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return v.NOOP}}),T=C()(f.prototype,"onSwitched",[m],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return v.NOOP}}),f);const k={component:E,register:(e=(0,v.camelCaseToDelimited)(E._name))=>{customElements.define(e,E)}},q=E;return v.globalContext.AUTO_DEFINE_WEB_INTERNATIONALIZATION&&k.register(),p})()));
|
|
1
|
+
"use strict";if("undefined"!=typeof module&&null!==module&&"undefined"!==eval("typeof require")&&null!==eval("require")&&"main"in eval("require")&&"undefined"!==eval("typeof require.main")&&null!==eval("require.main")){var ORIGINAL_MAIN_MODULE=module;module!==eval("require.main")&&"paths"in module&&"paths"in eval("require.main")&&"undefined"!=typeof __dirname&&null!==__dirname&&(module.paths=eval("require.main.paths").concat(module.paths.filter((function(path){return eval("require.main.paths").includes(path)}))))}if(null==window)var window="undefined"==typeof global||null===global?{}:global;!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("@babel/runtime/helpers/initializerDefineProperty"),require("@babel/runtime/helpers/applyDecoratedDescriptor"),require("@babel/runtime/helpers/initializerWarningHelper"),require("clientnode"),require("clientnode/property-types"),require("web-component-wrapper/decorator"),require("web-component-wrapper/Web"));else if("function"==typeof define&&define.amd)define(["@babel/runtime/helpers/initializerDefineProperty","@babel/runtime/helpers/applyDecoratedDescriptor","@babel/runtime/helpers/initializerWarningHelper","clientnode","clientnode/property-types","web-component-wrapper/decorator","web-component-wrapper/Web"],t);else{var o="object"==typeof exports?t(require("@babel/runtime/helpers/initializerDefineProperty"),require("@babel/runtime/helpers/applyDecoratedDescriptor"),require("@babel/runtime/helpers/initializerWarningHelper"),require("clientnode"),require("clientnode/property-types"),require("web-component-wrapper/decorator"),require("web-component-wrapper/Web")):t(e["@babel/runtime/helpers/initializerDefineProperty"],e["@babel/runtime/helpers/applyDecoratedDescriptor"],e["@babel/runtime/helpers/initializerWarningHelper"],e.clientnode,e["clientnode/property-types"],e["web-component-wrapper/decorator"],e["web-component-wrapper/Web"]);for(var n in o)("object"==typeof exports?exports:e)[n]=o[n]}}(this,((e,t,o,n,i,a,r)=>(()=>{var s=[,t=>{t.exports=e},e=>{e.exports=t},e=>{e.exports=o},e=>{e.exports=n},e=>{e.exports=i},e=>{e.exports=a},e=>{e.exports=r}],l={};function c(e){var t=l[e];if(void 0!==t)return t.exports;var o=l[e]={exports:{}};return s[e](o,o.exports,c),o.exports}c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},c.d=(e,t)=>{for(var o in t)c.o(t,o)&&!c.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var p={};c.r(p),c.d(p,{WebInternationalization:()=>k,api:()=>E,default:()=>R,log:()=>O});var u,d,h,m,g,f,N,b,w,T,_,x,D=c(1),y=c.n(D),L=c(2),C=c.n(L),v=(c(3),c(4)),A=c(5),P=c(6),S=c(7);const O=new v.Logger({name:"web-internationalization"});let k=(u=(0,P.property)({type:A.object}),d=(0,P.property)({type:A.func}),h=(0,P.property)({type:A.func}),m=(0,P.property)({type:A.func}),g=(0,P.property)({type:A.func}),x=class e extends S.Web{constructor(){super(),this.self=e,y()(this,"options",N,this),y()(this,"onEnsure",b,this),y()(this,"onSwitch",w,this),y()(this,"onEnsured",T,this),y()(this,"onSwitched",_,this),this.switchLanguageButtonDomNodes=null,this.currentLanguage="enUS",this.knownTranslations={},this.lock=new v.Lock,this._domNodesToFade=[],this._replacements=[],this._domNodesWithKnownTranslation={},this.defineGetterAndSetterInterface()}async onUpdateAttribute(e,t){await super.onUpdateAttribute(e,t),"options"===e&&this._extendOptions()}async render(e="unknown",t=!0){await super.render(e,!1),0===Object.keys(this.options).length&&this._extendOptions(),this.options.preReplacementLanguagePattern=(0,v.format)(this.options.preReplacementLanguagePattern,this.options.replacementLanguagePattern.substring(1,this.options.replacementLanguagePattern.length-1)),this.options.lockDescription=(0,v.format)(this.options.lockDescription,this.self._name),this.options.sessionDescription=(0,v.format)(this.options.sessionDescription,this.self._name),await this.waitForNestedComponentRendering(),this.switchLanguageButtonDomNodes=this.hostDomNode.querySelectorAll(`a[href^="#${this.options.languageHashPrefix}"]`),this._movePreReplacementNodes(),this.currentLanguage=this._normalizeLanguage(this.options.default);const o=this._determineUsefulLanguage(),n=0===this.options.selection.length;for(const e of this.switchLanguageButtonDomNodes){n&&this.options.selection.push(e.getAttribute("href").substring(`#${this.options.languageHashPrefix}`.length));const t=e=>{e.preventDefault();const t=e.target?.getAttribute("href");t&&this.switch(t.substring(this.options.languageHashPrefix.length+1))};this.addSecureEventListener(e,"click",t)}this.currentLanguage===o?await this.refresh():await this.switch(o,!0),await this.resolveRenderingPromiseIfSet(e,t)}async switch(e,t=!1){if(!0===e||!this.options.selection.length||this.options.selection.includes(e)){if(await this.lock.acquire(this.options.lockDescription),!0===e?(t=!0,e=this.currentLanguage):e=this._normalizeLanguage(e),t||this.currentLanguage!==e){let o="Switch to";return t&&(o="Ensure"),O.debug(`${o} "${e}".`),this._switchCurrentLanguageIndicator(e),t?await this.onEnsure(e):await this.onSwitch(this.currentLanguage,e),this._domNodesToFade=[],this._replacements=[],this._collectDomNodesToReplace(e,t),void await this._handleSwitchEffect(e,t)}O.debug(`"${e}" is already current selected language.`),this.lock.release(this.options.lockDescription)}else O.debug(`"${e}" isn't one of the allowed languages.`)}refresh(){return this._movePreReplacementNodes(),this.switch(!0)}_extendOptions(){this.setPropertyValue("options",(0,v.extend)(!0,{},this.self._defaultOptions,this.options))}async _handleSwitchEffect(e,t){const o=this.currentLanguage;if(!t&&this.options.useEffect&&this._domNodesToFade.length>0)return await Promise.all(this._domNodesToFade.map((e=>{const t=(0,v.fadeOut)(e);return t.then((()=>{t.resetStyles()}))}))),this._switchLanguage(e),await Promise.all(this._domNodesToFade.map((e=>{const t=(0,v.fadeIn)(e);return t.then((()=>{t.resetStyles()}))}))),this.onSwitched(o,e),void this.lock.release(this.options.lockDescription);this._switchLanguage(e),t?this.onEnsured(e):this.onSwitched(o,e),this.lock.release(this.options.lockDescription)}_movePreReplacementNodes(){for(const e of(0,v.getAll)(this.hostDomNode)){const t=e.nodeName.toLowerCase();if(this.options.replacementDomNodeNames.includes(t)){["#comment","#text"].includes(t)||e.classList.add(this.options.selectors.hideClassName);const o=new RegExp(this.options.preReplacementLanguagePattern),n=e.textContent?.match(o);if(e.textContent&&n&&n[0]&&(e.textContent=e.textContent.replace(o,n[1]),e.parentElement)){let t=!1;for(const o of(0,v.getAll)(e.parentElement)){if(t&&(0,v.getText)(o,!0).length>0){o.appendChild(e);break}e===o&&(t=!0)}}}}}_collectDomNodesToReplace(e,t){let o=null,n=null;this.knownTranslations={};for(const i of(0,v.getAll)(this.hostDomNode)){const a=i.nodeName.toLowerCase(),r=(0,v.getText)(i,!0);if(!this._shouldSkipDomNode(i,r,o))if(this.options.replaceDomNodeNames.includes(a))o=i;else if(this.options.alternativeDomNodeNames.includes(a))i.hasAttribute("lang")?i.getAttribute("lang")===e&&this._processAlternativeDomNode(i,e,t,n):this._initializeCurrentLanguageDomNode(i,t);else if(o){if(this.options.replacementDomNodeNames.includes(a)){({domNodeToTranslate:o,languageDomNode:n}=this._processReplacementDomNode(i,a,e,t,o,n));continue}o=null,n=null}}this._registerKnownTextNodes()}_shouldSkipDomNode(e,t,o){return 0===t.length&&(e.nodeType!==Node.COMMENT_NODE||""===(e.nodeValue||"").trim())||Boolean(o?.contains(e))||Boolean((0,v.closest)(e,this.options.replaceDomNodeNames.concat(this.options.replacementDomNodeNames).join(","),!0))}_processAlternativeDomNode(e,t,o,n){let i=null;for(const t of e.parentElement.querySelectorAll(this.options.alternativeDomNodeNames.join(",")))if(t.hasAttribute("active")||!t.hasAttribute("lang")){i=t;break}i&&(this._initializeCurrentLanguageDomNode(i,o),this._registerTextNodeToChange(i,e,e.innerHTML,n))}_initializeCurrentLanguageDomNode(e,t){e.hasAttribute("active")||e.setAttribute("active",""),e.hasAttribute("lang")||e.setAttribute("lang",t&&this.options.default||this.currentLanguage)}_processReplacementDomNode(e,t,o,n,i,a){const r=("#comment"===t?e.textContent:e.innerHTML).match(new RegExp(this.options.replacementLanguagePattern));return Array.isArray(r)&&r[1]===o?(this.knownTranslations[(0,v.getText)(i,!0).join(" ")]=r[2].trim(),a=this._ensureLastTextNodeHavingLanguageIndicator(i,a,n),this._registerTextNodeToChange(i,e,r[2],a),{domNodeToTranslate:null,languageDomNode:null}):(e.textContent.match(new RegExp(this.options.currentLanguagePattern))&&(a=e),{domNodeToTranslate:i,languageDomNode:a})}_registerKnownTextNodes(){this._domNodesWithKnownTranslation={};for(const e of this.hostDomNode.querySelectorAll(this.options.selectors.knownTranslation))for(const t of(0,v.getAll)(e)){const e=(0,v.getText)(t).join(" ");e&&!this.options.replaceDomNodeNames.includes(t.nodeName.toLowerCase())&&!(0,v.closest)(t,this.options.replaceDomNodeNames.join(","),!0)&&Object.prototype.hasOwnProperty.call(this.knownTranslations,e)&&(this._domNodesToFade.push(t.parentElement),Object.prototype.hasOwnProperty.call(this._domNodesWithKnownTranslation,this.knownTranslations[e])?this._domNodesWithKnownTranslation[this.knownTranslations[e]].push(t):this._domNodesWithKnownTranslation[this.knownTranslations[e]]=[t])}}_normalizeLanguage(e){for(const[t,o]of Object.entries(this.options.languageMapping))if(o.includes(t.toLowerCase())||o.push(t.toLowerCase()),o.includes(e.toLowerCase()))return t;return this.options.default}_determineUsefulLanguage(){let e;return this.options.initial?e=this.options.initial:Object.prototype.hasOwnProperty.call(v.globalContext,"window")&&(v.globalContext.window?.localStorage.getItem(this.options.sessionDescription)?(e=v.globalContext.window.localStorage.getItem(this.options.sessionDescription),O.debug(`Determine "${e}", because of local storage`,"information.")):v.globalContext.window?.navigator.language&&(e=v.globalContext.window.navigator.language,O.debug(`Determine "${e}", because of browser settings.`))),e||(e=this.options.default,O.debug(`Determine "${e}", because of default option.`)),e=this._normalizeLanguage(e),this.options.selection.length&&!this.options.selection.includes(e)&&(O.debug(`"${e}" isn't one of the allowed languages. Set`,`language to "${this.options.selection[0]}".`),e=this.options.selection[0]),v.globalContext.window?.localStorage&&v.globalContext.window.localStorage.setItem(this.options.sessionDescription,e),e}_registerTextNodeToChange(e,t,o,n){this._domNodesToFade.push(e.parentElement),t&&this._replacements.push({domNodeToTranslate:e,domNodeToReplaceWith:t,textToReplaceWith:o,currentLanguageDomNode:n})}_ensureLastTextNodeHavingLanguageIndicator(e,t,o){if(e&&!t){let n=this.currentLanguage;o&&(n=this.options.default||this.currentLanguage),(t=v.globalContext.document?.createComment(n)||null)&&e.after(t)}return t}_switchLanguage(e){for(const t of this._replacements){const o=this._getCurrentNodeText(t.domNodeToTranslate),n=o.trim();if(!this.options.templateDelimiter||!n.endsWith(this.options.templateDelimiter.post)&&this.options.templateDelimiter.post){const n=this._resolveCurrentLanguageDomNode(t),i=n.textContent;i&&e===i&&O.warn(`Text node "${t.textToReplaceWith}" is`,`marked as "${i}" and has same`,"translation language as it already is.");const a=t.domNodeToReplaceWith.nodeName.toLowerCase();if(this.options.alternativeDomNodeNames.includes(a)){t.domNodeToReplaceWith.setAttribute("active",""),t.domNodeToTranslate.removeAttribute("active");continue}const r=this._createBackupNode(a,i,o,t.domNodeToTranslate);t.domNodeToTranslate.after(r),t.domNodeToTranslate.after(v.globalContext.document.createComment(e)),this._applyTextReplacement(t),n.remove(),t.domNodeToReplaceWith.remove()}}this._updateKnownTextNodes(),v.globalContext.localStorage&&v.globalContext.localStorage.setItem(this.options.sessionDescription,e),this.currentLanguage=e}_getCurrentNodeText(e){return"innerHTML"in e?e.innerHTML:e.textContent}_resolveCurrentLanguageDomNode(e){if(e.currentLanguageDomNode)return e.currentLanguageDomNode;let t=document.body,o=!1;for(const n of(0,v.getAll)(e.domNodeToTranslate.parentElement)){if(o){e.currentLanguageDomNode=t=n;break}n===e.domNodeToTranslate&&(o=!0)}return t}_createBackupNode(e,t,o,n){if("#comment"===e)return v.globalContext.document.createComment(`${t}:${o}`);const i=v.globalContext.document.createElement(e);i.appendChild(v.globalContext.document.createTextNode(`${t}:`)),i.classList.add(this.options.selectors.hideClassName);for(const e of Array.from(n.childNodes))i.appendChild(e);return i}_applyTextReplacement(e){if("innerHTML"in e.domNodeToTranslate)if("#comment"===e.domNodeToReplaceWith.nodeName.toLowerCase())e.domNodeToTranslate.innerHTML=e.textToReplaceWith;else{let t=!1;for(const o of Array.from(e.domNodeToReplaceWith.childNodes))t||(o.textContent=o.textContent.replace(/^[a-z]{2}[A-Z]{2}:/,""),t=!0),e.domNodeToTranslate.appendChild(o)}else e.domNodeToTranslate.textContent=e.textToReplaceWith}_updateKnownTextNodes(){for(const[e,t]of Object.entries(this._domNodesWithKnownTranslation))for(const o of t)o.textContent=e}_switchCurrentLanguageIndicator(e){for(const e of this.hostDomNode.querySelectorAll(`a[href="#${this.options.languageHashPrefix}${this.currentLanguage}"].`+this.options.currentLanguageIndicatorClassName))e.classList.remove(this.options.currentLanguageIndicatorClassName);for(const t of this.hostDomNode.querySelectorAll(`a[href="#${this.options.languageHashPrefix}${e}"]`))t.classList.add(this.options.currentLanguageIndicatorClassName)}},x._name="WebInternationalization",x._defaultOptions={currentLanguageIndicatorClassName:"current",currentLanguagePattern:"^[a-z]{2}[A-Z]{2}$",default:"enUS",useEffect:!0,initial:null,languageHashPrefix:"lang-",languageMapping:{deDE:["de","de_de","de-de","german","deutsch"],enUS:["en","en_us","en-us"],enEN:["en_en","en-en","english"],frFR:["fr","fr_fr","fr-fr","french"]},lockDescription:"{1}Switch",preReplacementLanguagePattern:"^\\|({1})$",alternativeDomNodeNames:["lang-alternative"],replaceDomNodeNames:["#text","lang-replace"],replacementDomNodeNames:["#comment","lang-replacement"],replacementLanguagePattern:"^([a-z]{2}[A-Z]{2}):((.|\\s)*)$",selection:[],selectors:{knownTranslation:".web-internationalization-generated-content",hideClassName:"wi-hide"},sessionDescription:"{1}",templateDelimiter:{pre:"{{",post:"}}"}},f=x,N=C()(f.prototype,"options",[u],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return{}}}),b=C()(f.prototype,"onEnsure",[d],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return v.NOOP}}),w=C()(f.prototype,"onSwitch",[h],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return v.NOOP}}),T=C()(f.prototype,"onEnsured",[m],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return v.NOOP}}),_=C()(f.prototype,"onSwitched",[g],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return v.NOOP}}),f);const E={component:k,register:(e=(0,v.camelCaseToDelimited)(k._name))=>{customElements.define(e,k)}},R=k;return v.globalContext.AUTO_DEFINE_WEB_INTERNATIONALIZATION&&E.register(),p})()));
|
package/package.json
CHANGED
package/type.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { HTMLItem, Mapping } from 'clientnode';
|
|
2
2
|
export interface Replacement {
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
domNodeToTranslate: HTMLItem;
|
|
4
|
+
domNodeToReplaceWith: HTMLItem;
|
|
5
5
|
textToReplaceWith: string;
|
|
6
6
|
currentLanguageDomNode: HTMLItem | null;
|
|
7
7
|
}
|