import{html as e,css as t,render as i,unsafeCSS as o}from"../../lit/index.js";import{SimpleColors as a}from"../simple-colors/simple-colors.js";import{UndoManagerBehaviors as s}from"../undo-manager/undo-manager.js";import{HAXStore as n}from"./lib/hax-store.js";import{autorun as r,toJS as l}from"../../mobx/dist/mobx.esm.js";import"./lib/hax-text-editor-toolbar.js";import{encapScript as d,wipeSlot as c,generateResourceID as h,nodeToHaxElement as u,haxElementToNode as g,camelToDash as m,wrap as v,unwrap as b,ReplaceWithPolyfill as x,normalizeEventPath as N}from"../utils/utils.js";import{HaxUiBaseStyles as y}from"./lib/hax-ui-styles.js";import{I18NMixin as _}from"../i18n-manager/lib/I18NMixin.js";import"../absolute-position-behavior/absolute-position-behavior.js";import"../simple-icon/lib/simple-icons.js";import{SimpleIconsetStore as E}from"../simple-icon/lib/simple-iconset.js";import"./lib/hax-context-behaviors.js";import"./lib/hax-plate-context.js";import"../grid-plate/grid-plate.js";import"../media-image/media-image.js";import{SuperDaemonInstance as f}from"../super-daemon/super-daemon.js";Element.prototype.replaceWith||(Element.prototype.replaceWith=x),CharacterData.prototype.replaceWith||(CharacterData.prototype.replaceWith=x),DocumentType.prototype.replaceWith||(DocumentType.prototype.replaceWith=x),String.prototype.replaceAll||(String.prototype.replaceAll=function(e,t){return this.split(e).join(t)});var A=null;const T=25,S=200;class HaxBody extends(_(s(a))){static get tag(){return"hax-body"}static get styles(){return[super.styles,t`
        :host([edit-mode]),
        :host([edit-mode]) * ::slotted(*) {
          caret-color: var(--hax-ui-caret-color, auto);
        }

        hax-text-editor-toolbar {
          background-color: var(--hax-ui-background-color);
          --simple-toolbar-button-bg: var(--hax-ui-background-color);
          --simple-picker-options-background-color: var(
            --hax-ui-background-color
          );
          --simple-picker-option-active-background-color: var(
            --hax-ui-color-accent
          );
          --simple-picker-option-active-color: var(--hax-tray-text-color);
          --simple-picker-color-active: var(--hax-tray-text-color);
          --simple-picker-color: var(--hax-tray-text-color);
        }
        :host([edit-mode][tray-status="full-panel"]) {
          opacity: 0.2;
          pointer-events: none;
        }
        :host {
          display: block;
          position: relative;
          min-height: 32px;
          min-width: 32px;
          outline: none;
          --hax-contextual-action-text-color: var(--hax-ui-background-color);
          --hax-contextual-action-hover-color: var(--hax-ui-color-accent);
          --hax-contextual-action-color: var(--hax-ui-color-accent-secondary);
          --hax-body-editable-outline: 1px solid
            var(--hax-ui-disabled-color, #ddd);
          --hax-body-active-outline-hover: 2px solid
            var(--hax-ui-color-faded, #444);
          --hax-body-active-outline: 2px solid var(--hax-ui-color-focus, #000);
          --hax-body-active-drag-outline: 1px solid
            var(--hax-ui-color-accent, #009dc7);
          --hax-body-target-background-color: var(
            --hax-ui-background-color-accent
          );
          --hax-body-possible-target-background-color: inherit;
        }
        #topcontext {
          z-index: calc(var(--hax-ui-focus-z-index) - 2);
          min-width: 280px;
        }
        #topcontextmenu {
          width: auto;
          max-width: 100%;
          position: absolute;
          bottom: 0;
          margin-bottom: 10px;
          margin-left: -10px;
        }
        .hax-context-menu {
          visibility: hidden;
          opacity: 0;
          z-index: -1;
          pointer-events: none;
          transition: 0.3s all ease-in-out;
        }
        .hax-context-menu:hover {
          z-index: calc(var(--hax-ui-focus-z-index) + 1);
        }
        .hax-context-visible,
        .hax-context-menu-active {
          display: flex;
          pointer-events: auto;
          visibility: visible;
          z-index: 1;
          opacity: 1;
        }
        /* this helps ensure editable-table doesn't try internal text editor; all others should */
        :host([edit-mode])
          #bodycontainer
          ::slotted(*[contenteditable][data-hax-ray]:not(editable-table)) {
          -webkit-appearance: textfield;
          cursor: text;
          -moz-user-select: text;
          -khtml-user-select: text;
          -webkit-user-select: text;
          -o-user-select: text;
        }
        :host([edit-mode]) #bodycontainer ::slotted(*[data-hax-ray]:hover) {
          cursor: pointer;
          outline: 2px solid var(--hax-ui-color-hover, #0001);
          transition: 0.2s outline-width ease-in-out;
          outline-offset: 8px;
        }

        :host([edit-mode])
          #bodycontainer
          ::slotted(
            [contenteditable][data-hax-ray]:empty:not(
                [data-instructional-action]
              )
          )::before {
          content: attr(data-hax-ray);
          opacity: 0.2;
          transition: 0.6s all ease-in-out;
        }

        :host([edit-mode])
          #bodycontainer
          ::slotted(
            p[contenteditable][data-hax-ray][data-hax-active]:empty:not(
                [data-instructional-action]
              )
          )::before {
          content: "Type '/' for Merlin";
          opacity: 0.4;
        }

        :host([edit-mode])
          #bodycontainer
          ::slotted(
            [contenteditable][data-hax-ray]:hover:empty:not(
                [data-instructional-action]
              )
          )::before {
          opacity: 0.4;
          cursor: text;
        }

        :host([edit-mode])
          #bodycontainer
          ::slotted(
            [contenteditable][data-hax-ray]:empty:focus:not(
                [data-instructional-action]
              )
          )::before {
          content: "";
        }

        :host([edit-mode]) #bodycontainer ::slotted([data-hax-active]),
        :host([edit-mode]) #bodycontainer ::slotted(*.hax-hovered) {
          outline-offset: 8px;
        }
        :host([edit-mode]) #bodycontainer ::slotted(img[contenteditable]) {
          max-width: 100%;
        }
        :host([edit-mode]) #bodycontainer ::slotted(*[contenteditable]) {
          caret-color: var(--hax-ui-caret-color, auto);
        }
        :host([edit-mode]) #bodycontainer ::slotted(*.blinkfocus) {
          outline: 2px solid var(--hax-contextual-action-hover-color);
        }
        :host([edit-mode]) #bodycontainer ::slotted(*[data-hax-lock]) {
          opacity: 0.5;
          transition: 0.3s all ease-in-out;
        }
        :host([edit-mode]) #bodycontainer ::slotted(*[data-hax-lock]:hover) {
          opacity: 0.9;
        }
        :host([edit-mode]) #bodycontainer ::slotted(*[data-hax-lock])::after {
          width: 28px;
          height: 28px;
          content: "";
          display: flex;
          float: right;
          z-index: 1;
          position: relative;
          background-position: center;
          background-repeat: no-repeat;
          background-color: #fffafa;
        }
        :host([edit-mode])
          #bodycontainer
          ::slotted(*:not([data-hax-layout]):hover) {
          outline: var(--hax-body-active-outline-hover);
          caret-color: var(--hax-ui-caret-color, auto);
        }
        :host(.hax-add-content-visible[edit-mode])
          #bodycontainer
          ::slotted([data-hax-active]) {
          margin-bottom: 30px;
        }
        :host([edit-mode]) #bodycontainer ::slotted([data-hax-active]:hover) {
          cursor: text !important;
          caret-color: var(--hax-ui-caret-color, auto);
          outline: var(--hax-body-active-outline-hover);
        }
        :host([edit-mode])
          #bodycontainer
          ::slotted(*:not([data-hax-layout]) [data-hax-active]:hover) {
          cursor: text !important;
          caret-color: var(--hax-ui-caret-color, auto);
          outline: var(--hax-body-active-outline-hover);
        }
        :host([edit-mode])
          #bodycontainer
          ::slotted([data-hax-active][contenteditable]) {
          outline: var(--hax-body-active-outline) !important;
          caret-color: var(--hax-ui-caret-color, auto);
        }
        :host([edit-mode]) #bodycontainer ::slotted(hr[contenteditable]) {
          height: 2px;
          background-color: #eeeeee;
          padding-top: 4px;
          padding-bottom: 4px;
        }
        /** Fix to support safari as it defaults to none */
        :host([edit-mode]) #bodycontainer ::slotted(*[contenteditable]) {
          -webkit-user-select: text;
          cursor: pointer;
        }

        :host([edit-mode])
          #bodycontainer
          ::slotted(*[contenteditable]::-moz-selection),
        :host([edit-mode])
          #bodycontainer
          ::slotted(*[contenteditable] *::-moz-selection) {
          background-color: var(--hax-body-highlight, #ffffac);
          color: black;
        }
        :host([edit-mode])
          #bodycontainer
          ::slotted(*[contenteditable]::selection),
        :host([edit-mode])
          #bodycontainer
          ::slotted(*[contenteditable] *::selection) {
          background-color: var(--hax-body-highlight, #ffffac);
          color: black;
        }
        #bodycontainer {
          -webkit-user-select: text;
          user-select: text;
        }
        absolute-position-behavior:not(:defined),
        .hax-context-menu:not(:defined) {
          display: none;
        }
        /* drag and drop */
        :host([edit-mode][hax-mover]) #bodycontainer ::slotted(*)::before {
          background-color: var(--hax-body-possible-target-background-color);
          content: " ";
          width: 100%;
          display: block;
          position: relative;
          margin: -12px 0 0 0;
          z-index: 2;
          height: 12px;
          transition: 0.3s all ease-in-out;
        }
        :host([edit-mode][hax-mover]) #bodycontainer ::slotted(img) {
          outline: var(--hax-body-editable-outline);
        }
        :host([edit-mode]) #bodycontainer ::slotted(img.hax-hovered),
        :host([edit-mode]) #bodycontainer ::slotted(*.hax-hovered)::before {
          background-color: var(--hax-body-target-background-color) !important;
        }
        :host([edit-mode]) #bodycontainer ::slotted(img.hax-hovered) {
          border-top: 8px
            var(--hax-contextual-action-hover-color, var(--hax-ui-color-accent));
          margin-top: -8px;
        }
        [hidden],
        :host([hidden]),
        #textcontextmenu.not-text {
          display: none !important;
        }
        /** This is mobile layout for controls */
        @media screen and (max-width: 800px) {
          .hax-context-menu {
            height: 0px;
          }
          .hax-context-visible {
            height: auto;
          }

          :host([edit-mode]) #bodycontainer,
          :host([edit-mode]) #bodycontainer[element-align="left"],
          :host([edit-mode]) #bodycontainer[element-align="right"] {
            margin: calc(100px + var(--hax-tray-menubar-min-height)) 0 0 0;
          }
        }

        @media screen and (min-color-index: 0) and(-webkit-min-device-pixel-ratio:0) {
          /*
            Define here the CSS styles applied only to Safari browsers
            (any version and any device) via https://solvit.io/bcf61b6
          */
          :host([edit-mode][hax-mover]) #bodycontainer ::slotted(*) {
            outline: var(--hax-body-editable-outline);
            background-color: var(--hax-body-possible-target-background-color);
          }
          :host([edit-mode]) #bodycontainer ::slotted(*.hax-hovered) {
            background-color: var(
              --hax-body-target-background-color
            ) !important;
            outline: var(--hax-body-active-outline);
          }
        }
      `]}constructor(){if(super(),this._useristyping=!1,this.__ignoreActive=!1,this.__dragMoving=!1,this.___moveLock=!1,this.viewSourceToggle=!1,this.editMode=!1,this.haxMover=!1,this.activeNode=null,this.__lockIconPath=E.getIcon("icons:lock"),this.part="hax-body",this.t={addContent:"Add Content"},this.timesClickedArrowDown=0,this.timesClickedArrowUp=0,this.registerLocalization({context:this,namespace:"hax"}),!globalThis.HaxUiStyles){globalThis.HaxUiStyles=globalThis.document.createElement("div");let e=globalThis.document.createElement("style"),t=y.map((e=>e.cssText)).join("");e.setAttribute("data-hax",!0),e.setAttribute("type","text/css"),e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t)),globalThis.document.body.appendChild(e)}this.polyfillSafe=n.computePolyfillSafe(),this.addEventListener("place-holder-replace",this.replacePlaceholder.bind(this)),this.addEventListener("focusin",this._focusIn.bind(this)),this.addEventListener("mousemove",this._mouseMove.bind(this)),this.addEventListener("mouseleave",this._mouseLeave.bind(this)),this.addEventListener("touchstart",this._mouseMove.bind(this),{passive:!0}),this.addEventListener("mousedown",this._mouseDown.bind(this)),this.addEventListener("mouseup",this._mouseUp.bind(this)),this.addEventListener("dragenter",this.dragEnterBody.bind(this)),this.addEventListener("dragend",this.dragEndBody.bind(this)),this.addEventListener("drop",this.dropEvent.bind(this)),r((()=>{this.editMode=l(n.editMode)})),r((()=>{this.elementAlign=l(n.elementAlign)})),r((()=>{this.trayStatus=l(n.trayStatus),this.trayDetail=l(n.trayDetail)})),r((()=>{this.activeNode=l(n.activeNode),this.activeNode&&this.activeNode.setAttribute&&this.activeNode.setAttribute("data-hax-active","data-hax-active")})),r((()=>{l(n.activeEditingElement)}))}get isGridActive(){return n.isGridPlateElement(activeNode)}dragEndBody(e){this.__manageFakeEndCap(!1),n._lockContextPosition=!1,this.querySelectorAll(".hax-hovered").forEach((e=>{e.classList.remove("hax-hovered")}))}_mouseLeave(e){this.editMode&&n.ready&&(clearTimeout(this.__mouseQuickTimer),clearTimeout(this.__mouseTimer),this.__activeHover=null)}_mouseMove(e){if(this.editMode&&n.ready){var t=N(e);clearTimeout(this.__mouseQuickTimer),this.__mouseQuickTimer=setTimeout((()=>{this.__activeHover&&this.__activeHover!=t[0].closest("[data-hax-ray]:not(li)")&&(this.__activeHover=null)}),300),clearTimeout(this.__mouseTimer),this.__mouseTimer=setTimeout((()=>{let e=t[0].closest("[data-hax-ray]:not(li)");if(e)this.__activeHover=e;else if(t[0].closest("[data-move-order]")&&t[3]&&t[3].closest("[data-hax-layout]"))if(t[0].closest("[data-move-order]:not(.has-nodes")){if(this.__addAbove=!1,this.__slot=t[0].closest("[data-move-order]").getAttribute("id").replace("col","col-"),0==t[0].closest("[data-move-order]").parentNode.parentNode.host.children.length){let e=globalThis.document.createElement("p");t[0].closest("[data-move-order]").parentNode.parentNode.host.appendChild(e)}this.__activeHover=t[0].closest("[data-move-order]").parentNode.parentNode.host.children[0]}else this.__activeHover=t[0].closest("[data-move-order]").parentNode.parentNode.host;else t[0].closest("#bodycontainer")&&(this.__activeHover=null)}),400)}}_mouseDown(e){if(this.editMode){this.__mouseDown=!0;let t=e.target;t.closest("[draggable]")?t=t.closest("[draggable]"):t.closest("[slot]")?t=t.closest("[slot]"):t.closest("[data-hax-ray]")?t=t.closest("[data-hax-ray]"):t.closest("[contenteditable]")?t=t.closest("[contenteditable]"):n.validTagList.includes(t.tagName.toLowerCase())||"HAX-BODY"===t.tagName||t.haxUIElement||console.warn(t),!t.haxUIElement&&this.__focusLogic(t)&&(n.haxTray.trayDetail="content-edit",e.stopPropagation(),e.stopImmediatePropagation())}}_mouseUp(e){setTimeout((()=>{this.__mouseDown=!1}),0),this._useristyping=!1,clearTimeout(A),this.__manageFakeEndCap(!1)}scrollerFixclickEvent(e){this._useristyping=!1,this.positionContextMenus(),clearTimeout(A)}blurEvent(e){this.editMode&&n.activeEditingElement}__manageFakeEndCap(e=!0){if(e&&!this.__fakeEndCap){let e=globalThis.document.createElement("fake-hax-body-end");e.style.width="100%",e.style.height="20px",e.style.zIndex="2",e.style.display="block",this.__fakeEndCap=e,this.haxMover=!0,this.appendChild(this.__fakeEndCap),this.__applyNodeEditableState(this.__fakeEndCap,!0)}else!e&&this.__fakeEndCap&&(this.__fakeEndCap.remove(),this.haxMover=!1,this.__fakeEndCap=null)}dragEnterBody(e){this.hideContextMenus(),this._useristyping=!1,this.__manageFakeEndCap(!0)}revealMenuIfHidden(e){this._useristyping=!1,this.positionContextMenus()}render(){return e`
      <style id="hax-body-style-element"></style>
      <div
        id="bodycontainer"
        class="ignore-activation"
        element-align="${this.elementAlign||"left"}"
      >
        <slot id="body"></slot>
      </div>
      <absolute-position-behavior
        id="topcontext"
        fit-to-visible-bounds
        justify
        position="top"
        allow-overlap
        auto
        sticky
        data-node-type="${this.activeNode?this.viewSourceToggle?this.activeNode.parentNode.tagName:this.activeNode.tagName:""}"
        .target="${this.activeNode?this.viewSourceToggle?this.activeNode.parentNode:this.activeNode:globalThis.document.body}"
        .trayStatus="${this.trayStatus}"
        ?hidden="${!this.activeNode}"
      >
        <div id="topcontextmenu" @mouseenter="${this.revealMenuIfHidden}">
          <hax-plate-context
            always-expanded
            id="platecontextmenu"
            class="hax-context-menu ignore-activation"
            .activeNode="${this.activeNode}"
            .trayDetail="${this.trayDetail}"
            .trayStatus="${this.trayStatus}"
            ?viewSource="${this.viewSourceToggle}"
            ?canMoveElement="${this.canMoveElement}"
          ></hax-plate-context>
          <hax-text-editor-toolbar
            id="textcontextmenu"
            class="hax-context-menu ignore-activation ${this.calcClasses(this.activeNode)}"
            .activeNode="${this.activeNode}"
            show="always"
          >
          </hax-text-editor-toolbar>
        </div>
      </absolute-position-behavior>
    `}calcClasses(e){let t="not-text";return e&&e.getAttribute&&!e.getAttribute("data-hax-lock")&&e.parentNode&&e.parentNode.getAttribute&&!e.parentNode.getAttribute("data-hax-lock")&&n.isTextElement(e)&&!n.isSingleSlotElement(e)&&(t="is-text"),t}static get properties(){return{...super.properties,_useristyping:{type:Boolean},haxMover:{type:Boolean,attribute:"hax-mover",reflect:!0},editMode:{type:Boolean,reflect:!0,attribute:"edit-mode"},elementAlign:{type:String,reflect:!0,attribute:"element-align"},trayDetail:{type:String,reflect:!0,attribute:"tray-detail"},trayStatus:{type:String,reflect:!0,attribute:"tray-status"},activeNode:{type:Object},canMoveElement:{type:Boolean},viewSourceToggle:{type:Boolean,reflect:!0}}}HAXBODYStyleSheetContent(){let e=[];return e.push(t`
      :host([edit-mode]) #bodycontainer ::slotted(*[data-hax-lock])::after {
        background-image: url("${o(this.__lockIconPath)}");
      }
    `),e}firstUpdated(e){i(this.HAXBODYStyleSheetContent(),this.shadowRoot.querySelector("#hax-body-style-element")),this.dispatchEvent(new CustomEvent("hax-register-body",{bubbles:!0,cancelable:!0,composed:!0,detail:this}));try{globalThis.document.execCommand("enableObjectResizing",!1,!1),globalThis.document.execCommand("defaultParagraphSeparator",!1,"p")}catch(e){console.warn(e)}this.contextMenus={text:this.shadowRoot.querySelector("#textcontextmenu"),plate:this.shadowRoot.querySelector("#platecontextmenu"),parent:this.shadowRoot.querySelector("#topcontext")},this.shadowRoot.querySelector("slot").addEventListener("mouseup",(e=>{this.editMode&&setTimeout((()=>{const e=n.getSelection();n._tmpSelection=e,n.haxSelectedText=e.toString();try{const e=n.getRange();e.cloneRange&&(n._tmpRange=e.cloneRange())}catch(e){console.warn(e)}}),10)})),this.editMode=n.editMode,this.__tabTrap=!1,this.ready=!0,super.firstUpdated&&super.firstUpdated(e)}async updated(e){super.updated&&super.updated(e),e.forEach((async(e,t)=>{"editMode"==t&&void 0!==e&&setTimeout((async()=>{this.__ignoreActive=!0,await this._editModeChanged(this[t],e),setTimeout((()=>{this.__ignoreActive=!1}),100)}),0),"_useristyping"==t&&this[t]&&this.hideContextMenus(),"activeNode"==t&&this.ready&&void 0!==e&&await this._activeNodeChanged(this[t],e)}))}_toggleNodeLocking(e){e.detail.lock?(this.contextMenus.plate.disableDuplicate=!0,this.contextMenus.plate.disableOps=!0,this.contextMenus.plate.disableItemOps=!0,this.contextMenus.plate.canMoveElement=!1,e.detail.node.removeAttribute("contenteditable"),this.removeAttribute("contenteditable")):(this.contextMenus.plate.disableDuplicate=!1,this.contextMenus.plate.disableOps=!1,this.contextMenus.plate.disableItemOps=!1,this.contextMenus.plate.canMoveElement=this.canMoveElement,e.detail.node.setAttribute("contenteditable",!0),this.setAttribute("contenteditable",!0)),this.requestUpdate()}_keepContextVisible(e=null){this.editMode&&(clearTimeout(this.__contextVisibleLock),this.__contextVisibleLock=setTimeout((()=>{let e=!1;this.contextMenus.plate.classList.contains("hax-context-visible")&&(e=this.contextMenus.plate),e&&this.positionContextMenus()}),100))}_onKeyUp(e){if(["ArrowUp","ArrowDown"].includes(e.key)&&this.activeNode&&n.isTextElement(this.activeNode)&&!f.opened){let t=e.key;if(this[`timesClicked${t}`]++,this[`timesClicked${t}`]>=2&&this.activeNode===this.prevKeyActiveNode)if("ArrowUp"===t){if(this.activeNode.previousElementSibling&&"PAGE-BREAK"===this.activeNode.previousElementSibling.tagName)this.haxInsert("p","",{},this.activeNode.previousElementSibling);else if(this.activeNode.parentNode!==this&&this.activeNode.parentNode.previousElementSibling&&"PAGE-BREAK"===this.activeNode.parentNode.previousElementSibling.tagName)this.haxInsert("p","",{},this.activeNode.parentNode.previousElementSibling);else if(!this.activeNode.previousElementSibling&&this.activeNode.parentNode===this){let e=globalThis.document.createElement("p");this.insertBefore(e,this.activeNode)}}else this.activeNode.nextElementSibling||this.children[this.children.length-1]!==this.activeNode?this.activeNode.parentNode&&this.activeNode.parentNode!==this&&!this.activeNode.parentNode.nextElementSibling&&this.children[this.children.length-1]===this.activeNode.parentNode&&this.haxInsert("p","",{},this.activeNode.parentNode):this.haxInsert("p","",{}),this[`timesClicked${t}`]=0,this.prevKeyActiveNode=null;else this.prevKeyActiveNode=this.activeNode;setTimeout((()=>{this[`timesClicked${t}`]=0,this.prevKeyActiveNode=null}),200)}}_onKeyDown(e){if(this.editMode&&"HAX-TRAY"!==globalThis.document.activeElement.tagName&&"BODY"!==globalThis.document.activeElement.tagName&&"SIMPLE-MODAL"!==globalThis.document.activeElement.tagName&&this.getAttribute("contenteditable")){if(this.__dropActiveVisible(),this.__manageFakeEndCap(!1),null!=n.getSelection().anchorNode)switch(e.key){case"Z":case"z":e.ctrlKey&&(e.shiftKey?this.redo():this.undo(),e.detail.keyboardEvent&&(e.detail.keyboardEvent.preventDefault(),e.detail.keyboardEvent.stopPropagation(),e.detail.keyboardEvent.stopImmediatePropagation()),e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation());break;case"Tab":this._useristyping=!0,n.isTextElement(this.activeNode)&&(e.detail.keyboardEvent&&(e.detail.keyboardEvent.preventDefault(),e.detail.keyboardEvent.stopPropagation(),e.detail.keyboardEvent.stopImmediatePropagation()),e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),e.shiftKey?this._tabBackKeyPressed():this._tabKeyPressed());break;case"Enter":if(this._useristyping=!0,this.activeNode&&(this.__slot=this.activeNode.getAttribute("slot")),this.activeNode&&"P"===this.activeNode.tagName&&["1","#","`",">","-"].includes(this.activeNode.textContent[0])){const e=this.activeNode.textContent.replaceAll(/ /g," ");this.keyboardShortCutProcess(e)}break;case"Backspace":case"Delete":this.activeNode&&""==this.activeNode.textContent&&this.activeNode.previousElementSibling&&this.activeNode.previousElementSibling.tagName&&(["TABLE","EDITABLE-TABLE","IFRAME-LOADER","IFRAME","WEBVIEW"].includes(this.activeNode.previousElementSibling.tagName)||"PAGE-BREAK"===this.activeNode.previousElementSibling.tagName&&2===this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0}).length&&this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0})[1]===this.activeNode)&&e.preventDefault(),this._useristyping=!0,this.__delHit=!0,this.querySelectorAll("[data-hax-active]").forEach((e=>e.classList.remove)),setTimeout((()=>{const e=n.getSelection();n._tmpSelection=e,n.haxSelectedText=e.toString();const t=n.getRange();t.commonAncestorContainer&&this.activeNode!==t.commonAncestorContainer&&"function"==typeof t.commonAncestorContainer.focus?"HAX-BODY"!==t.commonAncestorContainer.tagName&&this.__focusLogic(t.commonAncestorContainer,!1):t.commonAncestorContainer&&t.commonAncestorContainer.parentNode&&this.activeNode!==t.commonAncestorContainer.parentNode&&"function"==typeof t.commonAncestorContainer.parentNode.focus&&("HAX-BODY"!==t.commonAncestorContainer.parentNode.tagName?this.__focusLogic(t.commonAncestorContainer.parentNode,!1):this.__focusLogic(t.commonAncestorContainer,!1))}),100);break;case"Escape":this._useristyping=!0;break;case"/":const t=n.getRange();this.activeNode&&n.isTextElement(this.activeNode)&&""==t.commonAncestorContainer.textContent.trim()&&(e.preventDefault(),f.mini=!0,f.activeRange=t,f.activeSelection=n.getSelection(),f.activeNode=t.commonAncestorContainer,f.runProgram(t.commonAncestorContainer.textContent.trim(),"*"),f.open());break;case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":this._useristyping=!0,this.querySelectorAll("[data-hax-active]").forEach((e=>e.classList.remove)),setTimeout((()=>{const e=n.getSelection();n._tmpSelection=e,n.haxSelectedText=e.toString();const t=n.getRange();t.commonAncestorContainer&&this.activeNode!==t.commonAncestorContainer&&"function"==typeof t.commonAncestorContainer.focus?"HAX-BODY"!==t.commonAncestorContainer.tagName&&this.__focusLogic(t.commonAncestorContainer,!1):t.commonAncestorContainer&&t.commonAncestorContainer.parentNode&&this.activeNode!==t.commonAncestorContainer.parentNode&&"function"==typeof t.commonAncestorContainer.parentNode.focus&&("HAX-BODY"!==t.commonAncestorContainer.parentNode.tagName?this.__focusLogic(t.commonAncestorContainer.parentNode,!1):this.__focusLogic(t.commonAncestorContainer,!1))}),0);break;default:this._useristyping=!0,setTimeout((()=>{if(this.activeNode&&"P"===this.activeNode.tagName&&["1","#","`",">","-"].includes(this.activeNode.textContent[0])){const e=this.activeNode.textContent.replaceAll(/ /g," ");" "===e[e.length-1]&&this.keyboardShortCutProcess(e)}}),0)}}}keyboardShortCutProcess(e){if(n.keyboardShortcuts[e.replace(" ","")]){let t=g(n.keyboardShortcuts[e.replace(" ","")]);this.haxReplaceNode(this.activeNode,t),this.__focusLogic(t),"HR"===t.tagName&&this.haxInsert("p","",{})}}setActiveNode(e,t=!1){e&&this.editMode&&this.activeNode&&(n.isTextElement(this.activeNode)||t)&&(n.activeNode=e,clearTimeout(this.__positionContextTimer),this.__positionContextTimer=setTimeout((()=>{this.__addActiveVisible(),this.positionContextMenus()}),2e3))}elementMidViewport(){const e=this.activeNode.getBoundingClientRect().y;return e<0&&e>-1*this.activeNode.offsetHeight+140}replacePlaceholder(e){if("text"===e.detail){let e=globalThis.document.createElement("p");this.haxReplaceNode(this.activeNode,e),this.__focusLogic(e),this.activeNode.parentNode&&this.activeNode.parentNode.setAttribute("contenteditable",!0)}else this.replaceElementWorkflow()}async canTansformNode(e=null){return await this.replaceElementWorkflow(e,!0).length>0}async insertElementWorkflow(e=null,t=!1){}get primitiveTextBlocks(){return["p","div","pre","h1","h2","h3","h4","h5","h6"]}getAllSlotConfig(e){if(!e)return;let t=this.getParentGrid(e);return t&&t.tag?this.getSlotConfig(n.elementList[t.tag],slot):void 0}getParentGrid(e){return((e=e||this.activeNode)?e.slot:void 0)?u(e.parentNode):void 0}getSlotConfig(e="",t={}){let i=t.settings,o=i?Object.keys(i||{}).map((t=>i[t].filter((t=>!(!t.slot||e&&t.slot!==e))))).flat():void 0;return o&&o.length>0?o[0]:void 0}async replaceElementWorkflow(e=null,t=!1){null==e&&(e=this.activeNode);let i=await u(e,null);if(!i)return;let o=!1,a=(e||{}).slot,s=this.getParentGrid(e);this.primitiveTextBlocks.includes(i.tag)&&(o=!0);var r=i.content?{innerHTML:i.content}:{};if(void 0!==n.elementList[i.tag]&&!1!==n.elementList[i.tag].gizmo&&void 0!==n.elementList[i.tag].gizmo.handles&&n.elementList[i.tag].gizmo.handles.length>0){let e=n.elementList[i.tag].gizmo;for(var l=0;l<e.handles.length;l++)for(var d in i.properties.innerHTML&&(r.innerHTML=i.properties.innerHTML),e.handles[l])"type"!==d&&void 0!==i.properties[e.handles[l][d]]&&(r[d]=i.properties[e.handles[l][d]])}let c=n.guessGizmo("*",r,o),h=s?this.getSlotConfig(a,n.elementList[s.tag]):void 0,g=s&&"grid-plate"===s.tag?["grid-plate"]:h?h.excludedSlotWrappers:void 0,m=h?h.allowedSlotWrappers:void 0;if((g||m)&&(c=c.filter((e=>!g.includes(e.tag)&&(!m||m.includes(e.tag))))),c.length>0){let i=e.tagName.toLowerCase(),o=i.replace("-"," ");void 0!==n.elementList[i]&&!1!==n.elementList[i].gizmo&&(o=n.elementList[i].gizmo.title),t||(n.activePlaceHolder=this.activeNode,n.haxAppPicker.presentOptions(c,"__convert",`Change ${o} to...`,"gizmo"))}else t||n.toast("Sorry, this can not be transformed!",5e3);return c}haxClearBody(e=!0){let t=!0;e&&(t=prompt("Are you sure you want to delete all content?")),t&&c(this)}haxInsert(e,t,i={},o=this.activeNode,a=!1){var s=globalThis.document.createElement(e);s.innerHTML=t;const r=s.cloneNode(!0);for(var l in i){let e=m(l);""!=e&&i.hasOwnProperty(l)&&(!0===i[l]?r.setAttribute(e,e):!1===i[l]?r.removeAttribute(e):null!=i[l]&&i[l].constructor===Array||null!=i[l]&&i[l].constructor===Object?r.properties&&r.properties[l].readOnly||(r.set?r.set(e,i[l]):r[e]=i[l]):r.setAttribute(e,i[l]))}return null!==n.activePlaceHolder&&void 0!==n.activePlaceHolder.style?(r.style.width=n.activePlaceHolder.style.width,r.style.float=n.activePlaceHolder.style.float,r.style.margin=n.activePlaceHolder.style.margin,r.style.display=n.activePlaceHolder.style.display,this.haxReplaceNode(n.activePlaceHolder,r),n.activePlaceHolder=null):o&&o.parentNode?this.__isLayout(o.parentNode)?(null!=o.getAttribute("slot")&&r.setAttribute("slot",o.getAttribute("slot")),this.__addAbove?o.parentNode.insertBefore(r,o):o.parentNode.insertBefore(r,o.nextElementSibling)):o.parentNode&&o.parentNode.nextElementSibling?o.parentNode.nextElementSibling.parentNode.insertBefore(r,o.parentNode.nextElementSibling):o.parentNode&&o.nextElementSibling?this.__addAbove?o.parentNode.insertBefore(r,o):o.parentNode.insertBefore(r,o.nextElementSibling):o.parentNode&&o.parentNode.children[o.parentNode.children.length-1]===o?this.__addAbove?o.parentNode.insertBefore(r,o):o.parentNode.appendChild(r):o.parentNode?o.parentNode.insertBefore(r,o):this.appendChild(r):this.appendChild(r),this.contextMenus.text.hasSelectedText=!1,setTimeout((()=>{this.__focusLogic(r),this.scrollHere(r)}),0),r}async haxToContent(){this.hideContextMenus();var e=this.activeNode;n.activeNode=null;let t="slot"===this.shadowRoot.querySelector("#body").localName?this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0}):[];for(var i="",o=0;o<t.length;o++)if(this._validElementTest(t[o],!0))this.__applyDragDropState(t[o],!1),t[o].classList.remove("hax-hovered"),t[o].removeAttribute("contenteditable"),i+=await n.nodeToContent(t[o]),this.__isLayout(t[o])&&this._applyContentEditable(this.editMode,t[o]);else if(8===t[o].nodeType)i+="\x3c!-- "+t[o].textContent+" --\x3e";else if(t[o].haxUIElement&&t[o].children&&t[o].children[0]){let e=await n.runHook(t[o],"activeElementChanged",[this.activeNode,!1]);e&&e!==t[o]?i+=await n.nodeToContent(e):i+=await n.nodeToContent(t[o].children[0])}else 1!==t[o].nodeType&&void 0!==t[o].textContent&&"undefined"!==t[o].textContent?i+=t[o].textContent:console.warn(t[o]);if(i=(i=(i=(i=(i=(i=(i=(i=(i=(i=i.replace(/\scontenteditable=\"false\"/g,"")).replace(/\scontenteditable/g,"")).replace(/\sdraggable/g,"")).replace(/\sdata-hax-ray="(\s|.)*?"/gim,"")).replace(/\sdata-hax-grid="(\s|.)*?"/gim,"")).replace(/\sdata-hax-layout="(\s|.)*?"/gim,"")).replace(/\sdata-hax-active="(\s|.)*?"/gim,"")).replace(/ class=""/gim,"")).replace(/ contenteditable="(\s|.)*?"/gim,"")).replace(/&nbsp;/gm," "),this.parentNode.tagName){let e=this.parentNode.tagName.toLowerCase(),t="style-scope "+e+" x-scope",a=new RegExp(t,"g");i=i.replace(a,""),t="style-scope "+e,a=new RegExp(t,"g"),i=i.replace(a,""),t="x-scope "+e+"-0",a=new RegExp(t,"g"),i=i.replace(a,"");let s=n.validTagList;for(var o in s)t="style-scope "+s[o],a=new RegExp(t,"g"),i=i.replace(a,""),t="x-scope "+s[o]+"-0 ",a=new RegExp(t,"g"),i=i.replace(a,""),t="x-scope "+s[o]+"-0",a=new RegExp(t,"g"),i=i.replace(a,"")}return i=(i=i.replace(/\sclass=\"\"/g,"")).replace(/\sclass=\"\s\"/g,""),this._applyContentEditable(this.editMode),n.activeNode=e,i=d(i)}async haxDuplicateNode(e){let t=await u(e,null);n.testHook(e,"preProcessInsertContent")&&(t=await n.runHook(e,"preProcessInsertContent",[t,this.activeNode])),t.content==t.properties.innerHTML&&delete t.properties.innerHTML;var i=g({tag:t.tag,content:t.content,properties:t.properties});return"webview"===i.tagName.toLowerCase()&&n._isSandboxed&&void 0!==i.guestinstance&&delete i.guestinstance,null!==e?e.parentNode.insertBefore(i,e.nextSibling):e.parentNode.appendChild(i),n.activeNode=i,!0}hideContextMenus(e=!0){clearTimeout(A),clearTimeout(this.__contextVisibleLock),clearTimeout(this.__positionContextTimer),this._hideContextMenu(this.contextMenus.text),this.__activeHover=null,e&&this._hideContextMenu(this.contextMenus.plate)}positionContextMenus(e=this.activeNode){if(e&&e.tagName&&this.ready&&!this._useristyping){let t=e.tagName.toLowerCase();n.elementList&&n.elementList[t]&&n.elementList[t].contentEditable&&null===e.getAttribute("data-hax-lock")&&e.parentNode&&null===e.parentNode.getAttribute("data-hax-lock")?e.setAttribute("contenteditable",!0):e.removeAttribute("contenteditable"),clearTimeout(this.__positionContextTimer),this.__positionContextTimer=setTimeout((()=>{if(!n._lockContextPosition){let t=e.tagName.toLowerCase();n._isSandboxed&&"webview"===t&&(t="iframe"),e&&"PAGE-BREAK"!==e.tagName?this._showContextMenu(this.contextMenus.plate):this._hideContextMenu(this.contextMenus.plate);let i=n.elementList[t];void 0===i||n.isTextElement(e)?this._showContextMenu(this.contextMenus.text):(this._hideContextMenu(this.contextMenus.text),i.element=e);(i||{}).gizmo;let o=i&&i.gizmo&&(i.gizmo.handles||[]).filter((e=>"inline"===(e||{}).type)).length>0;i&&"core"!=i.editingElement?setTimeout((()=>{(e&&e.parentNode||!o)&&(this.canMoveElement=!0)}),250):this.activeNode&&("LI"===this.activeNode.tagName||this._HTMLInlineTextDecorationTest(this.activeNode))?this.canMoveElement=!1:this.canMoveElement=!0}this.contextMenus.parent.setPosition()}),50)}}__addActiveVisible(){for(var e in this.contextMenus)("add"!=e||this.__activeHover)&&this.contextMenus[e].classList.add("hax-context-menu-active")}__dropActiveVisible(){for(var e in this.contextMenus)this.contextMenus[e].classList.remove("hax-context-menu-active");this.__activeHover=null}haxMoveGridPlate(e,t=1){this.___moveLock=!0;let i=e?e.parentNode:void 0,o=t>0?e.nextElementSibling:e.previousElementSibling,a=this.__layoutSlots(i)||[],s=e.getAttribute("slot"),r=s?a.indexOf(s):-1,l=a[r+t];!o||s&&o.getAttribute("slot");return!o||s&&s!==o.getAttribute("slot")?l?e.setAttribute("slot",l):e&&i&&i!==this&&(o=t>0?i.nextElementSibling:i,l=i.getAttribute("slot"),o&&(i.parentNode.insertBefore(e,o),l&&e.setAttribute("slot",l))):i.insertBefore(e,t>0?o.nextElementSibling:o),setTimeout((()=>{n.activeNode=e,this.scrollHere(e),this.__focusLogic(e)}),100),!0}async haxGridPlateOps(e=!0,t="right",i=this.activeNode){"GRID-PLATE"!==i.tagName&&"GRID-PLATE"===i.parentNode.tagName&&(i=i.parentNode);let o=!1;if("GRID-PLATE"===i.tagName){if(e)switch(i.layout){case"2-1":case"3-1":i.layout="2-1-1",o=!0;break;case"1-2":i.layout="1-2-1",o=!0;break;case"1-3":i.layout="1-1-2",o=!0;break;case"2-1-1":case"1-2-1":case"1-1-2":case"1-1-1":i.layout="1-1-1-1",o=!0;break;case"1":i.layout="1-1",o=!0;break;case"1-1":i.layout="1-1-1",o=!0}else switch(i.layout){case"2-1":case"1-2":case"1-3":case"3-1":case"1-1":case"1":let e;await i.childNodes.forEach((t=>{t.tagName&&(e=t.cloneNode(!0),i.getAttribute("slot")?e.setAttribute("slot",i.getAttribute("slot")):e.removeAttribute("slot"),i.parentNode.insertBefore(e,i))})),n.activeNode=e,setTimeout((()=>{i.remove()}),0),o=!0;break;case"1-1-1":i.layout="1-1",o=!0;break;case"1-1-1-1":i.layout="1-1-1",o=!0;break;case"2-1-1":i.layout="2-1",o=!0;break;case"1-2-1":case"1-1-2":i.layout="1-2",o=!0}if(o){let e=this.contextMenus.plate.shadowRoot.querySelector("#right"),o=this.contextMenus.plate.shadowRoot.querySelector("#rightremove");e.disabled=!1,o.disabled=!1,"1-1-1-1"==i.layout&&(e.disabled=!0),"left"==t&&i.childNodes.forEach((e=>{if(e.tagName){let t=parseInt(e.getAttribute("slot").replace("col-",""),10)+1;e.setAttribute("slot",`col-${t}`)}}))}}else{let e=globalThis.document.createElement("grid-plate");e.layout="1-2-1",e.disableResponsive=!0,i.getAttribute("slot")&&e.setAttribute("slot",i.getAttribute("slot"));let t=i.cloneNode(!0);t.setAttribute("slot","col-2"),e.appendChild(t),i.parentNode.insertBefore(e,i),setTimeout((()=>{i.remove()}),0)}await n.refreshActiveNodeForm()}haxReplaceNode(e,t){try{null==e&&(e=this.__oldActiveNode),!e.replaceWith&&n._tmpRange&&(e=n._tmpRange,n._tmpRange=null),e&&e.getAttribute&&null!=e.getAttribute("slot")&&t.setAttribute("slot",e.getAttribute("slot")),e.replaceWith(t)}catch(e){console.warn(e)}return t}haxChangeTagName(e,t,i=!0){for(var o=globalThis.document.createElement(t),a=0,s=e.attributes.length;a<s;++a){let t=e.attributes.item(a).nodeName,i=e.attributes.item(a).value;try{o.setAttribute(t,i)}catch(t){console.warn(e.attributes),console.warn(t)}}i&&(o.innerHTML=e.innerHTML.trim()),"ul"==t||"ol"==t?"<br />"==o.innerHTML?o.innerHTML="<li><br /></li>":"ul"!=e.tagName.toLowerCase()&&"ol"!=e.tagName.toLowerCase()&&(o.innerHTML="<li>"+e.innerHTML.trim().replace(/<br\/>/g,"</li>\n<li>").replace(/<br>/g,"</li>\n<li>")+"</li>"):"ul"!=e.tagName.toLowerCase()&&"ol"!=e.tagName.toLowerCase()||(o.innerHTML=o.innerHTML.replace(/<ul>/g,"").replace(/<\/ul>/g,"").replace(/<li><\/li>/g,"").replace(/<li>/g,"").replace(/<\/li>/g,"<br/>"));try{e.replaceWith(o),i&&setTimeout((()=>{let e=o.children;e[0]&&e.tagName?e[0].focus():o.focus()}),10)}catch(t){console.warn(t),console.warn(o),console.warn(e)}return o}haxDeleteNode(e){if(e.previousElementSibling)n.activeNode=e.previousElementSibling;else if(e.nextElementSibling)n.activeNode=e.nextElementSibling;else{this.haxInsert("p","",{});try{var t=globalThis.document.createRange(),i=n.getSelection();t.setStart(this.activeNode,0),t.collapse(!0),i.removeAllRanges(),i.addRange(t),this.activeNode.focus()}catch(e){console.warn(e)}}try{return e.remove()}catch(e){console.warn(e)}}importContent(e,t=!0){t&&c(this,"*"),setTimeout((()=>{e=d(e);let t=globalThis.document.createElement("div");for(t.insertAdjacentHTML("beforeend",e);null!==t.firstChild;)if(void 0!==t.firstChild.tagName)if(n._isSandboxed&&"iframe"===t.firstChild.tagName.toLowerCase()){for(var i=globalThis.document.createElement("webview"),o=0,a=t.firstChild.attributes.length;o<a;++o){var s=t.firstChild.attributes.item(o).nodeName,r=t.firstChild.attributes.item(o).value;"height"!==s&&"width"!==s||i.style[s],i.setAttribute(s,r)}this.appendChild(i)}else this.appendChild(t.firstChild);else t.removeChild(t.firstChild)}),0)}sortGridSlots(e=this.activeNode){let t=n.haxSchemaFromTag(e.tagName);"grid"===t.type&&("GRID-PLATE"===e.tagName?e.layout.split("-").map(((e,t)=>`col-${t}`)):n.slotsFromSchema(t).map((e=>e.slot))).reverse().forEach(((t,i)=>{0==i?e.querySelectorAll(`[slot=${t}]`).forEach((t=>e.append(t))):[...e.querySelectorAll(`[slot=${t}]`)].reverse().forEach((t=>e.insertBefore(t,e.firstChild)))}))}async _haxContextOperation(e){let t=e.detail,i=N(e),o=i&&i[0]?i[0].getAttribute("data-slot"):void 0;switch(t.eventName){case"insert-above-active":if(this.activeNode&&this.activeNode.previousElementSibling)this.haxInsert("p","",{},this.activeNode.previousElementSibling);else if(this.activeNode){let e=globalThis.document.createElement("p");this.activeNode.getAttribute("slot")&&e.setAttribute("slot",this.activeNode.getAttribute("slot")),this.activeNode.parentNode.insertBefore(e,this.activeNode)}else this.appendChild(p);break;case"insert-below-active":this.haxInsert("p","",{});break;case"move-to-slot":o&&this.activeNode&&n.isGridPlateElement(this.activeNode.parentNode)&&(this.activeNode.slot=o,this.sortGridSlots(this.activeNode.parentNode));break;case"insert-into-active":if(o&&this.activeNode&&n.isGridPlateElement(this.activeNode)){let e=globalThis.document.createElement("p");e.slot=o,this.activeNode.append(e),this.haxInsert("p","",{slot:o},e),e.remove(),this.sortGridSlots()}break;case"hax-select-grid":if(i[0]&&i[0].eventData){let e=i[0].eventData;this.setActiveNode(e,!0),this.positionContextMenus(e)}break;case"hax-select-grid-item":if(i[0]&&i[0].eventData){let e=i[0].eventData,t=e.target,o=e.slot,a=e.index,s=e.grid,n=e.editMode,r=e.invisible?s:[...s.children].filter((e=>o&&""!==o?e.slot===o:!e.slot||""===e.slot))[a]||t;s&&n?this.setSlotEditMode(s,n,r):(this.setActiveNode(node,!0),this.positionContextMenus(node))}break;case"hax-edit-element-toggle":if(i[0]&&i[0].eventData){let e=i[0].eventData;e&&e.target&&e.editMode&&this.toggleElementEditMode(e.target,e.editMode)}break;case"hax-source-view-toggle":if(this.activeNode.__haxSourceView){this.activeNode.__haxSourceView=!1;let e=await n.runHook(n.activeEditingElement,"activeElementChanged",[this.activeNode,!1]),t={};if(this.activeNode&&this.activeNode.tagName?t=n.haxSchemaFromTag(this.activeNode.tagName.toLowerCase()):this.activeNode.parentElement&&this.activeNode.parentElement.tagName&&(t=n.haxSchemaFromTag(this.activeNode.parentElement.tagName.toLowerCase())),this.activeNode&&this.activeNode.getAttribute&&null!=this.activeNode.getAttribute("slot")&&e.setAttribute("slot",this.activeNode.getAttribute("slot")),t.saveOptions&&t.saveOptions.unsetAttributes&&t.saveOptions.unsetAttributes.length)for(var a in t.saveOptions.unsetAttributes)e.removeAttribute(t.saveOptions.unsetAttributes[a]);this.__applyNodeEditableState(e,this.editMode),b(n.activeEditingElement),n.activeEditingElement=null,this.viewSourceToggle=!1}else this.activeNode.__haxSourceView=!0,n.activeEditingElement=globalThis.document.createElement("code-editor"),n.activeEditingElement.language="html",n.activeEditingElement.title="",n.activeEditingElement.theme="vs",n.activeEditingElement.fontSize=12,n.activeEditingElement.wordWrap=!0,this.viewSourceToggle=!0,import("../code-editor/code-editor.js"),this.activeNode.getAttribute&&null!=this.activeNode.getAttribute("slot")&&n.activeEditingElement.setAttribute("slot",this.activeNode.getAttribute("slot")),this.__ignoreActive=!0,this.activeNode.removeAttribute("contenteditable"),this.__applyDragDropState(this.activeNode,!1),this.activeNode.removeAttribute("data-hax-active"),n.testHook(this.activeNode,"preProcessNodeToContent")&&(n.activeNode=await n.runHook(this.activeNode,"preProcessNodeToContent",[this.activeNode])),v(this.activeNode,n.activeEditingElement),n.activeEditingElement.focus();break;case"hax-full-text-editor-toggle":if(this.activeNode.__haxSourceView){this.activeNode.__haxSourceView=!1;let e=await n.runHook(n.activeEditingElement,"activeElementChanged",[this.activeNode,!1]),t=n.haxSchemaFromTag(this.activeNode.tagName.toLowerCase());if(this.activeNode&&this.activeNode.getAttribute&&null!=this.activeNode.getAttribute("slot")&&e.setAttribute("slot",this.activeNode.getAttribute("slot")),t.saveOptions&&t.saveOptions.unsetAttributes&&t.saveOptions.unsetAttributes.length)for(var a in t.saveOptions.unsetAttributes)e.removeAttribute(t.saveOptions.unsetAttributes[a]);this.__applyNodeEditableState(e,this.editMode),b(n.activeEditingElement),n.activeEditingElement=null,this.viewSourceElement=n.activeEditingElement}else this.activeNode.__haxSourceView=!0,import("../rich-text-editor/rich-text-editor.js").then((()=>{n.activeEditingElement=globalThis.document.createElement("rich-text-editor"),n.activeEditingElement.type="rich-text-editor-toolbar-full",this.activeNode.getAttribute&&null!=this.activeNode.getAttribute("slot")&&n.activeEditingElement.setAttribute("slot",this.activeNode.getAttribute("slot")),this.__ignoreActive=!0,this.activeNode.removeAttribute("contenteditable"),this.__applyDragDropState(this.activeNode,!1),this.activeNode.removeAttribute("data-hax-active"),v(this.activeNode,n.activeEditingElement),this.viewSourceElement=n.activeEditingElement}));break;case"text-tag":n.activeNode=this.haxChangeTagName(this.activeNode,t.value),this.positionContextMenus();break;case"text-tag-ul":this.contextMenus.text.realSelectedValue="ul",n.activeNode=this.haxChangeTagName(this.activeNode,"ul"),this.positionContextMenus();break;case"text-tag-ol":this.contextMenus.text.realSelectedValue="ol",n.activeNode=this.haxChangeTagName(this.activeNode,"ol"),this.positionContextMenus();break;case"hax-plate-create-right":this.haxGridPlateOps();break;case"hax-plate-remove-right":this.haxGridPlateOps(!1);break;case"hax-plate-duplicate":this.haxDuplicateNode(this.activeNode);break;case"hax-plate-delete":null!=this.activeNode&&this.haxDeleteNode(this.activeNode);break;case"hax-plate-up":this.activeNode.previousElementSibling&&"PAGE-BREAK"!==this.activeNode.previousElementSibling.tagName&&this.haxMoveGridPlate(this.activeNode,-1);break;case"hax-plate-down":this.activeNode.nextElementSibling&&this.haxMoveGridPlate(this.activeNode);break;case"content-edit":"content-edit"===n.haxTray.trayDetail&&(n.haxTray.collapsed=!1),n.haxTray.trayDetail="content-edit";break;case"super-daemon":const e=n.getRange();f.mini=!0,f.activeRange=e,f.activeSelection=n.getSelection();let s=this.activeNode;e.commonAncestorContainer.tagName?s=e.commonAncestorContainer:e.commonAncestorContainer.parentNode&&e.commonAncestorContainer.parentNode.tagName&&(s=e.commonAncestorContainer.parentNode),f.activeNode=s,f.runProgram(s.textContent.trim(),"*"),f.open();break;case"hide-context-menus":this.hideContextMenus()}}_focusIn(e){this.__mouseDown||this.__focusLogic(e.target)&&(e.stopPropagation(),e.stopImmediatePropagation())}__focusLogic(e,t=!0){let i=!1;if(this.editMode&&!this.__tabTrap){let o=e;("SPAN"===o.tagName&&n.isTextElement(o.parentNode)&&""==o.parentNode.getAttribute("slot")||"LI"===o.tagName&&n.isTextElement(o.parentNode)&&["UL","OL"].includes(o.parentNode.tagName))&&(o=e.parentNode);let a=null;if(this._validElementTest(o)&&o.parentNode&&o.parentNode.tagName){if("P"===o.parentNode.tagName&&""==o.parentNode.getAttribute("slot"))a=o,i=!0;else{for(;o.parentNode&&o.parentNode.tagName&&"HAX-BODY"!=o.parentNode.tagName;)null===a&&"B"!==o.tagName&&"I"!==o.tagName&&"STRONG"!==o.tagName&&"EM"!==o.tagName&&(a=o),o=o.parentNode;null===a?a=o:n.isGridPlateElement(o)}(this.activeNode&&this.activeNode.parentNode!==o&&!o.classList.contains("ignore-activation")||o.haxUIElement||o.classList.contains("ignore-activation"))&&(i=!0),a.haxUIElement||a.classList.contains("ignore-activation")||(n.activeNode=a,setTimeout((()=>{if(t&&!this.__mouseDown&&n.isTextElement(a))try{var e=globalThis.document.createRange(),i=n.getSelection();e.setStart(this.activeNode,0),e.collapse(!0),i.removeAllRanges(),i.addRange(e),this.activeNode.focus()}catch(e){console.warn(e)}this.positionContextMenus(a)}),0),i=!0)}}else this.__tabTrap=!1;return i}scrollHere(e){setTimeout((()=>{e.scrollIntoView({behavior:"smooth",inline:"nearest",block:"end"})}),100)}undo(){super.undo(),setTimeout((()=>{let e=this.querySelector("[data-hax-active]");e?(this.__focusLogic(e),this.scrollHere(e)):this.hideContextMenus()}),0)}redo(){super.redo(),setTimeout((()=>{let e=this.querySelector("[data-hax-active]");e?(this.__focusLogic(e),this.scrollHere(e)):this.hideContextMenus()}),0)}async _editModeChanged(e,t){if(void 0!==t){if(this._applyContentEditable(e),e){if(this.children&&this.children[0]&&this.children[0].focus&&this.children[0].tagName)"PAGE-BREAK"===this.children[0].tagName&&this.children[1]&&this.children[1].focus?this.__focusLogic(this.children[1]):"PAGE-BREAK"===this.children[0].tagName?this.haxInsert("p","",{}):this.__focusLogic(this.children[0]);else{this.haxInsert("p","",{});try{var i=globalThis.document.createRange(),o=n.getSelection();i.setStart(this.activeNode,0),i.collapse(!0),o.removeAllRanges(),o.addRange(i),this.activeNode.focus()}catch(e){console.warn(e)}}this._haxContextOperation({detail:{eventName:"content-edit",value:!0}})}else this.activeNode&&(this.unsetSlotEditMode(this.activeNode),this.unsetElementEditMode(this.activeNode));setTimeout((()=>{this.undoStack.undoStackLimit=50,this.undoStack.undoStackPosition=-1,this.undoStack.commands=[],this.undoStack.changed(),this.undoStackInitialValue=this.innerHTML,this.undoStackPrevValue=this.undoStackInitialValue}),0)}if(0==e){b(n.activeEditingElement),n.activeEditingElement=null,this.removeAttribute("contenteditable"),this.hideContextMenus();let e=this.querySelectorAll("[contenteditable],[data-hax-active]");for(var a=0;a<e.length;a++){let t=e[a];t.removeAttribute("contenteditable"),t.removeAttribute("data-hax-active")}}let s="slot"===this.shadowRoot.querySelector("#body").localName?this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0}):[];0===s.length&&(s=this.shadowRoot.querySelector("#body").children);for(a=0;a<s.length;a++)await n.runHook(s[a],"editModeChanged",[e]);e?(this._haxContextOperation=this._haxContextOperation.bind(this),this._toggleNodeLocking=this._toggleNodeLocking.bind(this),this.scrollerFixclickEvent=this.scrollerFixclickEvent.bind(this),this.blurEvent=this.blurEvent.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this),this._keepContextVisible=this._keepContextVisible.bind(this),this.windowControllers=new AbortController,globalThis.addEventListener("hax-context-item-selected",this._haxContextOperation,{signal:this.windowControllers.signal}),globalThis.addEventListener("hax-toggle-active-node-lock",this._toggleNodeLocking,{signal:this.windowControllers.signal}),globalThis.addEventListener("click",this.scrollerFixclickEvent,{signal:this.windowControllers.signal}),globalThis.addEventListener("blur",this.blurEvent,{signal:this.windowControllers.signal}),globalThis.addEventListener("keydown",this._onKeyDown,{signal:this.windowControllers.signal}),globalThis.addEventListener("keyup",this._onKeyUp,{signal:this.windowControllers.signal}),globalThis.addEventListener("resize",this._keepContextVisible,{passive:!0,signal:this.windowControllers.signal}),this._observer=new MutationObserver((e=>{var t=!1;this.__ignoreActive||this.__dragMoving||this.undoStackIgnore||this.__fakeEndCap||!this.ready||!this.editMode||!this.shadowRoot?this.undoStackIgnore&&e.forEach((e=>{e.addedNodes.length>0&&e.addedNodes.forEach((e=>{this._validElementTest(e,!0)&&setTimeout((()=>{this.__applyNodeEditableState(e,this.editMode)}),0)}))})):e.forEach((e=>{if(e.removedNodes.length>0)for(var i of e.removedNodes)e.previousSibling&&this.activeNode;if(e.addedNodes.length>0){for(var i of e.addedNodes)if(this._validElementTest(i)){if(!this.__delHit&&"BR"===i.tagName&&i.parentElement&&n.__validGridTags().includes(i.parentElement.tagName.toLowerCase())&&i===i.parentElement.childNodes[i.parentElement.childNodes.length-1]){let e=i.parentElement;if(i.remove(),e.childNodes.length>0){let t=e.childNodes[e.childNodes.length-1];t.textContent+="​",n._positionCursorInNode(t,t.length)}continue}if(this.__delHit=!1,"P"===i.tagName&&i.children.length>0&&"P"===i.children[0].tagName){b(i);continue}if("P"===i.tagName&&i.parentElement&&"P"===i.parentElement.tagName){b(i.parentElement);continue}if(null!=i.getAttribute("slot")&&i.parentElement===this){i.removeAttribute("slot");continue}if("LI"===i.tagName&&i.children.length>0&&"SPAN"===i.children[0].tagName){this.activeNode!==i.children[0]&&this.activeNode!==i||(n.activeNode=i),b(i.children[0]);continue}if("LI"===i.tagName&&i.parentElement&&!["UL","OL"].includes(i.parentElement.tagName)){b(i);continue}if("P"===i.tagName&&i.children.length>0&&["P","LI"].includes(i.children[0].tagName)){b(i.children[0]);continue}if(this.__slot&&(i.setAttribute("slot",this.__slot),this.__slot=null),this.__indentTrap)if("SPAN"===i.tagName)i.parentNode===this?this.haxChangeTagName(i,"p",!0):"LI"===i.parentNode.tagName&&(i.parentNode.innerHTML=i.textContent);else if("BR"===i.tagName){i.remove();continue}if(!this.editMode||"true"!=i.getAttribute("contenteditable")&&!0!==i.getAttribute("contenteditable")&&"contenteditable"!=i.getAttribute("contenteditable")||this.__applyNodeEditableState(i,!this.editMode),this.__applyNodeEditableState(i,this.editMode),n.isGridPlateElement(i)){let e=i.querySelectorAll("*");for(var o=0;o<e.length;o++)this._validElementTest(e[o],!0)&&this.__applyNodeEditableState(e[o],this.editMode)}if(["H1","H2","H3","H4","H5","H6"].includes(i.tagName)&&null==i.getAttribute("id")&&i.setAttribute("id",h("header-")),this.___moveLock||t)this.___moveLock=!1;else{if(t=!0,"LI"===i.tagName&&i.parentNode)n.activeNode=i.parentNode;else if("BR"===i.tagName){const e=n.getSelection();n._tmpSelection=e,n.haxSelectedText=e.toString();const t=n.getRange();t.collapsed&&"BR"===this.activeNode.tagName&&this.activeNode.parentNode===t.commonAncestorContainer&&""===this.activeNode.innerText&&(n.activeNode=this.activeNode.parentNode)}else n.activeNode=i;n.activeNode.setAttribute("data-hax-active","data-hax-active")}}this.__indentTrap&&setTimeout((()=>{this.__indentTrap=!1}),0)}else this.ready&&this.editMode&&n.ready&&0===e.addedNodes.length&&e.removedNodes.length>0&&this.shadowRoot&&(1===this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0}).length&&"PAGE-BREAK"===this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0})[0].tagName||0===this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0}).length)&&setTimeout((()=>{(1===this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0}).length&&"PAGE-BREAK"===this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0})[0].tagName||0===this.shadowRoot.querySelector("#body").assignedNodes({flatten:!0}).length)&&this.appendChild(document.createElement("p"))}),100)})),this.__ignoreActive&&(this.__ignoreActive=!1),n.haxTray.updateMap()})),this._observer.observe(this,{childList:!0,subtree:!0})):(this.windowControllers.abort(),this._observer.disconnect())}_haxResolvePreviousElement(e){for(e=e.previousElementSibling;null!=e&&void 0!==e.tagName&&"HAX-"===e.tagName.substring(0,4);)e=e.previousElementSibling;return e}_validElementTest(e,t=!1){return!(e.haxUIElement||!e.tagName||["TEMPLATE","HAX-BODY","FAKE-HAX-BODY-END"].includes(e.tagName))&&!(!t&&this._HTMLInlineTextDecorationTest(e)&&"HAX-BODY"!=e.parentNode)}_HTMLInlineTextDecorationTest(e){return["span","b","strong","i","em","u","strike"].includes(e.tagName.toLowerCase())}_HTMLPrimativeTest(e){return null!=e&&void 0!==e.tagName&&-1==e.tagName.indexOf("-")}_applyContentEditable(e,t=this.shadowRoot.querySelector("#body")){let i="slot"===t.localName?t.assignedNodes({flatten:!0}):[];0===i.length&&(i=t.children);for(var o=0;o<i.length;o++)if(this._validElementTest(i[o],!0)&&(!e||!0!==i[o].getAttribute("contenteditable")&&"true"!=i[o].getAttribute("contenteditable")&&"contenteditable"!=i[o].getAttribute("contenteditable"))&&this.__applyNodeEditableState(i[o],e),n.isGridPlateElement(i[o])){let t=i[o].querySelectorAll("*");for(var a=0;a<t.length;a++)this._validElementTest(t[a],!0)&&this.__applyNodeEditableState(t[a],e)}}__layoutDropEvent(e,t){[...t.querySelectorAll(".active")].forEach((e=>{e.classList.remove("active")})),[...t.shadowRoot.querySelectorAll(".active")].forEach((e=>{e.classList.remove("active")}))}__layoutDragEnter(e){e.target.classList.add("active")}__layoutDragLeave(e){e.target.classList.remove("active")}__layoutMonitor(e){var t=N(e);t[0]&&t[0].assignedNodes&&t[0].assignedNodes().length&&t[0].parentNode&&t[0].parentNode.classList?t[0].parentNode.classList.add("has-nodes"):t[0].parentNode&&t[0].parentNode.classList&&t[0].parentNode.classList.remove("has-nodes")}__getLayoutOrder(e,t){if(!t.shadowRoot)return!1;let i=e.getAttribute("slot"),o=t.shadowRoot.querySelector(`[slot=${i}]`);return[...t.shadowRoot.querySelectorAll("[slot]")].map((e=>e.parentNode)).indexOf(o)||-1}__layoutCanMove(e,t,i){if(!t.shadowRoot)return!1;let o=t.shadowRoot.querySelector(`[slot=${slot}]`),a=[...t.shadowRoot.querySelectorAll("[slot]")].map((e=>e.parentNode)),s=(a.indexOf(o)||-1)+(i?-1:1);return s>=a[0]&&s<=a[a.length-1]}__layoutMove(e,t,i){if(!t.shadowRoot)return!1;let o=t.shadowRoot.querySelector(`[slot=${n}]`),a=[...t.shadowRoot.querySelectorAll("[slot]")].map((e=>e.parentNode)),s=a.indexOf(o)||-1,n=a[s+(i?-1:1)];n&&e.setAttribute("slot",n)}async __sortLayoutChildren(e){e.setAttribute("hax-layout-sorting",!0);try{let t=Array.prototype.reduce.call(e.querySelectorAll("[slot]"),(function(e,t){return e}),[]);t=t.sort((function(t,i){return this.__getLayoutOrder(t,e)<this.__getLayoutOrder(i,e)?-1:1})),await t.forEach((t=>{t.parentNode===this&&e.appendChild(t)}))}catch(e){console.warn(e)}e.removeAttribute("hax-layout-sorting")}__layoutSlotValid(e,t){return this.__layoutSlots(t).includes(e.getAttribute("slot"))}__layoutSlots(e){return e.shadowRoot?[...e.shadowRoot.querySelectorAll("[slot]")].map((e=>e.getAttribute("name"))):[]}__applyDragDropState(e,t){let i={drop:t=>this.__layoutDropEvent.bind(this)(t,e),dragenter:this.__layoutDragEnter.bind(this),dragleave:this.__layoutDragEnter.bind(this),slotchange:this.__layoutMonitor.bind(this)};if(e.setAttribute("data-hax-layout",!0),n.isGridPlateElement(e)&&e.setAttribute("data-hax-grid",!0),t&&e.setAttribute("data-hax-ray",t),t&&e.shadowRoot){e.addEventListener("drop",i.drop);let t=[...e.shadowRoot.querySelectorAll("drag-enabled")],o=[...e.shadowRoot.querySelectorAll("slot")];t.forEach((e=>{e.addEventListener("dragenter",i.dragenter),e.addEventListener("dragleave",i.dragleave)})),o.forEach((e=>e.addEventListener("slotchange",i.slotchange))),e.haxLayoutObserver=new MutationObserver((t=>{e.getAttribute("hax-layout-sorting")||(t.forEach((t=>{t.addedNodes.forEach((t=>{t.tagName&&t!==this&&t.parentElement&&"HAX-BODY"!==t.parentElement.tagName&&!this.__layoutSlotValid(t,e)&&this.__layoutSlots(e).length>0&&t.setAttribute("slot",this.__layoutSlots(e)[0])}))})),this.__sortLayoutChildren(e))})),e.haxLayoutObserver.observe(this,{childList:!0})}else if(e.shadowRoot){e.haxLayoutObserver&&e.haxLayoutObserver.disconnect(),this.removeEventListener("drop",i.drop);let t=[...e.shadowRoot.querySelectorAll("drag-enabled")],o=[...e.shadowRoot.querySelectorAll("slot")];t.forEach((e=>{e.removeEventListener("dragenter",i.dragenter),e.removeEventListener("dragleave",i.dragleave)})),o.forEach((e=>e.removeEventListener("slotchange",i.slotchange))),e.removeAttribute("data-hax-ray")}}__isLayout(e){return e&&n.haxSchemaFromTag(e.tagName)&&"grid"===n.haxSchemaFromTag(e.tagName).type}__applyNodeEditableState(e,t=!0){let i;if(!e.tagName)return!1;let o=e.tagName.replace("-"," ").toLowerCase(),a=l(n.gizmoList).findIndex((t=>{if(t)return t.tag===e.tagName.toLowerCase()}));if(-1!==a&&(o=l(n.gizmoList)[a].title),"PAGE-BREAK"!==e.tagName?("IMG"==e.tagName&&e.setAttribute("draggable",!1),t?(this.__applyDragDropState(e,o),i="addEventListener"):(this.__applyDragDropState(e,!1),i="removeEventListener"),e[i]("drop",this.dropEvent.bind(this)),e[i]("dragenter",this.dragEnter.bind(this)),e[i]("dragleave",this.dragLeave.bind(this)),e[i]("dragover",(e=>{this.__dragMoving=!0,e.preventDefault()}))):t?e.setAttribute("data-hax-ray",""):e.removeAttribute("data-hax-ray"),this._HTMLPrimativeTest(e)&&(t?e.setAttribute("contenteditable",t):e.removeAttribute("contenteditable"),e.querySelectorAll("a").length>0)){let o=e.querySelectorAll("a");for(var s=0,r=o.length;s<r;s++)t?o[s].setAttribute("contenteditable",t):o[s].removeAttribute("contenteditable"),o[s][i]("click",(e=>{e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}))}}undoManagerStackLogic(e){this.__dragMoving||(this.querySelectorAll(".hax-hovered").forEach((e=>{e.classList.remove("hax-hovered")})),super.undoManagerStackLogic(e))}dropEvent(e){if(this.editMode){this.__dragMoving=!1,this.undoManagerStackLogic({}),clearTimeout(A),n._lockContextPosition=!1,n.haxTray.activeTab="item-1";var t,i=null,o=N(e);if(null!==(i=e.target.closest("[data-hax-layout]")&&e.target.parentNode!=e.target.closest("[data-hax-layout]")?e.target.closest("[data-hax-layout]"):e.target.closest("[contenteditable],img")?e.target.closest("[contenteditable],img"):e.originalTarget?e.originalTarget:e.target).getAttribute("data-hax-lock"))return!1;o[0].classList.contains("column")?this.__slot=o[0].getAttribute("id").replace("col","col-"):i.getAttribute("slot")&&(this.__slot=i.getAttribute("slot")),this.querySelectorAll(".hax-hovered").forEach((e=>{e.classList.remove("hax-hovered")})),this.querySelectorAll(".active").forEach((e=>{e.classList.remove("active")})),n.activeNode=i;try{if(null===n.__dragTarget&&e.dataTransfer&&e.dataTransfer.items&&e.dataTransfer.items.length>0&&"file"===e.dataTransfer.items[0].kind){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();let i=globalThis.document.createElement("p");e.target.closest("[data-hax-layout]")&&e.target.parentNode!=e.target.closest("[data-hax-layout]")?t=e.target.closest("[data-hax-layout]"):e.target.closest("[contenteditable],img")&&(t=e.target.closest("[contenteditable],img")),t&&(t.tagName&&"HAX-BODY"!==t.tagName||!t.getAttribute("data-hax-layout"))||this.__isLayout(o[0])?(t.getAttribute("slot")?i.setAttribute("slot",t.getAttribute("slot")):o[0].classList.contains("column")?i.setAttribute("slot",o[0].getAttribute("id").replace("col","col-")):i.removeAttribute("slot"),t.parentNode.insertBefore(i,t)):(o[0].classList.contains("column")?i.setAttribute("slot",o[0].getAttribute("id").replace("col","col-")):t&&"HAX-BODY"===t.tagName&&i.getAttribute("slot")&&i.removeAttribute("slot"),t?t.appendChild(i):this.appendChild(i)),e.placeHolderElement=i,this.dispatchEvent(new CustomEvent("place-holder-file-drop",{bubbles:!0,cancelable:!0,composed:!0,detail:e}))}else{if(i=n.__dragTarget,t=e.target,e.target.closest("[data-hax-layout]")&&e.target.parentNode!=e.target.closest("[data-hax-layout]")?t=e.target.closest("[data-hax-layout]"):e.target.closest("[contenteditable],img")&&(t=e.target.closest("[contenteditable],img")),t&&i&&this._validElementTest(i)&&i!==t){try{"HAX-BODY"!==t.tagName&&!this.__isLayout(t)||this.__isLayout(o[0])?(t.getAttribute("slot")?i.setAttribute("slot",t.getAttribute("slot")):o[0].classList.contains("column")?i.setAttribute("slot",o[0].getAttribute("id").replace("col","col-")):i.removeAttribute("slot"),t.parentNode.insertBefore(i,t)):(o[0].classList.contains("column")?i.setAttribute("slot",o[0].getAttribute("id").replace("col","col-")):"HAX-BODY"===t.tagName&&i.getAttribute("slot")&&i.removeAttribute("slot"),t.appendChild(i))}catch(e){console.warn(e)}e.preventDefault(),e.stopPropagation()}i&&this._validElementTest(i)&&"function"==typeof i.focus&&(n.activeNode=i,n.testHook(n.activeNode,"trayDragNDropToNode")&&n.runHook(n.activeNode,"trayDragNDropToNode",[n.activeNode]),this.dispatchEvent(new CustomEvent("hax-drop-focus-event",{bubbles:!0,cancelable:!0,composed:!0,detail:this.activeNode})),this.scrollHere(this.activeNode),this.positionContextMenus())}}catch(e){console.warn(e)}}n.__dragTarget=null,this.__manageFakeEndCap(!1)}dragEnter(e){this.editMode&&e.target&&n.__dragTarget&&(this.__dragMoving=!0,e.preventDefault(),e.target&&e.target.classList&&e.target.classList.add("hax-hovered"),this.handleMousemove(e))}handleMousemove(e){var t=e.clientX,i=e.clientY,o=globalThis.document.documentElement.clientWidth,a=globalThis.document.documentElement.clientHeight,s=S,n=S,r=a-S,l=o-S,d=t<200,c=t>l,h=i<200,u=i>r;if(d||c||h||u){var g=Math.max(globalThis.document.body.scrollWidth,globalThis.document.body.offsetWidth,globalThis.document.body.clientWidth,globalThis.document.documentElement.scrollWidth,globalThis.document.documentElement.offsetWidth,globalThis.document.documentElement.clientWidth),m=Math.max(globalThis.document.body.scrollHeight,globalThis.document.body.offsetHeight,globalThis.document.body.clientHeight,globalThis.document.documentElement.scrollHeight,globalThis.document.documentElement.offsetHeight,globalThis.document.documentElement.clientHeight),p=g-o,v=m-a;!function checkForWindowScroll(){clearTimeout(A),function adjustWindowScroll(){var e=globalThis.pageXOffset,o=globalThis.pageYOffset,a=o>0,g=o<v,m=e>0,b=e<p,x=e,N=o;if(d&&m){x-=T*((n-t)/S)}else if(c&&b){x+=T*((t-l)/S)}if(h&&a){N-=T*((s-i)/S)}else if(u&&g){N+=T*((i-r)/S)}return x=Math.max(0,Math.min(p,x)),N=Math.max(0,Math.min(v,N)),(x!==e||N!==o)&&(globalThis.scrollTo(x,N),!0)}()&&(A=setTimeout(checkForWindowScroll,30))}()}else clearTimeout(A)}dragLeave(e){this.editMode&&e.target&&e.target.classList&&(this.__dragMoving=!0,e.target.classList.remove("hax-hovered"))}toggleElementEditMode(e,t){e[t]?this.unsetElementEditMode(e,t):this.setElementEditMode(e,t)}unsetElementEditMode(e=this.activeNode){if(!e||!e.getAttribute)return;let t=e.getAttribute("data-element-edit-mode")||"editMode";e[t]=!1,this.__applyNodeEditableState(e,this.editMode),n.activeEditingElement=null,this.editElementToggled=!1,this.__ignoreActive=!1}setElementEditMode(e,t="editMode"){e.setAttribute("data-element-edit-mode",t),e[t]=!0,n.activeEditingElement=e,this.editElementToggled=!1,this.__ignoreActive=!0,this.activeNode.removeAttribute("contenteditable"),this.activeNode.removeAttribute("data-hax-active"),this.__applyDragDropState(this.activeNode,!1),n.activeEditingElement.focus()}unsetSlotEditMode(e){if(e.getAttribute&&e.getAttribute){let t=e.getAttribute("data-grid-saved-settings")?JSON.parse(e.getAttribute("data-grid-saved-settings")):void 0;Object.keys(t||{}).forEach((i=>e[i]=t[i])),e.removeAttribute("data-grid-saved-settings")}}setSlotEditMode(e,t,i){let o=e.getAttribute("data-grid-saved-settings")?JSON.parse(e.getAttribute("data-grid-saved-settings")):{},a=Object.keys(o);Object.keys(t||{}).forEach((i=>{a.includes(i)||(o[i]=e[i]),e[i]=t[i]})),e.setAttribute("data-grid-saved-settings",JSON.stringify(o))}async _activeNodeChanged(e,t){if(globalThis.SimplePopoverManager.requestAvailability().opened=!1,this.contextMenus.plate.disableDuplicate=!1,this.contextMenus.plate.disableOps=!1,this.contextMenus.plate.disableItemOps=!1,this.contextMenus.plate.canMoveElement=this.canMoveElement,setTimeout((()=>{this.prevKeyActiveNode=null}),5),t&&t.removeAttribute("data-hax-active"),e&&e.setAttribute("data-hax-active","data-hax-active"),e&&t&&n.isGridPlateElement(e)&&(this.__ignoreActive=!0),this.editMode&&null!=e&&e.parentNode&&e.tagName){let t=e.tagName.toLowerCase();(n.isTextElement(e)||"HR"===e.tagName||n.isGridPlateElement(e))&&null===e.getAttribute("data-hax-lock")&&null===e.parentNode.getAttribute("data-hax-lock")?(e.setAttribute("contenteditable",!0),this.setAttribute("contenteditable",!0)):(e.removeAttribute("contenteditable"),this.removeAttribute("contenteditable")),this._keepContextVisible(),this.contextMenus.text.realSelectedValue=t}else null===e&&(this.hideContextMenus(),this.__oldActiveNode=t);if(this.editMode&&await n.runHook(t,"activeElementChanged",[t,!1])&&(this.__ignoreActive=!0),this.editMode&&await n.runHook(e,"activeElementChanged",[e,!0])&&(this.__ignoreActive=!0),this.editMode&&t&&t.tagName){let e=n.haxSchemaFromTag(t.tagName.toLowerCase());if("core"!=e.editingElement||t.parentNode&&t.parentNode.haxUIElement&&t.parentNode===n.activeEditingElement){this.__ignoreActive=!0;let o=await n.runHook(t.parentNode,"activeElementChanged",[t,!1]);if(o&&o!==t){if(t&&t.getAttribute&&null!=t.getAttribute("slot")&&o.setAttribute("slot",t.getAttribute("slot")),e.saveOptions&&e.saveOptions.unsetAttributes&&e.saveOptions.unsetAttributes.length)for(var i in e.saveOptions.unsetAttributes)o.removeAttribute(e.saveOptions.unsetAttributes[i]);this.__applyNodeEditableState(o,this.editMode)}b(n.activeEditingElement),n.activeEditingElement=null}}if(this.editMode&&e){let t=n.haxSchemaFromTag(e.tagName);if(t&&t.editingElement&&"core"!=t.editingElement){if(t.editingElement.import){let e=new URL("./hax-body.js",import.meta.url).href+"/../../../";globalThis.WCGlobalBasePath&&(e=globalThis.WCGlobalBasePath),await import(`${e}${t.editingElement.import}`)}n.activeEditingElement=globalThis.document.createElement(t.editingElement.tag),e.getAttribute&&null!=e.getAttribute("slot")&&n.activeEditingElement.setAttribute("slot",e.getAttribute("slot")),t.editingElement.callback&&t.editingElement.callback(n.activeEditingElement),this.__ignoreActive=!0,v(e,n.activeEditingElement),await n.runHook(n.activeEditingElement,"activeElementChanged",[e,!0])}}!t||!t.parentNode||e&&e.parentNode&&e.parentNode===t.parentNode||this.unsetSlotEditMode(t.parentNode),this.unsetElementEditMode(t)}_getPosition(e){return{x:e.offsetLeft-e.scrollLeft+e.clientLeft,y:e.offsetTop-e.scrollTop+e.clientTop}}_showContextMenu(e){e.setAttribute("on-screen","on-screen"),e.classList.add("hax-context-visible","hax-context-menu-active")}_getContextContainer(e){let t=e&&e.parentNode?e.parentNode:void 0;return t&&t.nodeType?1==t.nodeType?t:t.host:void 0}_hideContextMenu(e){e&&(e.removeAttribute("on-screen"),e.classList.remove("hax-context-visible"),e.classList.remove("hax-context-menu-active"))}_tabKeyPressed(){if(this.activeNode&&n.getRange().cloneRange)try{let t=!1,i=this.activeNode.parentNode;const o=this.activeNode.parentNode.tagName;let a=n.getRange().cloneRange();var e=a.commonAncestorContainer.tagName;if(void 0===e&&(e=a.commonAncestorContainer.parentNode.tagName),["UL","OL","LI"].includes(o)||["UL","OL","LI"].includes(e))this.polyfillSafe&&(this.__tabTrap=!0,this.__indentTrap=!0,globalThis.document.execCommand("indent"));else for(;!t;)null==i.nextSibling?t=!0:"function"===i.nextSibling.focus?(i.nextSibling.focus(),t=!0):i=i.nextSibling}catch(e){console.warn(e)}}_tabBackKeyPressed(){if(this.activeNode&&n.getRange().cloneRange)try{let t=this.activeNode.parentNode;const i=this.activeNode.parentNode.tagName;let o=n.getRange().cloneRange();var e=o.commonAncestorContainer.tagName;if(void 0===e&&(e=o.commonAncestorContainer.parentNode.tagName),["UL","OL","LI"].includes(i)||["UL","OL","LI"].includes(e))this.polyfillSafe&&(this.__tabTrap=!0,this.__indentTrap=!0,globalThis.document.execCommand("outdent"));else{if(null!=t)for(;null!=t&&!this._validElementTest(t);)t=t.previousSibling;null!=t&&setTimeout((()=>{t.focus()}),50)}}catch(e){console.warn(e)}}}customElements.define(HaxBody.tag,HaxBody);export{HaxBody};