UNPKG

wysiwyg4all

Version:

Free opensource minimal WYSIWYG editor for web developers

5 lines 47 kB
var N=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var I=Object.prototype.hasOwnProperty;var H=(p,e,t)=>e in p?N(p,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):p[e]=t;var P=(p,e)=>{for(var t in e)N(p,t,{get:e[t],enumerable:!0})},O=(p,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of M(e))!I.call(p,r)&&r!==t&&N(p,r,{get:()=>e[r],enumerable:!(n=A(e,r))||n.enumerable});return p};var B=p=>O(N({},"__esModule",{value:!0}),p);var m=(p,e,t)=>H(p,typeof e!="symbol"?e+"":e,t);var K={};P(K,{Wysiwyg4All:()=>x});module.exports=B(K);var S={h1:"_h1",h2:"_h2",h3:"_h3",h4:"_h4",h5:"_h5",h6:"_h6",small:"_small",bold:"_b",italic:"_i",underline:"_u",strike:"_del",color:"_color",backgroundColor:"_backgroundColor"},D={h1:["_small","_h2","_h3","_h4","_h5","_h6"],h2:["_small","_h1","_h3","_h4","_h5","_h6"],h3:["_small","_h1","_h2","_h4","_h5","_h6"],h4:["_small","_h1","_h2","_h3","_h5","_h6"],h5:["_small","_h1","_h2","_h3","_h4","_h6"],h6:["_small","_h1","_h2","_h3","_h4","_h5"],small:["_h1","_h2","_h3","_h4","_h5","_h6","_b"],bold:["_small"],underline:["_del"],strike:["_u"]},F=["_alignCenter_","_alignRight_"],w=["_h1","_h2","_h3","_h4","_h5","_h6","_small"],z=new Set(w),W=new Set(["P","LI","BLOCKQUOTE","UL","OL","HR","DIV"]),U=/(^|\s)(#[\p{L}\p{N}_-]{1,80})(?=\s)/gu,q=/(https?:\/\/[^\s]+|www\.[^\s]+)(?=\s)/gi;function j(p,e,t){return Math.max(e,Math.min(t,p))}function _(p,e){return typeof p=="number"?`${p}px`:typeof p=="string"&&p.trim()?p:e}function X(p){return p instanceof HTMLElement}function R(p){return p instanceof Node}function k(p){let e=Math.random().toString(36).slice(2,8),t=Date.now().toString().slice(-6);return`${p}_${t}${e}`}function T(p){let e=document.createElement("span");if(e.style.color="",e.style.color=p,!e.style.color)return null;document.body.appendChild(e);let t=getComputedStyle(e).color;e.remove();let n=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i);if(!n)return null;let[,r,s,o]=n;return`#${[r,s,o].map(l=>j(Number(l),0,255).toString(16).padStart(2,"0")).join("")}`}function $(p){let e=T(p)||"#0d9488";return{"--content":"#ffffff","--content-text":"#111827","--content-focus":e,"--focus":`${e}33`,"--placeholder":"#9ca3af"}}var x=class{constructor(e){m(this,"option");m(this,"element");m(this,"styleTagOfCommand");m(this,"customCommandHandlers",new Map);m(this,"eventBus",new Map);m(this,"imageInput");m(this,"observer",null);m(this,"range",null);m(this,"rangeBackup",null);m(this,"callback");m(this,"hashtagEnabled");m(this,"urlEnabled");m(this,"lastKey",null);m(this,"suspendSelectionCaptureForColorPicker",!1);m(this,"colorCommandDebounceTimer",null);m(this,"pendingColorCommand",null);m(this,"pendingColorSelectionSnapshot",null);m(this,"trackerUpdateInFlight",!1);m(this,"trackerUpdateQueued",!1);m(this,"livePickerColor",null);m(this,"livePickerBackgroundColor",null);m(this,"colorPickerInteractionUntil",0);m(this,"highlightColor");m(this,"defaultFontColor","#111827");m(this,"defaultBackgroundColor","#ffffff");m(this,"image_array",[]);m(this,"hashtag_array",[]);m(this,"urllink_array",[]);m(this,"custom_array",[]);m(this,"commandTracker",{});m(this,"onWindowMouseDown",e=>{if(R(e.target)&&this.isUnSelectableElement(e.target))return;let t=e.target;if(t instanceof HTMLInputElement&&t.type==="color"){let s=window.getSelection();if(s&&s.rangeCount>0&&this.element.contains(s.anchorNode)&&this.element.contains(s.focusNode)){let o=this.normalizeEditorRange(s.getRangeAt(0));o&&(this.range=o,this.backupCurrentRange(o,{bypassNormalize:!0}))}}let n=document.activeElement;if(n instanceof HTMLInputElement&&n.type==="color"&&R(e.target)&&this.element.contains(e.target)){this.suspendSelectionCaptureForColorPicker=!0,window.setTimeout(()=>{let s=document.activeElement;s instanceof HTMLInputElement&&s.type==="color"||(this.suspendSelectionCaptureForColorPicker=!1)},0);return}this.suspendSelectionCaptureForColorPicker=!1});m(this,"onSelectionChange",()=>{if(this.suspendSelectionCaptureForColorPicker){let e=document.activeElement;if(!(e instanceof HTMLInputElement&&e.type==="color"))this.suspendSelectionCaptureForColorPicker=!1;else return}this.captureRange(),this.updateCommandTracker()});m(this,"onKeyDown",e=>{if(this.lastKey=e.key.toUpperCase(),this.captureRange(),!!this.range){if(["BACKSPACE","DELETE"].includes(this.lastKey)){if(!this.element.textContent?.trim()&&this.element.childNodes.length<=1){e.preventDefault(),this.ensureRootHasSafeLine();return}if(this.handleDeleteFromTrailingEmptyLine()){e.preventDefault();return}}if(this.lastKey==="TAB"){e.preventDefault(),this.insertText(" ");return}if(this.lastKey==="ENTER"){if(this.handleEnterFromQuoteTail()){e.preventDefault();return}queueMicrotask(()=>this.ensureRootHasSafeLine())}window.setTimeout(()=>{this.normalizeDocument(),this.scanSpecialTokens()},0)}});m(this,"onPaste",e=>{e.preventDefault();let t=e.clipboardData?.getData("text/plain")||"";this.insertText(t.replace(/\r\n?/g,` `)),queueMicrotask(()=>{this.normalizeDocument(),this.scanSpecialTokens()})});if(!e||typeof e!="object")throw new Error("Wysiwyg4All option is required");if(!e.elementId||typeof e.elementId!="string")throw new Error("The wysiwyg element should have an ID");let t=e.elementId.startsWith("#")?e.elementId.slice(1):e.elementId,n=document.getElementById(t);if(!n)throw new Error(`element #${t} is null`);this.option={...e,elementId:t},this.element=n,this.callback=e.callback,this.hashtagEnabled=!!e.hashtag,this.urlEnabled=!!e.urllink,this.styleTagOfCommand={...S},this.highlightColor=T(typeof e.highlightColor=="string"?e.highlightColor:"#0d9488")||"#0d9488",this.applyTheme(e.highlightColor),this.applyFontSize(e.fontSize),this.element.classList.add("_wysiwyg4all"),this.element.innerHTML="",this.setPlaceholder(e.placeholder||""),this.setSpellcheck(!!e.spellcheck),this.imageInput=document.createElement("input"),this.imageInput.type="file",this.imageInput.accept="image/gif,image/png,image/jpeg,image/webp",this.imageInput.multiple=!0,this.imageInput.hidden=!0,this.imageInput.addEventListener("change",r=>{this.onImageSelected(r).catch(s=>console.error(s))}),this.initializeCommandTracker(),this.bindCoreEvents(),this.bootstrapExtensions(e.extensions||[]),queueMicrotask(()=>{this.loadHTML(e.html||"",e.editable??!0).catch(r=>{console.error(r)})})}initializeCommandTracker(){let e=["quote","unorderedList","orderedList","alignLeft","alignCenter","alignRight",...Object.keys(this.styleTagOfCommand)];for(let t of e)this.commandTracker[t]=!1}applyTheme(e){let t=typeof e=="object"&&e?e:$(typeof e=="string"?e:"#0d9488");for(let[i,l]of Object.entries(t))this.element.style.setProperty(i,l);let n=getComputedStyle(this.element),r=n.getPropertyValue("--content-text").trim(),s=n.getPropertyValue("--content").trim(),o=n.getPropertyValue("--content-focus").trim();this.defaultFontColor=T(r)||"#111827",this.defaultBackgroundColor=T(s)||"#ffffff",this.highlightColor=T(o)||this.highlightColor}applyFontSize(e){let t=typeof e=="number"?{desktop:e,tablet:e,phone:e}:e||{},n=_(t.desktop,"18px"),r=_(t.tablet??t.desktop,n),s=_(t.phone??t.tablet??t.desktop,r);this.element.style.setProperty("--wysiwyg-font-desktop",n),this.element.style.setProperty("--wysiwyg-font-tablet",r),this.element.style.setProperty("--wysiwyg-font-phone",s);let o={h1:4.2,h2:3.56,h3:2.92,h4:2.28,h5:1.64,h6:1.15,small:.8};for(let[i,l]of Object.entries(o)){let a=t[i]??l;if(typeof a=="number")this.element.style.setProperty(`--wysiwyg-${i}`,`calc(var(--wysiwyg-font) * ${a})`);else{let u=a.trim();if(u.endsWith("px"))this.element.style.setProperty(`--wysiwyg-${i}`,u);else{let c=Number.parseFloat(u);Number.isFinite(c)&&c>0&&this.element.style.setProperty(`--wysiwyg-${i}`,`calc(var(--wysiwyg-font) * ${c})`)}}}}bindCoreEvents(){document.addEventListener("selectionchange",this.onSelectionChange),this.element.addEventListener("keydown",this.onKeyDown),this.element.addEventListener("paste",this.onPaste),window.addEventListener("mousedown",this.onWindowMouseDown)}unbindCoreEvents(){document.removeEventListener("selectionchange",this.onSelectionChange),this.element.removeEventListener("keydown",this.onKeyDown),this.element.removeEventListener("paste",this.onPaste),window.removeEventListener("mousedown",this.onWindowMouseDown)}bootstrapExtensions(e){let t={registerCommand:(n,r)=>{this.customCommandHandlers.set(n,r)},on:(n,r)=>(this.eventBus.has(n)||this.eventBus.set(n,new Set),this.eventBus.get(n)?.add(r),()=>{this.eventBus.get(n)?.delete(r)}),editor:this};for(let n of e)try{n(t)}catch(r){console.error("extension bootstrap failed",r)}}emit(e,...t){let n=this.eventBus.get(e);if(n)for(let r of n)try{r(...t)}catch(s){console.error(s)}}ensureRootHasSafeLine(){if(this.element.childNodes.length===0){this.element.append(this.createEmptyParagraph());return}if(this.element.childNodes.length===1){let e=this.element.firstChild;e&&e.nodeType===Node.TEXT_NODE&&!e.textContent&&(e.remove(),this.element.append(this.createEmptyParagraph()))}}createEmptyParagraph(e){let t=document.createElement("p");return e&&e.length?t.append(document.createTextNode(e)):t.append(document.createElement("br")),t}setSelectionAtStart(e){let t=document.createRange();t.selectNodeContents(e),t.collapse(!0),this.restoreLastSelection(t)}isLineVisuallyEmpty(e){return!this.isLineBlockElement(e)||e.querySelector("img,video,audio,table,hr,._media_,._custom_")?!1:(e.textContent||"").split("\u200B").join("").trim().length===0}isNonTextElement(e){return e.classList.contains("_media_")||e.classList.contains("_custom_")?!0:["HR","BLOCKQUOTE","UL","OL","TABLE"].includes(e.tagName)}getContainingQuote(e){let t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;if(!t)return null;let n=t.closest("blockquote");return n instanceof HTMLElement?n:null}unwrapQuote(e){let t=e.parentNode;if(!t)return;let n=e.firstChild;for(;e.firstChild;)t.insertBefore(e.firstChild,e);if(e.remove(),n){let r=n.nodeType===Node.TEXT_NODE?n.parentNode:n;r&&this.setSelectionAtStart(r)}this.ensureRootHasSafeLine()}getQuoteLineBlocks(e){return Array.from(e.querySelectorAll("p,li,td,th,tr"))}handleEnterFromQuoteTail(){if(!this.range||!this.range.collapsed)return!1;let e=this.getContainingQuote(this.range.startContainer);if(!e)return!1;let t=this.getContainingLineBlock(this.range.startContainer);if(!t||!e.contains(t)||!this.isLineVisuallyEmpty(t))return!1;let n=this.getQuoteLineBlocks(e);if(n.length===0||n[n.length-1]!==t)return!1;if(t.remove(),this.getQuoteLineBlocks(e).length===0&&!(e.textContent||"").trim())return e.remove(),this.ensureRootHasSafeLine(),this.setSelectionAtStart(this.element.lastElementChild||this.element),!0;let s=this.ensureTrailingEditableLineAfter(e);return this.setSelectionAtStart(s),!0}handleDeleteFromTrailingEmptyLine(){if(!this.range||!this.range.collapsed)return!1;let e=this.getContainingLineBlock(this.range.startContainer);if(!e||e!==this.element.lastElementChild||!this.isLineVisuallyEmpty(e))return!1;let t=e.previousElementSibling;return!t||!this.isNonTextElement(t)?!1:(t.remove(),e.isConnected?(this.setSelectionAtStart(e),!0):(this.element.append(this.createEmptyParagraph()),this.setSelectionAtStart(this.element.lastElementChild),!0))}captureRange(){let e=window.getSelection();if(!e||!this.element.contains(e.anchorNode))return;if(!e||e.rangeCount===0){this.range=null;return}let t=this.normalizeEditorRange(e.getRangeAt(0)),n=t;if(!n){this.range=null;return}let r=this.reanchorCollapsedRangeToAdjacentStylePlaceholder(n);r&&(n=r,t&&(n.startContainer!==t.startContainer||n.startOffset!==t.startOffset)&&(e.removeAllRanges(),e.addRange(n))),this.range=n,this.backupCurrentRange(n,{bypassNormalize:!0})}isCollapsedStyleAnchorSpan(e){return e.tagName!=="SPAN"||this.isProtectedSpan(e)||!this.isTextStyleWrapper(e,this.getKnownInlineStyleClassSet())||e.querySelector("br,hr,img,video,audio,table,ul,ol,li,blockquote,div,._media_,._custom_")?!1:(e.textContent||"").split("\u200B").join("").trim().length===0}reanchorCollapsedRangeToAdjacentStylePlaceholder(e){if(!e.collapsed)return null;let t=c=>{if(!(c instanceof HTMLElement)||!this.isCollapsedStyleAnchorSpan(c))return null;let g=c.firstChild,f=g instanceof Text?g:document.createTextNode("\u200B");g instanceof Text||c.append(f);let h=document.createRange();return h.setStart(f,f.length),h.collapse(!0),h},n=(c,g)=>{if(!(c instanceof Element))return null;let f=g>0?c.childNodes[g-1]:null,h=g<c.childNodes.length?c.childNodes[g]:null,v=[f,h];for(let E of v){let C=t(E);if(C)return C}return null},r=(c,g)=>{let f=c;for(;f&&f!==this.element;){let h=f.parentNode;if(!h||h===this.element.parentNode)break;let v=g?f.nextSibling:f.previousSibling,E=t(v);if(E)return E;f=h}return null};if(e.startContainer instanceof Element){let c=n(e.startContainer,e.startOffset);return c||(e.startOffset>=e.startContainer.childNodes.length?r(e.startContainer,!0):e.startOffset===0?r(e.startContainer,!1):null)}let s=e.startContainer,o=s.parentElement;if(!o)return null;let l=Array.from(o.childNodes).indexOf(s);if(l<0)return null;let a=l+(e.startOffset>0?1:0),u=n(o,a);if(u)return u;if(s instanceof Text){if(e.startOffset>=s.length)return r(o,!0);if(e.startOffset===0)return r(o,!1)}return null}backupCurrentRange(e,t){let n=t?.bypassNormalize??!1,r=null;if(e instanceof Range)r=e.cloneRange();else{let o=e??window.getSelection();if(!o||o.rangeCount===0||!this.element.contains(o.anchorNode))return null;r=o.getRangeAt(0).cloneRange()}let s=n?r:this.normalizeEditorRange(r);return s?(this.rangeBackup=s.cloneRange(),this.rangeBackup):null}getTextOffsetWithinEditor(e,t){if(e!==this.element&&!this.element.contains(e))return null;let n=document.createRange();try{n.setStart(this.element,0),n.setEnd(e,t)}catch{return null}return n.toString().length}resolveBoundaryFromTextOffset(e){let t=Math.max(0,e),n=document.createTreeWalker(this.element,NodeFilter.SHOW_TEXT),r=null;for(;n.nextNode();){let o=n.currentNode,i=o.length;if(r=o,t<=i)return{container:o,offset:t};t-=i}if(r)return{container:r,offset:r.length};let s=this.element.lastChild;return s?this.getDeepBoundaryPoint(s,!1):null}snapshotRangeToTextOffsets(e){let t=this.normalizeEditorRange(e);if(!t)return null;let n=this.getTextOffsetWithinEditor(t.startContainer,t.startOffset),r=this.getTextOffsetWithinEditor(t.endContainer,t.endOffset);return n===null||r===null?null:{start:n,end:r}}restoreRangeFromTextOffsets(e){let t=this.resolveBoundaryFromTextOffset(e.start),n=this.resolveBoundaryFromTextOffset(e.end);if(!t||!n)return null;let r=document.createRange();try{r.setStart(t.container,t.offset),r.setEnd(n.container,n.offset)}catch{return null}return this.normalizeEditorRange(r)}getDeepBoundaryPoint(e,t){let n=e;for(;n.nodeType!==Node.TEXT_NODE&&n.childNodes.length>0;)n=t?n.firstChild:n.lastChild;if(n.nodeType===Node.TEXT_NODE){let r=n;return{container:r,offset:t?0:r.length}}return{container:n,offset:t?0:n.childNodes.length}}resolveRangeBoundaryPoint(e,t,n){if(e===this.element){let{childNodes:r}=this.element;if(r.length===0)return null;if(n){let o=t<r.length?r[t]:r[r.length-1];return this.getDeepBoundaryPoint(o,t<r.length)}let s=t>0?r[t-1]:r[0];return this.getDeepBoundaryPoint(s,t===0)}return this.element.contains(e)?{container:e,offset:t}:null}normalizeEditorRange(e){if(e.collapsed){let s=this.resolveRangeBoundaryPoint(e.startContainer,e.startOffset,!0);if(!s)return null;let o=e.cloneRange();try{o.setStart(s.container,s.offset),o.setEnd(s.container,s.offset)}catch{return null}return o}let t=this.resolveRangeBoundaryPoint(e.startContainer,e.startOffset,!0),n=this.resolveRangeBoundaryPoint(e.endContainer,e.endOffset,!1);if(!t||!n)return null;let r=e.cloneRange();try{r.setStart(t.container,t.offset),r.setEnd(n.container,n.offset)}catch{return null}return r}restoreLastSelection(e=this.rangeBackup){if(!e)return;let t=this.normalizeEditorRange(e);if(!t)return;let n=window.getSelection();n&&(this.range=t,n.removeAllRanges(),n.addRange(t))}setPlaceholder(e){e&&e.trim()?this.element.setAttribute("placeholder",e):this.element.removeAttribute("placeholder"),this.updatePlaceholderVisibility()}setSpellcheck(e){this.element.setAttribute("spellcheck",e?"true":"false")}setEditable(e){this.element.setAttribute("contenteditable",e?"true":"false"),this.observeMutation(e),this.updatePlaceholderVisibility()}isEditorInPlaceholderState(){if(this.element.childNodes.length===0)return!0;if(this.element.childNodes.length!==1)return!1;let e=this.element.firstChild;return e?e.nodeType===Node.TEXT_NODE?(e.textContent||"").split("\u200B").join("").trim().length===0:e instanceof HTMLElement?e.tagName==="BR"?!0:e.tagName==="P"?this.isLineVisuallyEmpty(e):!1:!1:!0}updatePlaceholderVisibility(){let e=!!this.element.getAttribute("placeholder")?.trim(),t=this.element.getAttribute("contenteditable")==="true",n=e&&t&&this.isEditorInPlaceholderState();this.element.classList.toggle("_placeholderVisible",n)}destroy(){this.unbindCoreEvents(),this.observeMutation(!1),this.colorCommandDebounceTimer!==null&&(window.clearTimeout(this.colorCommandDebounceTimer),this.colorCommandDebounceTimer=null),this.imageInput.remove(),this.eventBus.clear(),this.customCommandHandlers.clear()}observeMutation(e){this.observer&&(this.observer.disconnect(),this.observer=null),e&&(this.observer=new MutationObserver(t=>{for(let n of t){if(n.type!=="childList")continue;let r=n.target;if(r instanceof HTMLElement){if(r===this.element&&r.childNodes.length===0){r.append(this.createEmptyParagraph());continue}if(this.isCeilingElement(r)&&r!==this.element&&r.childNodes.length===0){r.remove();continue}this.isTextBlockElement(r)&&r.childNodes.length===1&&this.isUnSelectableElement(r.firstChild)&&r.append(document.createTextNode(""))}}this.updatePlaceholderVisibility()}),this.observer.observe(this.element,{attributes:!0,childList:!0,characterData:!0,subtree:!0}))}isUnSelectableElement(e){let t=e?.nodeType===Node.TEXT_NODE?e.parentElement:e;return t?!!t.closest("._media_, ._hashtag_, ._urllink_, hr"):!1}isTextBlockElement(e){let t=e?.nodeType===Node.TEXT_NODE?e.parentElement:e;return t?["P","LI","TD","TH","TR"].includes(t.tagName):!1}isCeilingElement(e){let t=e?.nodeType===Node.TEXT_NODE?e.parentElement:e;return t?t===this.element?!0:["UL","OL","LI","BLOCKQUOTE"].includes(t.tagName):!1}cleanupZeroWidthSpaces(){let e=[],t=document.createTreeWalker(this.element,NodeFilter.SHOW_TEXT,{acceptNode:n=>{let r=n.parentElement;return!r||r.closest("._media_, ._custom_")?NodeFilter.FILTER_REJECT:(n.textContent||"").includes("\u200B")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;t.nextNode();)e.push(t.currentNode);for(let n of e){let r=n.length-1;for(;r>=0;)n.data[r]==="\u200B"&&n.deleteData(r,1),r--;n.length===0&&n.remove()}this.element.normalize()}normalizeDocument(){let e=window.getSelection(),t=!!(e&&e.rangeCount>0&&this.element.contains(e.anchorNode)&&this.element.contains(e.focusNode)),n=t?this.range??this.rangeBackup:this.range??this.rangeBackup,r=n?this.snapshotRangeToTextOffsets(n):null;this.cleanupZeroWidthSpaces();let s=[],o=document.createTreeWalker(this.element,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT);for(;o.nextNode();){let i=o.currentNode;if(i.nodeType===Node.ELEMENT_NODE){let l=i;if(l.classList.contains("_static_"))continue;!l.classList.contains("_media_")&&!l.classList.contains("_custom_")&&!l.closest("._media_")&&!l.closest("._custom_")&&!this.isCeilingElement(l)&&!l.textContent&&l.childNodes.length===0&&l.tagName!=="BR"&&l.tagName!=="HR"&&s.push(l)}}for(let i of s)i.remove();if(this.redistributeInlineStylesAcrossBlocks(),this.cleanupNestedFontSizeWrappers(),this.cleanupRedundantTextWrappers(),this.cleanupEmptyTextStyleElements(),this.ensureRootHasSafeLine(),t){this.captureRange();return}if(r){let i=this.restoreRangeFromTextOffsets(r);i&&(this.range=i,this.rangeBackup=i.cloneRange())}}isLineBlockElement(e){return["P","LI","TD","TH","TR"].includes(e.tagName)}cloneInlineStyleSpan(e){let t=document.createElement("span");return t.className=e.className,e.style.cssText.trim()&&(t.style.cssText=e.style.cssText),t}getContainingLineBlock(e){let t=e.nodeType===Node.TEXT_NODE?e.parentNode:e;for(;t&&t!==this.element;){if(t instanceof HTMLElement&&this.isLineBlockElement(t))return t;t=t.parentNode}return null}getLineBlocksBetween(e,t){let n=Array.from(this.element.querySelectorAll("p,li,td,th,tr")),r=n.indexOf(e),s=n.indexOf(t);if(r<0||s<0)return[];let o=Math.min(r,s),i=Math.max(r,s);return n.slice(o,i+1)}doesRangeIntersectElement(e,t){let n=document.createRange();n.selectNodeContents(t);let r=e.compareBoundaryPoints(Range.END_TO_START,n)<=0,s=e.compareBoundaryPoints(Range.START_TO_END,n)>=0;return!r&&!s}getSelectedLineBlocks(e){return Array.from(this.element.querySelectorAll("p,li,td,th,tr")).filter(n=>this.doesRangeIntersectElement(e,n))}createLineIntersectionRange(e,t){let n=document.createRange();return n.selectNodeContents(t),t.contains(e.startContainer)&&n.setStart(e.startContainer,e.startOffset),t.contains(e.endContainer)&&n.setEnd(e.endContainer,e.endOffset),this.splitRangeBoundaries(n)}applyStyleToRange(e,t,n,r){if(e.collapsed)return null;let s=e.extractContents(),o=document.createElement("span");return o.classList.add(t),n==="color"&&r&&o.style.setProperty("color",r),n==="backgroundColor"&&r&&o.style.setProperty("background-color",r),o.append(s),this.stripSameStyleFromFragment(o,t,n),this.removeCounterClasses(o,n),e.insertNode(o),o}wrapMultilineSelectionWithClass(e,t,n,r,s){let o=s||this.getSelectedLineBlocks(e);if(o.length<=1)return!1;let i=o.map(a=>this.createLineIntersectionRange(e,a)).filter(a=>!a.collapsed);if(i.length===0)return!1;let l=null;for(let a=i.length-1;a>=0;a--){let u=this.applyStyleToRange(i[a],t,n,r);u&&!l&&(l=u)}return l&&this.setSelectionAtEnd(l),this.normalizeDocument(),this.cleanupEmptyTextStyleElements(),!0}redistributeInlineStylesAcrossBlocks(){let e=this.getKnownInlineStyleClassSet(),t=!0;for(;t;){t=!1;let n=Array.from(this.element.querySelectorAll("span")).reverse();for(let r of n){if(!r.isConnected||!this.isTextStyleWrapper(r,e)||this.isProtectedSpan(r))continue;let s=Array.from(r.childNodes);if(!s.some(c=>c instanceof HTMLElement&&this.isLineBlockElement(c)))continue;let i=r.parentNode;if(!i)continue;let l=document.createDocumentFragment(),a=[],u=()=>{if(a.length===0)return;let c=this.cloneInlineStyleSpan(r);for(let g of a)c.append(g);l.append(c),a=[]};for(let c of s)if(r.removeChild(c),c instanceof HTMLElement&&this.isLineBlockElement(c)){u();let g=c,f=this.cloneInlineStyleSpan(r);for(;g.firstChild;)f.append(g.firstChild);g.append(f),l.append(g)}else a.push(c);u(),i.insertBefore(l,r),r.remove(),t=!0}}}isFontSizeClassName(e){return z.has(e)}getElementFontSizeClass(e){for(let t of w)if(e.classList.contains(t))return t;return null}findOutermostFontSizeAncestor(e){let t=e.nodeType===Node.TEXT_NODE?e.parentNode:e,n=null;for(;t&&t!==this.element;)t instanceof HTMLElement&&this.getElementFontSizeClass(t)&&(n=t),t=t.parentNode;return n}cleanupNestedFontSizeWrappers(){let e=!0;for(;e;){e=!1;let t=Array.from(this.element.querySelectorAll("span")).reverse();for(let n of t){if(!n.isConnected||n.closest("._media_, ._custom_")||!this.getElementFontSizeClass(n))continue;let r=n.parentElement,s=null;for(;r&&r!==this.element;)this.getElementFontSizeClass(r)&&(s=r),r=r.parentElement;s&&(this.breakOutFromAncestor(n,s),e=!0)}}}hasMeaningfulAttributes(e){for(let t of Array.from(e.attributes)){let n=t.name.toLowerCase(),r=t.value.trim();if(n==="class"){if(e.classList.length>0)return!0;continue}if(n==="style"){if(e.style.length>0||r.length>0)return!0;continue}if(n.startsWith("data-")||n==="id"&&r.length>0||n==="contenteditable"&&r.length>0||r.length>0)return!0}return!1}hasNonClassStyleAttributes(e){for(let t of Array.from(e.attributes)){let n=t.name.toLowerCase();if(!(n==="class"||n==="style")&&(n.startsWith("data-")||t.value.trim().length>0))return!0}return!1}isProtectedSpan(e){return!!(e.tagName!=="SPAN"||e.classList.contains("_hashtag_")||e.classList.contains("_urllink_")||e.closest("._media_, ._custom_"))}cleanupRedundantTextWrappers(){let e=this.getKnownInlineStyleClassSet(),t=!0;for(;t;){t=!1;let n=Array.from(this.element.querySelectorAll("span")).reverse();for(let r of n){if(!r.isConnected||this.isProtectedSpan(r))continue;let s=Array.from(r.childNodes),o=s.filter(i=>i instanceof HTMLElement);if(o.length===1&&s.length===1){let i=o[0];if(i.tagName==="SPAN"&&!this.isProtectedSpan(i)&&r.className.trim()===i.className.trim()&&r.style.cssText.trim()===i.style.cssText.trim()&&!this.hasNonClassStyleAttributes(r)&&!this.hasNonClassStyleAttributes(i)){for(;i.firstChild;)r.insertBefore(i.firstChild,i);i.remove(),t=!0}}if(!this.hasMeaningfulAttributes(r)&&!this.isTextStyleWrapper(r,e)){let i=r.parentNode;if(!i)continue;for(;r.firstChild;)i.insertBefore(r.firstChild,r);r.remove(),t=!0}}}}isTextStyleWrapper(e,t){if(e.tagName!=="SPAN"||e.classList.contains("_hashtag_")||e.classList.contains("_urllink_"))return!1;for(let n of Array.from(e.classList))if(t.has(n)||n.endsWith("_stop"))return!0;return!1}cleanupEmptyTextStyleElements(){let e=this.getKnownInlineStyleClassSet(),t="br,hr,img,video,audio,table,ul,ol,li,blockquote,div,._media_,._custom_",n=!0;for(;n;){n=!1;let r=Array.from(this.element.querySelectorAll("span")).reverse();for(let s of r){if(!this.isTextStyleWrapper(s,e)||s.querySelector(t))continue;(s.textContent||"").split("\u200B").join("").trim().length===0&&(s.remove(),n=!0)}}}setSelectionAtEnd(e){let t=document.createRange();t.selectNodeContents(e),t.collapse(!1),this.restoreLastSelection(t)}splitRangeBoundaries(e){if(e.startContainer.nodeType===Node.TEXT_NODE){let t=e.startContainer;e.startOffset>0&&e.startOffset<t.length&&(t.splitText(e.startOffset),e.setStart(t.nextSibling,0))}if(e.endContainer.nodeType===Node.TEXT_NODE){let t=e.endContainer;e.endOffset>0&&e.endOffset<t.length&&t.splitText(e.endOffset)}return e}getKnownInlineStyleClassSet(){return new Set(Object.values(S))}findClosestAncestorWithClass(e,t){let n=e.nodeType===Node.TEXT_NODE?e.parentNode:e;for(;n&&n!==this.element;){if(n instanceof HTMLElement&&n.classList.contains(t))return n;n=n.parentNode}return null}findOutermostAncestorWithClass(e,t){let n=e.nodeType===Node.TEXT_NODE?e.parentNode:e,r=null;for(;n&&n!==this.element;)n instanceof HTMLElement&&n.classList.contains(t)&&(r=n),n=n.parentNode;return r}collectPreservedInlineStyles(e,t){let n=this.getKnownInlineStyleClassSet(),r=[];for(let s of Array.from(e.classList))n.has(s)&&(s===t||s===`${t}_stop`||r.push(s));return{classes:r,color:e.style.color||void 0,backgroundColor:e.style.backgroundColor||void 0}}liftNodeOneLevel(e){let t=e.parentElement;if(!t||t===this.element)return;let n=t.parentNode;if(!n||n!==this.element&&!(n instanceof HTMLElement&&this.element.contains(n)))return;let r=t.cloneNode(!1);for(;e.nextSibling;)r.append(e.nextSibling);n.insertBefore(e,t.nextSibling),r.childNodes.length&&n.insertBefore(r,e.nextSibling),t.childNodes.length===0&&t.remove()}breakOutFromAncestor(e,t){if(!(!this.element.contains(e)||!this.element.contains(t))){for(;e.parentElement&&e.parentElement!==t;)this.liftNodeOneLevel(e);e.parentElement===t&&t.parentElement&&this.element.contains(t.parentElement)&&this.liftNodeOneLevel(e),t.childNodes.length===0&&t.remove()}}stripSameStyleFromFragment(e,t,n){let r=e.querySelectorAll(`.${t}`);for(let s of Array.from(r))s.classList.remove(t),n==="color"&&s.style.removeProperty("color"),n==="backgroundColor"&&s.style.removeProperty("background-color")}wrapSelectionWithClass(e,t,n){if(this.captureRange(),!this.range)return;let r=this.splitRangeBoundaries(this.range.cloneRange());if(!r.collapsed){let C=this.getContainingLineBlock(r.startContainer),d=this.getContainingLineBlock(r.endContainer);if(C&&d&&C!==d){let y=this.getLineBlocksBetween(C,d);if(this.wrapMultilineSelectionWithClass(r,e,t,n,y))return}if(this.wrapMultilineSelectionWithClass(r,e,t,n))return}let s=this.isFontSizeClassName(e),o=this.findClosestAncestorWithClass(r.startContainer,e),i=this.findClosestAncestorWithClass(r.endContainer,e),a=!!o&&o===i?o:null,u=s?this.findOutermostFontSizeAncestor(r.startContainer):null,c=s?this.findOutermostFontSizeAncestor(r.endContainer):null,f=a??(s&&u&&u===c?u:null),h=a?this.collectPreservedInlineStyles(a,e):{classes:[],color:void 0,backgroundColor:void 0};if(r.collapsed){let C=document.createElement("span");C.classList.add(e);for(let b of h.classes)C.classList.add(b);t!=="color"&&h.color&&C.style.setProperty("color",h.color),t!=="backgroundColor"&&h.backgroundColor&&C.style.setProperty("background-color",h.backgroundColor),t==="color"&&n&&C.style.setProperty("color",n),t==="backgroundColor"&&n&&C.style.setProperty("background-color",n);let d=document.createTextNode("\u200B");C.append(d),r.insertNode(C),f&&this.breakOutFromAncestor(C,f);let y=document.createRange();y.setStart(d,1),y.collapse(!0),this.restoreLastSelection(y),this.backupCurrentRange(y,{bypassNormalize:!0}),this.element.focus({preventScroll:!0});return}let v=r.extractContents(),E=document.createElement("span");E.classList.add(e);for(let C of h.classes)E.classList.add(C);t!=="color"&&h.color&&E.style.setProperty("color",h.color),t!=="backgroundColor"&&h.backgroundColor&&E.style.setProperty("background-color",h.backgroundColor),t==="color"&&n&&E.style.setProperty("color",n),t==="backgroundColor"&&n&&E.style.setProperty("background-color",n),E.append(v),this.stripSameStyleFromFragment(E,e,t),this.removeCounterClasses(E,t),r.insertNode(E),f&&this.breakOutFromAncestor(E,f),this.setSelectionAtEnd(E),this.normalizeDocument(),this.cleanupEmptyTextStyleElements()}removeCounterClasses(e,t){let n=D[t]||[];for(let r of n)e.querySelectorAll(`.${r}`).forEach(s=>s.classList.remove(r))}isStyleAppliedToSelection(e){if(this.captureRange(),!this.range)return!1;let t=this.range.collapsed?this.range.startContainer:this.range.commonAncestorContainer,n=t.nodeType===Node.TEXT_NODE?t.parentElement:t;return!n||!this.element.contains(n)?!1:!!n.closest(`.${e}`)}removeStyleFromSelection(e,t){if(this.captureRange(),!this.range)return;let n=this.splitRangeBoundaries(this.range.cloneRange()),r=n.collapsed?this.findOutermostAncestorWithClass(n.startContainer,e):null,s=this.findClosestAncestorWithClass(n.startContainer,e),o=this.findClosestAncestorWithClass(n.endContainer,e),i=n.collapsed?r:s&&s===o?s:null;if(n.collapsed){if(i){let c=document.createElement("span");c.classList.add(`${e}_stop`);let g=document.createTextNode("\u200B");if(c.append(g),this.isCollapsedStyleAnchorSpan(i)){let v=i.parentNode;if(!v)return;let E=i.nextSibling;i.remove(),v.insertBefore(c,E);let C=document.createRange();C.setStart(g,1),C.collapse(!0),this.restoreLastSelection(C),this.backupCurrentRange(C,{bypassNormalize:!0}),this.element.focus({preventScroll:!0}),this.ensureRootHasSafeLine();return}let f=i.parentNode;if(!f)return;f.insertBefore(c,i.nextSibling);let h=document.createRange();h.setStart(g,1),h.collapse(!0),this.restoreLastSelection(h),this.backupCurrentRange(h,{bypassNormalize:!0}),this.element.focus({preventScroll:!0})}return}let l=i?this.collectPreservedInlineStyles(i,e):{classes:[],color:void 0,backgroundColor:void 0},a=n.extractContents(),u=document.createElement("span");for(let c of l.classes)u.classList.add(c);t!=="color"&&l.color&&u.style.setProperty("color",l.color),t!=="backgroundColor"&&l.backgroundColor&&u.style.setProperty("background-color",l.backgroundColor),u.append(a),this.stripSameStyleFromFragment(u,e,t),u.classList.remove(e),t==="color"&&u.style.removeProperty("color"),t==="backgroundColor"&&u.style.removeProperty("background-color"),n.insertNode(u),i&&this.breakOutFromAncestor(u,i),this.setSelectionAtEnd(u),this.normalizeDocument(),this.cleanupEmptyTextStyleElements()}applyAlignment(e){if(this.captureRange(),!this.range)return;let t=this.getClosestLine(this.range.startContainer);if(t){for(let n of F)t.classList.remove(n);e==="alignCenter"&&t.classList.add("_alignCenter_"),e==="alignRight"&&t.classList.add("_alignRight_")}}getClosestLine(e){let t=e;for(;t&&t!==this.element;){if(t instanceof HTMLElement&&(W.has(t.tagName)||t.classList.contains("_media_")))return t;t=t.parentNode}return this.element.lastElementChild}insertNodeAtSelection(e,t=!0){if(this.captureRange(),!this.range){this.element.append(e);return}if(!t){if(this.range.insertNode(e),e.nodeType===Node.TEXT_NODE)this.setSelectionAtEnd(e);else{let r=document.createRange();r.setStartAfter(e),r.collapse(!0),this.restoreLastSelection(r)}return}let n=this.getClosestLine(this.range.endContainer);if(!n||!n.parentNode){this.element.append(e);return}n.nextSibling?n.parentNode.insertBefore(e,n.nextSibling):n.parentNode.append(e),this.setSelectionAtEnd(e)}ensureCaretAfterNonTextElement(e){if(!e.isConnected)return;let t=e.parentElement;if(!t)return;let n=e.nextElementSibling,r=null;for(;n;){if(this.isLineBlockElement(n)){r=n;break}n=n.nextElementSibling}r||(r=this.createEmptyParagraph(),t.append(r)),r.childNodes.length===0&&r.append(document.createElement("br")),this.setSelectionAtStart(r)}ensureTrailingEditableLineAfter(e){let t=e.parentElement;if(!t)return this.createEmptyParagraph();let n=e.nextElementSibling;if(n&&this.isLineBlockElement(n))return n.childNodes.length===0&&n.append(document.createElement("br")),n;if(n&&!this.isLineBlockElement(n)){let s=this.createEmptyParagraph();return t.insertBefore(s,n),s}let r=this.createEmptyParagraph();return t.append(r),r}insertText(e){if(this.captureRange(),!this.range)return;this.range.deleteContents();let t=e.split(` `);if(t.length===1){let r=document.createTextNode(t[0]);this.range.insertNode(r);let s=document.createRange();s.setStart(r,r.length),s.collapse(!0),this.restoreLastSelection(s);return}let n=document.createDocumentFragment();for(let r=0;r<t.length;r++)r>0&&n.append(document.createElement("br")),n.append(document.createTextNode(t[r]));this.range.insertNode(n)}async onImageSelected(e){let t=e.target,n=t.files;if(!n||n.length===0)return;await this.safeCallback({loading:!0});let r=[];for(let l of Array.from(n)){let a=await this.readFileAsDataUrl(l),u=await this.readImageDimension(a);r.push({elementId:k("img"),source:a,filename:l.name,fileType:l.type,fileSize:l.size,lastModified:l.lastModified,dimension:u})}await this.safeCallback({loading:!1}),t.value="";let o=(await this.safeCallback({image:r})).image||r,i=null;for(let l of o){let a=document.createElement("div");a.classList.add("_media_"),a.setAttribute("contenteditable","false");let u=l.element instanceof HTMLImageElement?l.element:document.createElement("img");if(u.id=l.elementId||k("img"),u.setAttribute("src",l.source),u.classList.add(`_img_${l.source.slice(-64).replace(/[^a-zA-Z0-9_-]/g,"")}`),Array.isArray(l.class))for(let c of l.class)u.classList.add(c);if(l.onclick&&(u.addEventListener("click",l.onclick),u.classList.add("_hover_")),a.append(u),l.style)for(let[c,g]of Object.entries(l.style))a.style.setProperty(c,g);this.image_array.push({...l,element:u,elementId:u.id}),this.insertNodeAtSelection(a,!0),i=a}i&&this.ensureCaretAfterNonTextElement(i)}readFileAsDataUrl(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result||"")),r.onerror=()=>n(r.error||new Error("file read failed")),r.readAsDataURL(e)})}readImageDimension(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>t({width:r.width,height:r.height}),r.onerror=()=>n(new Error("image decode failed")),r.src=e})}async safeCallback(e){if(typeof this.callback!="function")return e;let t=this.callback(e);return(t instanceof Promise?await t:t)||e}resolveSpanByData(e){if(e.element instanceof HTMLSpanElement)return e.element;if(!e.elementId)return null;let t=document.getElementById(e.elementId);return t instanceof HTMLSpanElement?t:null}applySpanDecorators(e,t){if(t.style)for(let[n,r]of Object.entries(t.style))e.style.setProperty(n,r);t.onclick&&(e.addEventListener("click",t.onclick),e.classList.add("_hover_"))}isTransparentComputedColor(e){let t=e.replace(/\s+/g,"").toLowerCase();if(t==="transparent")return!0;let n=t.match(/^rgba\((\d+),(\d+),(\d+),([^\)]+)\)$/);return n?Number(n[4])===0:!1}resolveTrackerTextColor(e){return T(window.getComputedStyle(e).color)||this.defaultFontColor}resolveTrackerBackgroundColor(e){let t=e;for(;t;){let n=window.getComputedStyle(t).backgroundColor;if(!this.isTransparentComputedColor(n)){let r=T(n);if(r)return r}if(t===this.element)break;t=t.parentElement}return this.defaultBackgroundColor}updateCommandTracker(){this.trackerUpdateQueued=!0,!this.trackerUpdateInFlight&&(this.trackerUpdateInFlight=!0,this.flushCommandTrackerUpdates())}async flushCommandTrackerUpdates(){try{for(;this.trackerUpdateQueued;)this.trackerUpdateQueued=!1,await this.runCommandTrackerUpdate()}finally{this.trackerUpdateInFlight=!1,this.trackerUpdateQueued&&(this.trackerUpdateInFlight=!0,this.flushCommandTrackerUpdates())}}async runCommandTrackerUpdate(){let e=null,t=window.getSelection();t&&t.rangeCount>0&&this.element.contains(t.anchorNode)&&this.element.contains(t.focusNode)&&(e=this.normalizeEditorRange(t.getRangeAt(0))),e||(this.captureRange(),e=this.range);let n=document.activeElement,s=n instanceof HTMLInputElement&&n.type==="color"||Date.now()<this.colorPickerInteractionUntil;s||(this.livePickerColor=null,this.livePickerBackgroundColor=null);let o={unorderedList:!1,orderedList:!1,alignLeft:!1,alignCenter:!1,alignRight:!1,h1:!1,h2:!1,h3:!1,h4:!1,h5:!1,h6:!1,small:!1,bold:!1,italic:!1,underline:!1,strike:!1,color:this.defaultFontColor,backgroundColor:this.defaultBackgroundColor},i=null;if(e){let a=e.collapsed?e.startContainer:e.commonAncestorContainer,u=a.nodeType===Node.TEXT_NODE?a.parentElement:a;if(u&&this.element.contains(u)){o.color=this.resolveTrackerTextColor(u),o.backgroundColor=this.resolveTrackerBackgroundColor(u);for(let[c,g]of Object.entries(this.styleTagOfCommand)){let f=u.closest(`.${g}_stop`),h=u.closest(`.${g}`);f&&h&&h.contains(f)||f&&!h||h&&(c==="color"||c==="backgroundColor"||(o[c]=!0))}i=this.getClosestLine(e.startContainer)}}s&&(this.livePickerColor&&(o.color=this.livePickerColor),this.livePickerBackgroundColor&&(o.backgroundColor=this.livePickerBackgroundColor)),i&&(o.alignLeft=!i.classList.contains("_alignCenter_")&&!i.classList.contains("_alignRight_"),o.alignCenter=i.classList.contains("_alignCenter_"),o.alignRight=i.classList.contains("_alignRight_"),o.unorderedList=!!i.closest("ul"),o.orderedList=!!i.closest("ol")),this.commandTracker=o;let l=null;if(e){let a=e.collapsed?e.startContainer:e.endContainer;a.nodeType===Node.TEXT_NODE?l=e.getBoundingClientRect():a instanceof Element&&(l=a.getBoundingClientRect())}try{await this.safeCallback({commandTracker:o,range:e,caratPosition:l})}catch(a){console.error(a)}}async scanSpecialTokens(){if(!this.hashtagEnabled&&!this.urlEnabled)return;let e=window.getSelection(),t=e&&e.rangeCount>0&&this.element.contains(e.anchorNode)?this.normalizeEditorRange(e.getRangeAt(0)):null,n=t?this.snapshotRangeToTextOffsets(t):null,r=!1,s=document.createTreeWalker(this.element,NodeFilter.SHOW_TEXT,{acceptNode:a=>{if(!(a.textContent||"").trim())return NodeFilter.FILTER_REJECT;let c=a.parentElement;return!c||c.closest("._media_, ._custom_, ._hashtag_, ._urllink_")?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),o=[];for(;s.nextNode();)o.push(s.currentNode);let i=[],l=[];for(let a of o){let u=a.textContent||"",c=a.parentNode;if(!c)continue;let g=[],f=0,h=[];if(this.hashtagEnabled)for(let d of u.matchAll(U)){let y=d[1]||"",b=d[2]||"",L=(d.index||0)+y.length;h.push({index:L,end:L+b.length,type:"hashtag",value:b})}if(this.urlEnabled)for(let d of u.matchAll(q)){let y=d[0]||"",b=d.index||0;h.push({index:b,end:b+y.length,type:"url",value:y})}h.sort((d,y)=>d.index-y.index);let v=[],E=-1;for(let d of h)d.index<E||(v.push(d),E=d.end);if(v.length===0)continue;for(let d of v)d.index>f&&g.push({type:"text",value:u.slice(f,d.index)}),g.push({type:d.type,value:d.value}),f=d.end;f<u.length&&g.push({type:"text",value:u.slice(f)});let C=document.createDocumentFragment();for(let d of g){if(d.type==="text"){C.append(document.createTextNode(d.value));continue}let y=document.createElement("span");if(y.setAttribute("contenteditable","false"),y.textContent=d.value,d.type==="hashtag"){let b=k("hashtag");y.id=b,y.className=`_hashtag_ _hashtag_${d.value}`,i.push({elementId:b,tag:d.value.replace(/^#/,""),element:y})}else{let b=k("urllink");y.id=b,y.className=`_urllink_ _urllink_${d.value}`,y.addEventListener("click",()=>{let L=/^https?:\/\//i.test(d.value)?d.value:`http://${d.value}`;window.open(L,"_blank","noopener,noreferrer")}),l.push({elementId:b,url:d.value,element:y})}C.append(y)}c.replaceChild(C,a),r=!0}if(i.length>0){let a=await this.safeCallback({hashtag:i});for(let u of a.hashtag||i){let c=this.resolveSpanByData(u);c&&(this.applySpanDecorators(c,u),this.hashtag_array.push({...u,element:c,elementId:c.id||u.elementId}))}}if(l.length>0){let a=await this.safeCallback({urllink:l});for(let u of a.urllink||l){let c=this.resolveSpanByData(u);c&&(this.applySpanDecorators(c,u),this.urllink_array.push({...u,element:c,elementId:c.id||u.elementId}))}}if(r&&n){let a=this.restoreRangeFromTextOffsets(n);a&&(this.restoreLastSelection(a),this.backupCurrentRange(a,{bypassNormalize:!0}))}}async command(e){let t=typeof e=="object"&&!!e&&["color","backgroundColor"].some(s=>s in e),n=document.activeElement,r=n instanceof HTMLInputElement&&n.type==="color";if(t&&typeof e=="object"&&e&&(this.colorPickerInteractionUntil=Date.now()+500,typeof e.color=="string"&&(this.livePickerColor=T(e.color)||e.color),typeof e.backgroundColor=="string"&&(this.livePickerBackgroundColor=T(e.backgroundColor)||e.backgroundColor)),t&&(this.suspendSelectionCaptureForColorPicker||r)){let s=window.getSelection(),o=s&&s.rangeCount>0&&this.element.contains(s.anchorNode)&&this.element.contains(s.focusNode)?this.normalizeEditorRange(s.getRangeAt(0)):null;o?(this.range=o,this.backupCurrentRange(o,{bypassNormalize:!0})):this.rangeBackup?(this.restoreLastSelection(this.rangeBackup),this.range=this.rangeBackup.cloneRange()):this.captureRange()}else this.captureRange();if(t||(this.suspendSelectionCaptureForColorPicker=!1),typeof e=="string"){let s=!!(this.range&&this.range.collapsed);if(this.customCommandHandlers.has(e))await this.customCommandHandlers.get(e)?.(this,e);else if(Object.keys(S).includes(e)){let i=S[e];e==="color"?this.wrapSelectionWithClass(S.color,"color",this.highlightColor):this.isStyleAppliedToSelection(i)?this.removeStyleFromSelection(i,e):this.wrapSelectionWithClass(i,e)}else if(["alignLeft","alignCenter","alignRight"].includes(e))this.applyAlignment(e);else if(e==="divider"){let i=document.createElement("hr");this.insertNodeAtSelection(i,!0),this.ensureCaretAfterNonTextElement(i),this.backupCurrentRange()}else if(e==="quote"){if(this.range){let a=this.getContainingQuote(this.range.startContainer);a&&(this.unwrapQuote(a),this.normalizeDocument())}let i=document.createElement("blockquote"),l=this.createEmptyParagraph();i.append(l),this.insertNodeAtSelection(i,!0),this.ensureTrailingEditableLineAfter(i),this.setSelectionAtStart(l),this.backupCurrentRange()}else if(e==="unorderedList"||e==="orderedList"){let i=document.createElement(e==="unorderedList"?"ul":"ol"),l=document.createElement("li");l.append(document.createElement("br")),i.append(l),this.insertNodeAtSelection(i,!0),this.ensureTrailingEditableLineAfter(i),this.setSelectionAtStart(l),this.backupCurrentRange()}else if(e==="image")this.imageInput.click();else{let i=T(e);i&&this.wrapSelectionWithClass(S.color,"color",i)}let o=Object.keys(S).includes(e)||!!T(e);(!s||!o)&&this.restoreLastSelection(),this.updateCommandTracker();return}if(typeof e=="object"&&e){if(["color","backgroundColor"].some(o=>o in e)){let o=this.range?this.snapshotRangeToTextOffsets(this.range):null,i=!!(this.range&&this.range.collapsed),l=(a,u)=>{if(a.backgroundColor){let c=T(a.backgroundColor)||a.backgroundColor;this.wrapSelectionWithClass(S.backgroundColor,"backgroundColor",c)}else if(a.color){let c=T(a.color)||a.color;this.wrapSelectionWithClass(S.color,"color",c)}if(!i)if(u){let c=this.restoreRangeFromTextOffsets(u);c?(this.restoreLastSelection(c),this.backupCurrentRange(c,{bypassNormalize:!0})):this.restoreLastSelection()}else this.restoreLastSelection();this.updateCommandTracker(),this.suspendSelectionCaptureForColorPicker=document.activeElement instanceof HTMLInputElement&&document.activeElement.type==="color"};if(r){l({color:e.color,backgroundColor:e.backgroundColor},o);return}l({color:e.color,backgroundColor:e.backgroundColor},o);return}else if(e.element!==void 0){let o=null,i=null;if(typeof e.element=="string"?o=document.createTextNode(e.element):X(e.element)&&(o=e.element,i=e.element,e.elementId&&(o.id=e.elementId)),!o)return;if(o instanceof HTMLElement&&e.style)for(let[a,u]of Object.entries(e.style))typeof u=="string"&&o.style.setProperty(a,u);o instanceof HTMLElement&&(o.classList.add("_custom_"),this.custom_array.push({elementId:o.id||k("custom"),element:o}));let l=o.nodeType===Node.TEXT_NODE;this.insertNodeAtSelection(o,!l),i&&this.ensureCaretAfterNonTextElement(i)}return}this.suspendSelectionCaptureForColorPicker=!1}async loadHTML(e,t=!1){if(typeof e!="string")throw new Error("html should be a string");this.setEditable(!1),this.element.innerHTML="",this.image_array=[],this.hashtag_array=[],this.urllink_array=[],this.custom_array=[];let n=document.createElement("div");n.innerHTML=e;for(let l of Array.from(n.childNodes))this.element.append(l);let r=this.element.querySelectorAll("._media_ img");for(let l of Array.from(r)){let a=l.id||k("img");l.id=a,this.image_array.push({elementId:a,source:l.getAttribute("src")||"",element:l})}let s=this.element.querySelectorAll("._hashtag_");for(let l of Array.from(s)){let a=l.id||k("hashtag");l.id=a,this.hashtag_array.push({elementId:a,tag:(l.textContent||"").replace(/^#/,""),element:l})}let o=this.element.querySelectorAll("._urllink_");for(let l of Array.from(o)){let a=l.id||k("urllink");l.id=a,this.urllink_array.push({elementId:a,url:l.textContent||"",element:l})}let i=this.element.querySelectorAll("._custom_");for(let l of Array.from(i)){let a=l.id||k("custom");l.id=a,this.custom_array.push({elementId:a,element:l})}this.normalizeDocument(),t&&this.setEditable(!0),this.element.childNodes.length===0&&this.element.append(this.createEmptyParagraph()),this.updateCommandTracker(),this.updatePlaceholderVisibility()}async export(e){this.normalizeDocument();let n={dom:this.element.cloneNode(!0),urllink:this.urlEnabled?this.urllink_array:void 0,hashtag:this.hashtagEnabled?this.hashtag_array:void 0,image:this.image_array,custom:this.custom_array,title:""};if(e){let i=e(n);n=(i instanceof Promise?await i:i)||n}let r=Array.from(n.dom.querySelectorAll(":scope > *")),s=n.title||"",o=[];for(let i of r){let l=(i.textContent||"").trim();l&&(s?o.push(l):(s=l.slice(0,200),l.length>200&&o.push(l.slice(200))))}return{html:n.dom.innerHTML,title:s.trim(),text:o.join(` `).trim(),urllink:this.urlEnabled?n.urllink:void 0,hashtag:this.hashtagEnabled?n.hashtag:void 0,image:n.image,custom:n.custom}}};0&&(module.exports={Wysiwyg4All}); //# sourceMappingURL=wysiwyg4all.module.cjs.map