import{t}from"./core/translates.js";import{el}from"./core/el.js";const _t=(key,lang=navigator.language)=>t[lang]?t[lang][key]||"-":t.en[key],allTags=[{tag:"h1"},{tag:"h2"},{tag:"h3"},{tag:"h4"},{tag:"h5"},{tag:"h6"},{tag:"span"},{tag:"mark"},{tag:"small"},{tag:"dfn"},{tag:"a"},{tag:"q"},{tag:"b"},{tag:"i"},{tag:"u"},{tag:"s"},{tag:"sup"},{tag:"sub"},{tag:"kbd"},{tag:"abbr"},{tag:"strong"},{tag:"code"},{tag:"samp"},{tag:"del"},{tag:"ins"},{tag:"var"},{tag:"ul"},{tag:"ol"},{tag:"pre"},{tag:"time"},{tag:"img"},{tag:"audio"},{tag:"video"},{tag:"blockquote"},{tag:"details"}];class WCWYSIWYG extends HTMLElement{EditorTags;EditorCustomTags;EditorNode;EditorActionsSection;EditorCustomTagsForm;EditorInlineActions;EditorPropertyForm;EditorClearFormatBtn;EditorAutoCompleteForm;EditorBottomForm;EditorBottomFormNewP;EditorBottomFormViewToggle;EditorPreviewText;EditorTagsMethods;EditorAllowTags;EditorFullScreenButton;lang="ru";value="";static observedAttributes=["value"];#EditProps;#Autocomplete;#Extensions;#SotrageKey;#HideBottomActions;#Connected=!1;constructor(){super(),this.#checkExtensions(),this.classList.add("wc-wysiwyg"),this.onpointerup=()=>{const editorSelection=this.getSelection();null!==editorSelection.selection&&null!==editorSelection.selection.text&&this.EditorPropertyForm&&(this.EditorPropertyForm.style.display="none")},this.onfullscreenchange=()=>{const isFullScreen=document.fullscreenElement;this.classList.toggle("-fullscreen",null!==isFullScreen)}}connectedCallback(){if(!1===this.#Connected){const asyncExtensions=this.getAttribute("data-async-extensions")||!1;if(!1!==asyncExtensions){const asyncExtensionsPaths=asyncExtensions.split(",");asyncExtensionsPaths.forEach(extensionPath=>{import(extensionPath).then(esm=>{const Extension=new esm.default(this);"function"==typeof Extension.connectedCallback&&Extension.connectedCallback(),this.#Extensions instanceof Array?this.#Extensions.push(Extension):this.#Extensions=[Extension]})})}const allowTags=this.getAttribute("data-allow-tags")||allTags.map(t=>t.tag).join(",");if(this.EditorPreviewText=this.querySelector("textarea"),this.EditorPreviewText.className="wc-wysiwyg_pr -display-none",this.EditorPreviewText.oninput=event=>{const target=event.target;this.EditorNode.innerHTML=target.value,this.value=target.value},this.EditorAllowTags=allowTags.split(","),this.EditorTags=allTags.filter(tag=>allowTags.includes(tag.tag)),this.#EditProps=null!==this.getAttribute("data-edit-props")&&JSON.parse(this.getAttribute("data-edit-props")||""),this.#Autocomplete="1"===this.getAttribute("data-autocomplete"),this.#HideBottomActions="1"===this.getAttribute("data-hide-bottom-actions"),this.EditorInlineActions=this.EditorTags.filter(action=>!1===["video","audio","img"].includes(action.tag)),this.EditorClearFormatBtn=el("button",{classList:["wc-wysiwyg_btn","-clear"],attrs:{"data-hint":_t("clearFormat")},props:{innerHTML:"\u023E"}}),this.EditorActionsSection=el("section",{classList:["wc-wysiwyg_ec"]}),this.#makeActionButtons(this.EditorActionsSection,this.EditorTags),this.EditorActionsSection.append(this.EditorClearFormatBtn),this.#EditProps&&(this.EditorPropertyForm=el("form",{styles:{display:"none"},classList:["wc-wysiwyg_pf"],props:{onsubmit:event=>{event.preventDefault(),this.EditorPropertyForm.style.display="none"},onpointerup:event=>event.stopPropagation()}}),this.EditorActionsSection.append(this.EditorPropertyForm)),this.#Autocomplete&&(this.EditorAutoCompleteForm=el("form",{classList:["wc-wysiwyg_au"],props:{onsubmit:submitEvent=>{submitEvent.preventDefault(),submitEvent.stopPropagation();const tagName=submitEvent.submitter.value,newEl=el(tagName,{props:{innerHTML:tagName}});submitEvent.target.parentElement.replaceWith(newEl),newEl.focus()}}})),this.EditorBottomForm=el("fieldset",{classList:["wc-wysiwyg_bt"]}),this.EditorCustomTags=JSON.parse(this.getAttribute("data-custom-tags")+""),null!==this.EditorCustomTags&&(this.EditorCustomTagsForm=el("fieldset",{classList:["wc-wysiwyg_ce"]}),this.#makeActionButtons(this.EditorCustomTagsForm,this.EditorCustomTags),this.EditorActionsSection.prepend(this.EditorCustomTagsForm)),this.EditorNode=el("article",{classList:["wc-wysiwyg_content",this.getAttribute("data-content-class")||""],props:{contentEditable:!0,onpointerup:event=>{this.#checkCanClearElement(event),this.#EditProps&&this.#checkEditProps(event)},oninput:()=>{this.updateContent(),this.#Autocomplete&&this.#checkAutoComplete()},onkeydown:event=>{this.#checkKeyBindings(event)},onpaste:()=>{}}}),this.append(this.EditorActionsSection,this.EditorNode),!1===this.#HideBottomActions&&(this.EditorBottomFormViewToggle=el("button",{classList:["wc-wysiwyg_btn"],attrs:{"data-hint":_t("toggleViewMode"),"data-mode":"html5"},props:{type:"button",innerText:"\u0442\u0435\u043A\u0441\u0442/html5",onpointerup:()=>{let mode=this.EditorBottomFormViewToggle?.getAttribute("data-mode"),newMode="html5"===mode?"text":"html5";this.EditorBottomFormViewToggle?.setAttribute("data-mode",newMode),this.EditorNode.style.display="html5"===newMode?"":"none",this.EditorPreviewText.classList.toggle("-display-none","html5"===newMode),"text"===newMode&&(this.EditorPreviewText.value=this.EditorNode.innerHTML)}}}),this.EditorBottomFormNewP=el("button",{classList:["wc-wysiwyg_btn"],attrs:{"data-hint":_t("addNewParahraph")},props:{type:"button",innerText:"+ \u2761",onpointerup:()=>{const P=el("p",{props:{innerText:"/"}});this.EditorNode.appendChild(P),P.focus()}}}),this.EditorFullScreenButton=el("button",{classList:["wc-wysiwyg_btn"],attrs:{"data-hint":_t("fullScreen")},props:{type:"button",ariaRoleDescription:"button",innerText:"\uD83D\uDDA5\uFE0F",onpointerup:()=>{this.requestFullscreen()}}}),this.EditorBottomForm?.append(this.EditorBottomFormNewP,this.EditorBottomFormViewToggle,this.EditorFullScreenButton),this.append(this.EditorBottomForm)),this.EditorNode.innerHTML=this.EditorPreviewText.value,this.#SotrageKey=this.getAttribute("data-storage"),this.#SotrageKey){let storeValue=window.localStorage.getItem(this.#SotrageKey);storeValue&&(this.EditorNode.innerHTML=storeValue)}this.#Extensions instanceof Array&&this.#Extensions.forEach(extension=>"function"==typeof extension.connectedCallback&&extension.connectedCallback(this)),this.updateContent(),this.#Connected=!0}}updateContent(){this.value=this.EditorNode.innerHTML,this.EditorPreviewText.value=this.value,this.checkValidity(),this.dispatchEvent(new Event("oninput",{bubbles:!0,cancelable:!1})),this.updatePreviewEl(this.getAttribute("data-preview-el")),this.#SotrageKey&&window.localStorage.setItem(this.#SotrageKey,this.value)}updatePreviewEl(selector){if(selector){const previewEl=window.document.body.querySelector(selector);previewEl&&(previewEl.innerHTML=this.value)}}checkValidity(){let hasErros=!1,errors=[];null!==this.getAttribute("required")&&0===(this.EditorNode.textContent+"").length&&(hasErros=!0,errors.push(_t("required"))),+this.getAttribute("minlength")&&(this.EditorNode.textContent+"").length<+this.getAttribute("minlength")&&(hasErros=!0,errors.push(`${_t("minlength")} ${this.getAttribute("minlength")}`)),+this.getAttribute("maxlength")&&(this.EditorNode.textContent+"").length>+this.getAttribute("maxlength")&&(hasErros=!0,errors.push(`${_t("maxlength")} ${this.getAttribute("maxlength")}`));const filterTags=this.getAttribute("filtertags");if(null!==filterTags){const disallowTags=filterTags.split(",")||[];for(let i=0;i")},classList:["-errors"]});this.append(errosEl)}return!1==hasErros}#checkAutoComplete(){const editorSelection=this.getSelection();if(null!==editorSelection.selection&&null!==editorSelection.selection.anchorNode){const SelectionParentEl=editorSelection.selection.anchorNode.parentElement,AutoCompleteForm=this.EditorAutoCompleteForm;if(null!==SelectionParentEl&&null===editorSelection.text&&"P"===SelectionParentEl.nodeName&&SelectionParentEl.parentElement===this.EditorNode&&SelectionParentEl.innerText.startsWith("/")){const parsedTagName=SelectionParentEl.innerText.replace("/",""),filteredActions=this.EditorTags.filter(action=>action.tag.toLocaleLowerCase().startsWith(parsedTagName.toLocaleLowerCase()));0{AutoCompleteForm?.appendChild(el("button",{classList:["wc-wysiwyg_btn",`-${action.tag}`],attrs:{"data-hint":_t(action.tag)||null},props:{type:"submit",innerText:action.tag,value:action.tag}}))}),SelectionParentEl.appendChild(AutoCompleteForm)):(AutoCompleteForm.innerHTML="",AutoCompleteForm.parentElement&&AutoCompleteForm.parentElement.removeChild(AutoCompleteForm))}}}#checkCanClearElement(event){const eventTarget=event.target,clearBtn=this.EditorClearFormatBtn;eventTarget!==this.EditorNode&&("P"!==eventTarget.nodeName&&"SPAN"!==eventTarget.nodeName?(clearBtn.style.display="inline-block",clearBtn.innerHTML=`Ⱦ ${eventTarget.nodeName}`,clearBtn.onpointerup=()=>{eventTarget.replaceWith(document.createTextNode(eventTarget.textContent))}):(clearBtn.style.display="none",clearBtn.onpointerup=null))}#checkEditProps(event){const eventTarget=event.target;if(this.#EditProps[eventTarget.nodeName]){const props=this.#EditProps[eventTarget.nodeName];event.stopPropagation(),this.dispatchEvent(new CustomEvent("editprops",{detail:{eventTarget}})),this.EditorPropertyForm.style.display="",this.EditorPropertyForm.style.display="block",this.EditorPropertyForm.setAttribute("data-tag",eventTarget.nodeName),this.EditorPropertyForm.innerHTML="";for(let i=0;i{const eventInputTarget=eventInput.target;"class"===tagProp&&(eventTarget.className=eventInputTarget.value),(isAttr||"datetime"===tagProp)&&null!==eventInputTarget?eventTarget.setAttribute(tagProp,eventInputTarget.value):eventTarget[tagProp]=eventInputTarget.value,this.updateContent()}}})]}))}this.EditorPropertyForm.append(el("button",{classList:["wc-wysiwyg_btn"],props:{type:"submit",innerHTML:"↳"}}))}}#checkKeyBindings(event){if(event.altKey&&"Space"===event.code){const editorSelection=this.getSelection(),Selection=editorSelection.selection;if(null!==Selection&&"Caret"===Selection.type){const span=el("span");Selection.anchorNode?.parentElement?.insertAdjacentElement("afterend",span);const textN=document.createTextNode(" ");span.replaceWith(textN);const range=document.createRange();range.selectNodeContents(textN),Selection.removeAllRanges(),Selection.addRange(range)}}if("Enter"===event.code&&!1===event.shiftKey){const Selection=this.getSelection().selection;if(["LI","ARTICLE","P"].includes(Selection.anchorNode.parentElement.tagName))return!1;const p=el("p",{props:{innerHTML:` `}});Selection?.anchorNode?.parentElement?.insertAdjacentElement("afterend",p);const range=document.createRange();range.selectNodeContents(p),Selection?.removeAllRanges(),Selection?.addRange(range),event.stopPropagation(),event.preventDefault()}}#makeActionButtons(toEl,actions){for(let i=0;i{event.stopPropagation(),this.#tag(action)}},attrs:{"data-hint":action.hint?action.hint:_t(action.tag)||"-"}});toEl.appendChild(button)}}#tag=tag=>{switch(tag.tag){case"audio":this.#Media("audio");break;case"video":this.#Media("video");break;case"details":this.#Details();break;case"img":this.#Image();break;default:"function"==typeof tag.method?tag.method.apply(this,tag):this.#wrapTag(tag,tag.is)}};#Details(){const summaryTitle=prompt("Title","");if(""===summaryTitle)return!1;const mediaEl=el("details",{append:[el("summary",{props:{innerText:summaryTitle}}),el("p",{props:{innerText:"..."}})]});this.EditorNode.append(mediaEl),this.updateContent()}#wrapTag=(tag,is=!1)=>{const listTag=!!["ul","ol"].includes(tag.tag)&&tag.tag,newtag=!1===listTag?tag.tag:"li",Selection=this.getSelection().selection;let defaultOptions={};is&&(defaultOptions.options={is});let tagNode=el(newtag,defaultOptions);if(null!==Selection&&Selection.rangeCount){if(!1!==listTag){const list=el(listTag);tagNode.replaceWith(list),list.append(tagNode)}const range=Selection.getRangeAt(0).cloneRange();range.surroundContents(tagNode),Selection.removeAllRanges(),Selection.addRange(range),0===Selection.toString().length&&(tagNode.innerText=tag),this.updateContent(),this.#checkEditProps({target:tagNode,stopPropagation:()=>!1})}};#Media=tagName=>{const mediaSrc=prompt("src","");if(""===mediaSrc)return!1;const mediaEl=el(tagName,{attrs:{controls:!0},props:{src:mediaSrc}});this.EditorNode.append(mediaEl),this.updateContent()};#Image=()=>{const src=prompt("IMG URL"),caption=prompt("IMG caption"),img=new Image;if(src)img.src=src;else return alert("Invalid src");if(caption){const figure=el("figure",{append:[img,el("figcaption",{props:{textContent:caption}})]});img.setAttribute("alt",caption),this.EditorNode.appendChild(figure)}else this.EditorNode.appendChild(img)};#checkExtensions(){const _WCWYSIWYG=window._WCWYSIWYG;if(_WCWYSIWYG!==void 0&&0<_WCWYSIWYG.extensions.length){this.#Extensions=[];for(let i=0;i<_WCWYSIWYG.extensions.length;i++){const Extension=new _WCWYSIWYG.extensions[i](this);this.#Extensions.push(Extension)}}}getSelection(){const windowSelection=window.getSelection(),editorSelection={selection:null,element:null,text:null,node:null};if(null!==windowSelection){editorSelection.selection=windowSelection,editorSelection.node=windowSelection.anchorNode,editorSelection.element=windowSelection.anchorNode.parentElement;let selectionText=windowSelection.toString();0