UNPKG

@pap-it/tools-translator

Version:
5 lines (4 loc) 2.35 kB
"use strict";import{__decorate as o}from"tslib";import{ExtractSlotValue as h,CustomElement as l,html as c,property as p}from"@pap-it/system-utils";import{style as u}from"./style";import{init as d}from"./translator";export class Translator extends l{get Text(){return this.text}get Key(){return this.key}set Key(t){typeof t=="string"?this.key=t:this.key="",this.updateText()}constructor(){super(),this.dynamicAttributes=new Set,this.noupdate=!1,this.internalset=!1,this.mutantobservercallback=(t,e)=>{if(this.internalset){this.internalset=!1;return}for(const s of t)s.type==="attributes"&&s.attributeName&&this.dynamicAttributes.has(s.attributeName)&&(this.internalset=!0,this.updateText())},this.handletranslateslotchange=t=>{if(t.target instanceof HTMLSlotElement){const e=h(t.target).join(" ").trim();this.Key=e}},this.onscopeupdate=()=>{this.updateText()},this.updateText=()=>{const t=(this.scope?this.scope+".":"")+this.key;let e=window.papLocalization?.current?.translations?.[t]||this.key;if(e===void 0&&this.key===void 0)return;const s=/{([^{}]+)}/g,a=e.match(s);a&&a.forEach(n=>{const i=n.slice(1,-1),r=this.getAttribute(i);r&&(e=e.replace(n,r),this.dynamicAttributes.has(i)||this.dynamicAttributes.add(i))}),this.text=e,this.spanElement?this.spanElement.innerText=e:this.noupdate||this.requestUpdate(),this.internalset=!1,this.noupdate=!1},this.observer=new MutationObserver(this.mutantobservercallback),this.observer.observe(this,{attributes:!0})}connectedCallback(){super.connectedCallback(),d(),window.papLocalization?.subscribe(this.updateText)}disconnectedCallback(){super.disconnectedCallback(),window.papLocalization?.unsubscribe(this.updateText)}attributeChangedCallback(t,e,s){super.attributeChangedCallback(t,e,s),this.dynamicAttributes.has(t)&&this.updateText()}firstRender(){if(super.firstRender(),this.shadowRoot){const t=this.shadowRoot.querySelector("span.pap-translation-span");t&&(this.spanElement=t)}}translateKey(t,e){if(e)for(let s in e)this.setAttribute(s,e[s]),this.dynamicAttributes.add(s);return this.key!==t&&(this.noupdate=!0,this.Key=t),this.text}render(){return c` <span class="pap-translation-span"></span> <slot style="display:none;" @slotchange="${this.handletranslateslotchange}"></slot> `}}Translator.style=u,o([p({rerender:!1,onUpdate:"onscopeupdate"})],Translator.prototype,"scope",void 0);