/**
 * Copyright 2022 The Pennsylvania State University
 * @license Apache-2.0, see License.md for full text.
 */
import{LitElement as t,css as e,html as i}from"../../lit/index.js";import{I18NMixin as s}from"../i18n-manager/lib/I18NMixin.js";import{unsafeHTML as n}from"../../lit/directives/unsafe-html.js";import{HAXStore as o}from"../hax-body/lib/hax-store.js";import{store as a}from"../haxcms-elements/lib/core/haxcms-site-store.js";import{autorun as l,toJS as d}from"../../mobx/dist/mobx.esm.js";import{JSONOutlineSchemaItem as r}from"../json-outline-schema/lib/json-outline-schema-item.js";import{JsonOutlineSchema as c}from"../json-outline-schema/json-outline-schema.js";import"../simple-popover/simple-popover.js";import"../simple-icon/lib/simple-icon-lite.js";import"../hax-iconset/lib/simple-hax-iconset.js";import"../simple-icon/lib/simple-icon-button.js";import"../simple-fields/lib/simple-fields-field.js";import{encapScript as p,haxElementToNode as h}from"../utils/utils.js";export class OutlineDesigner extends(s(t)){static get styles(){return[e`
        :host {
          display: block;
          font-family: var(--ddd-font-navigation);
        }
        simple-icon-button[hidden] {
          visibility: hidden !important;
          opacity: 0;
          pointer-events: none;
          padding: 0;
          margin: 0;
          height: 0;
          border: 0;
        }
        .controls {
          position: sticky;
          top: -32px;
          background-color: light-dark(white, #262626);
          z-index: 1;
          padding: 16px 0 8px 0;
        }
        .controls .control {
          border: 1px solid black;
          border-radius: 0;
          padding: 4px;
        }
        simple-popover {
          --simple-popover-max-height: 300px;
        }
        simple-popover *:not(.close-btn) {
          max-width: 40vw;
        }
        simple-popover::part(simple-popover-content) {
          overflow: auto;
        }
        .close-btn {
          z-index: 1000;
          background-color: white;
          border: 0px;
          border-radius: 50%;
          position: absolute;
          top: 24px;
          right: 0;
        }
        .container {
          text-align: left;
        }
        ul {
          list-style: none;
          padding: 0;
          margin: 0;
        }
        ul li {
          margin: 0;
          padding: 0;
        }
        .operation {
          display: inline-flex;
          --simple-icon-width: 24px;
          --simple-icon-height: 24px;
          margin: 0 4px;
        }
        .content-adding-operations .operation {
          display: inline-flex;
          --simple-icon-width: 24px;
          --simple-icon-height: 24px;
          margin: 0 4px;
          border: 1px solid black;
          border-radius: 0;
          padding: 4px;
        }
        .lock {
          margin-right: 16px !important;
          visibility: var(--outline-designer-lock-visibility);
        }
        .del {
          margin-left: 32px !important;
        }
        .goto {
          margin-left: 32px !important;
        }
        .add {
          margin-left: 16px !important;
        }
        li .operations {
          justify-content: space-evenly;
          display: flex;
        }
        .content-operation {
          display: inline-flex;
          opacity: 0;
          visibility: hidden;
          --simple-icon-width: 24px;
          --simple-icon-height: 24px;
          margin: 0 4px;
        }
        .content-operations {
          justify-content: space-evenly;
          display: flex;
        }
        li.content-child:hover .content-operation {
          visibility: visible;
          opacity: 1;
        }
        li[class*="collapsed-by-"] {
          opacity: 0;
          height: 0px !important;
          visibility: hidden;
          padding: 0px !important;
          margin: 0px !important;
          width: 0px !important;
          padding: 0px !important;
          margin: 0px !important;
          border: 0px !important;
          pointer-events: none;
          z-index: -1;
        }
        /* content not rendered if hidden but in case we change that */
        li[data-contents-collapsed] {
          opacity: 0;
          height: 0px !important;
          visibility: hidden;
          padding: 0px !important;
          margin: 0px !important;
          width: 0px !important;
          padding: 0px !important;
          margin: 0px !important;
          border: 0px !important;
          pointer-events: none;
          z-index: -1;
        }
        li simple-icon-button:hover {
          background-color: #f5f5f5;
        }
        .active-preview-item {
          outline: 1px solid grey;
          outline-offset: -1px;
        }
        .label,
        .label-edit {
          display: none;
        }
        span[disabled].label {
          pointer-events: none;
          opacity: 0.6;
        }
        .shown {
          display: inline-block;
        }
        .outline-designer-hovered {
          outline: 2px solid black;
          outline-offset: -1px;
          background-color: #e5e5e5;
        }
        .make-child-btn {
          transition: 0.3s all ease-in-out;
          visibility: hidden;
          opacity: 0;
        }
        .outline-designer-hovered .make-child-btn {
          visibility: visible;
          opacity: 0.6;
        }
        .outline-designer-hovered .make-child-btn:hover {
          opacity: 1;
        }
        .modified .label::after {
          content: "*";
          color: red;
          font-size: 20px;
          line-height: 20px;
        }
        .new {
          --simple-icon-width: 16px;
          --simple-icon-height: 16px;
          background-color: black;
          display: block;
          margin: -14px 0 0 4px;
        }
        :host([stop-animation]) .item {
          transition: none !important;
        }
        .item {
          display: -webkit-box;
          border: 1px solid;
          border-color: grey;
          margin: 0;
          padding: 4px;
          cursor: pointer;
          opacity: 1;
          visibility: visible;
          height: 42px;
          transition:
            0.3s padding ease-in-out,
            0.3s border ease-in-out,
            0.3s margin ease-in-out;
          overflow: hidden;
          align-items: center;
          justify-content: left;
          display: flex;
        }
        .collapse-btn {
          visibility: hidden;
        }
        .item[data-has-children] .collapse-btn {
          visibility: visible;
        }
        .item[data-about-to-delete] {
          background-color: #ffa5a5;
          opacity: 0.5;
          border-color: red;
        }
        .item[data-about-to-delete][hidden] {
          visibility: hidden !important;
          opacity: 0 !important;
          padding: 0;
          margin: 0;
          height: 0;
          border: 0;
        }
        .item:hover,
        .item:focus {
          background-color: #f5f5f5;
        }
        .item:hover .label,
        .item:focus .label {
          color: black;
        }
        ul {
          list-style: none;
        }
        .item .label-edit,
        .item .label {
          cursor: text;
          font-size: 14px;
          font-weight: bold;
          min-width: 200px;
          margin-right: 8px;
          max-width: 40%;
          line-height: 1.2;
          padding: 0 4px;
          color: light-dark(black, white);
        }

        .content-child {
          margin-left: 46px;
          padding: 8px;
          height: 24px;
          border-top: none;
          border-bottom: none;
        }
        .content-heading,
        .content-non-heading {
          margin-left: 32px;
        }
        .indent-0 {
          padding-left: 0;
        }
        .indent-1 {
          padding-left: 16px;
        }
        .indent-2 {
          padding-left: calc(16px * 2);
        }
        .indent-3 {
          padding-left: calc(16px * 3);
        }
        .indent-4 {
          padding-left: calc(16px * 4);
        }
        .indent-5 {
          padding-left: calc(16px * 5);
        }
        .indent-6 {
          padding-left: calc(16px * 6);
        }
        .indent-7 {
          padding-left: calc(16px * 7);
        }
        .indent-8 {
          padding-left: calc(16px * 8);
        }
        .indent-9 {
          padding-left: calc(16px * 9);
        }
        .indent-10 {
          padding-left: calc(16px * 10);
        }
        .indent-11 {
          padding-left: calc(16px * 11);
        }
        .indent-12 {
          padding-left: calc(16px * 12);
        }
        .indent-13 {
          padding-left: calc(16px * 13);
        }
        .indent-14 {
          padding-left: calc(16px * 14);
        }
        .indent-15 {
          padding-left: calc(16px * 15);
        }
        .indent-16 {
          padding-left: calc(16px * 16);
        }
        .indent-17 {
          padding-left: calc(16px * 17);
        }
        .indent-18 {
          padding-left: calc(16px * 18);
        }
        .indent-19 {
          padding-left: calc(16px * 19);
        }
        .indent-20 {
          padding-left: calc(16px * 20);
        }
      `]}constructor(){super(),this._blurBlock=!1,this.fidelity="medium",this.haxGizmos=[],this.hideDelete=!1,this.activeItemForActions=null,this.storeTools=!1,this.hideContentOps=!1,this.items=[],this.appReady=!1,this.eventData={},this.activeId=null,this.activePreview=null,this.activePreviewIndex=-1,this.t={selectTarget:"Select target",importContentUnderThisPage:"Import content under this page",importThisContent:"Import this content",thisPage:"this page",newPage:"New page",copyOf:"Copy of"},this.registerLocalization({context:this,basePath:import.meta.url,locales:["es"]}),l((()=>{this.activeId=d(a.activeId)})),l((()=>{this.appReady=d(a.appReady)})),l((()=>{this.haxGizmos=d(o.gizmoList).filter((t=>!!(t&&t.meta&&t.meta.outlineDesigner)))})),this.addEventListener("click",this.resetPopOver.bind(this))}resetPopOver(){this.activePreview&&(this.shadowRoot.querySelector("simple-popover").setAttribute("hidden","hidden"),this.activePreview=null,this.activePreviewIndex=-1)}getSiteItems(){var t=[{text:this.t.selectTarget,value:null}];if(this.appReady&&this.items.length>0){const e=a.getManifestItems(!0);e.forEach((i=>{let s=i,n="- ";for(;s&&null!=s.parent;)s=e.find((t=>t.id==s.parent)),s&&(n="--"+n);t.push({text:n+i.title,value:i.id})}))}return t}render(){return i` <div class="controls">
        ${this.storeTools?i`
              <label for="targetselector">${this.t.importThisContent}</label>
              <simple-fields-field
                id="targetselector"
                type="select"
                value="children"
                .itemsList="${[{text:"as children of",value:"children"},{text:"Above",value:"above"},{text:"Below",value:"below"}]}"
              ></simple-fields-field>
              ${this.t.thisPage}:
              <simple-fields-field
                id="itemselector"
                type="select"
                value="${this.activeId}"
                .itemsList="${this.getSiteItems()}"
              ></simple-fields-field>
              <label for="itemselector"
                >${this.t.importContentUnderThisPage}</label
              >
            `:""}
        <simple-icon-button-lite
          class="control"
          icon="add"
          @click="${this.addItemToTop}"
          >Add page</simple-icon-button-lite
        >
        <simple-icon-button-lite
          icon="hardware:keyboard-arrow-right"
          @click="${this.collapseAll}"
          class="control"
          >Collapse all</simple-icon-button-lite
        >
        <simple-icon-button-lite
          icon="hardware:keyboard-arrow-down"
          @click="${this.expandAll}"
          class="control"
          >Expand all</simple-icon-button-lite
        >
        ${this.hasDeletedItems()?i`<simple-icon-button-lite
              icon="delete"
              @click="${this.toggleDelete}"
              class="control"
              >${this.hideDelete?"Show Deleted":"Hide Deleted"}</simple-icon-button-lite
            >`:""}
      </div>
      <ul id="list">
        ${this.items.map(((t,e)=>""===this.getItemParentsCollapsed(t)?this.renderItem(t,e):""))}
      </ul>
      <simple-popover auto for="list" hidden>
        <simple-icon-button
          @click="${this.resetPopOver}"
          title="Close"
          icon="cancel"
          class="close-btn"
        ></simple-icon-button>
        ${this.renderActiveContentItem(this.activePreview,this.activePreviewIndex)}
      </simple-popover>`}hasDeletedItems(){return!!this.items.find((t=>1==t.delete))}toggleDelete(t){this.hideDelete=!this.hideDelete}renderActiveContentItem(t,e){if(t&&-1!=e){let s=this.items.find((e=>e.id===t.getAttribute("data-content-parent-id")));if(s.contents){let t=globalThis.document.createElement("div");t.innerHTML=s.contents;for(let s=0;s<t.childNodes.length;s++){let o=t.childNodes[s];if(s===e)return i`${n(p(o.outerHTML))}`}}}}setActiveItemForActions(t){this.activeItemForActions=t.target.closest("[data-item-id]").getAttribute("data-item-id")}renderItem(t,e){return i`
      <li
        @dragenter="${this._dragEnter}"
        @dragleave="${this._dragLeave}"
        @mouseenter="${this.setActiveItemForActions}"
        class="item indent-${t.indent<20?t.indent:20} ${t.modified?"modified":""} ${this.getItemParentsCollapsed(t)}"
        data-item-id="${t.id}"
        @focusin="${this.setActiveItemForActions}"
        data-parents="${this.getItemParents(t)}"
        ?data-has-children="${this.hasChildren(t.id)}"
        ?data-about-to-delete="${t.delete}"
        ?hidden="${this.hideDelete&&t.delete}"
      >
        <simple-icon-button
          ?disabled="${this.isLocked(e)}"
          class="collapse-btn"
          icon="${this.isCollapsed(t.id)?"hardware:keyboard-arrow-right":"hardware:keyboard-arrow-down"}"
          @click="${this.collapseExpand}"
        ></simple-icon-button>
        <simple-icon-button
          ?disabled="${this.isLocked(e)}"
          @dragstart="${this._dragStart}"
          @dragend="${this._dragEnd}"
          draggable="${!this.isLocked(e)}"
          icon="hax:arrow-all"
        ></simple-icon-button>
        <simple-icon-button-lite
          ?disabled="${this.isLocked(e)}"
          ?hidden="${this.hideContentOps||""===t.contents||!t.contents}"
          icon="editor:insert-drive-file"
          @click="${this.toggleContent}"
          title="Content structure"
        >
          ${t.new?i`<simple-icon
                ?disabled="${this.isLocked(e)}"
                icon="av:fiber-new"
                title="${this.t.newPage}"
                class="new"
                accent-color="green"
                dark
                contrast="1"
              ></simple-icon>`:""}
        </simple-icon-button-lite>
        <span
          class="label shown"
          ?disabled="${this.isLocked(e)}"
          @dblclick="${this.editTitle}"
          >${t.title}</span
        >
        <span
          class="label-edit"
          @blur="${this.blurTitle}"
          @keypress="${this.monitorTitle}"
          @keydown="${this.monitorEsc}"
        ></span>
        <div class="operations">
          ${this.activeItemForActions===t.id?i`
                <div class="btn-contrast">
                  <simple-icon-button
                    part="lockbtn"
                    class="operation lock"
                    icon="${this.isLocked(e)?"icons:lock":"icons:lock-open"}"
                    @click="${t=>this.itemOp(e,"lock")}"
                    title="Lock / Unlock"
                  ></simple-icon-button>
                  <simple-icon-button
                    class="operation"
                    icon="hax:outline-designer-outdent"
                    @click="${t=>this.itemOp(e,"out")}"
                    title="Move next to parent"
                    ?disabled="${this.isLocked(e)}"
                  ></simple-icon-button>
                  <simple-icon-button
                    class="operation"
                    icon="hax:keyboard-arrow-up"
                    @click="${t=>this.itemOp(e,"up")}"
                    title="Move up"
                    ?disabled="${this.isLocked(e)}"
                  ></simple-icon-button>
                  <simple-icon-button
                    class="operation"
                    icon="hax:keyboard-arrow-down"
                    @click="${t=>this.itemOp(e,"down")}"
                    title="Move down"
                    ?disabled="${this.isLocked(e)}"
                  ></simple-icon-button>
                  <simple-icon-button
                    class="operation"
                    icon="hax:outline-designer-indent"
                    @click="${t=>this.itemOp(e,"in")}"
                    title="Make child"
                    ?disabled="${this.isLocked(e)}"
                  ></simple-icon-button>
                </div>
                <simple-icon-button
                  class="operation add"
                  icon="add"
                  accent-color="green"
                  @click="${t=>this.itemOp(e,"add")}"
                  title="Add"
                  ?disabled="${this.isLocked(e)}"
                ></simple-icon-button>
                <simple-icon-button
                  class="operation"
                  icon="content-copy"
                  accent-color="green"
                  @click="${t=>this.itemOp(e,"duplicate")}"
                  title="Duplicate"
                  ?disabled="${this.isLocked(e)}"
                ></simple-icon-button>
                <simple-icon-button
                  class="operation del"
                  icon="${t.delete?"hax:delete-restore":"delete"}"
                  accent-color="red"
                  @click="${t=>this.itemOp(e,"delete")}"
                  title="${t.delete?"Restore":"Delete"}"
                  ?disabled="${this.isLocked(e)}"
                ></simple-icon-button>
                <simple-icon-button
                  class="operation goto"
                  icon="open-in-browser"
                  accent-color="blue"
                  @click="${t=>this.itemOp(e,"goto")}"
                  title="Go to page"
                ></simple-icon-button>
              `:""}
        </div>
      </li>
      ${!this.hideContentOps&&t.showContent?this.renderItemContents(t):""}
    `}hasContents(t){return!(!t.contents||""==t.contents)}renderItemContents(t){let e=[this.itemContentsOperations(t)];if(t.contents){let i=globalThis.document.createElement("div");i.innerHTML=t.contents;let s=1,n=0;i.childNodes.forEach(((i,o)=>{n=0,["h1","h2","h3","h4","h5","h6"].includes(i.tagName.toLowerCase())&&(s=parseInt(i.tagName.toLowerCase().replace("h","")),n=-1),e.push(this.renderNodeAsItem(i,o,t,parseInt(t.indent)+s+n))}))}return e}itemContentsOperations(t){return i` <li
      class="item content-adding-operations indent-${t.indent<20?t.indent:20}"
      data-item-for-content-id="${t.id}"
      ?data-contents-collapsed="${!t.showContent}"
      ?data-about-to-delete="${t.delete}"
      ?hidden="${this.hideDelete&&t.delete}"
    >
      ${this.haxGizmos.map((t=>i`
          <simple-icon-button-lite
            class="operation"
            icon="${t.icon}"
            value="${t.tag}"
            @click="${this.prependNodeToContent}"
            >Add ${t.title}</simple-icon-button-lite
          >
        `))}
    </li>`}prependNodeToContent(t){let e=t.target.closest("[data-item-for-content-id]").getAttribute("data-item-for-content-id");this.items.map(((i,s)=>{if(i.id===e&&t.target.value){let e,n=o.haxSchemaFromTag(t.target.value);e=n.gizmo&&n.gizmo.tag&&n.demoSchema&&n.demoSchema[0]?h(n.demoSchema[0]):globalThis.document.createElement(tag),this.items[s].contents=e.outerHTML+i.contents,this.resetPopOver(),this.__syncUIAndDataModel()}}))}renderNodeAsItem(t,e,s,n){let a=t.tagName.toLowerCase(),l="hax:bricks",d=a,r="non-heading",c=o.haxSchemaFromTag(a);if(c&&c.gizmo)switch(l=c.gizmo.icon,d=c.gizmo.title,a){case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":d=t.innerText,r="heading"}return i` <li
      class="item content-child content-${r} indent-${n<20?n:20}"
      data-node-index="${e}"
      data-content-parent-id="${s.id}"
      ?data-contents-collapsed="${!s.showContent}"
      ?data-about-to-delete="${s.delete}"
      ?hidden="${this.hideDelete&&s.delete}"
    >
      <div class="btn-contrast">
        <simple-icon-button-lite
          icon="${l}"
          title="Click to preview"
          @click="${this.setActivePreview}"
        ></simple-icon-button-lite>
      </div>
      ${"heading"===r?i`
            <span
              class="label shown"
              ?disabled="${s.metadata.locked}"
              @dblclick="${this.editTitle}"
              >${d}</span
            >
            <span
              class="label-edit"
              @keypress="${this.monitorHeading}"
              @keydown="${this.monitorEsc}"
            ></span>
          `:i`<span class="label shown">${d}</span>`}
      <div class="content-operations">
        <simple-icon-button
          class="content-operation"
          icon="hax:outline-designer-outdent"
          @click="${t=>this.modifyContentAction(t,s,"in")}"
          title="Increase heading"
          ?disabled="${"h1"===a||s.metadata.locked}"
          ?hidden="${"heading"!==r}"
        ></simple-icon-button>
        <simple-icon-button
          icon="hax:keyboard-arrow-up"
          @click="${t=>this.modifyContentAction(t,s,"up")}"
          title="Move up"
          ?disabled="${s.metadata.locked}"
          class="content-operation"
        ></simple-icon-button>
        <simple-icon-button
          icon="hax:keyboard-arrow-down"
          @click="${t=>this.modifyContentAction(t,s,"down")}"
          title="Move down"
          ?disabled="${s.metadata.locked}"
          class="content-operation"
        ></simple-icon-button>
        <simple-icon-button
          class="content-operation"
          icon="hax:outline-designer-indent"
          @click="${t=>this.modifyContentAction(t,s,"out")}"
          title="Decrease Heading"
          ?disabled="${"h6"===a||s.metadata.locked}"
          ?hidden="${"heading"!==r}"
        ></simple-icon-button>
        <simple-icon-button
          class="content-operation"
          icon="editor:format-page-break"
          @click="${t=>this.pageBreakHere(t,s)}"
          title="Promote to page"
          ?disabled="${s.metadata.locked}"
          ?hidden="${"heading"!==r}"
        ></simple-icon-button>
        <simple-icon-button
          icon="delete"
          @click="${t=>this.modifyContentAction(t,s,"delete")}"
          class="content-operation del"
          title="Delete"
          ?disabled="${s.metadata.locked}"
          accent-color="red"
        ></simple-icon-button>
      </div>
    </li>`}setActivePreview(t){let e=t.target.closest("[data-content-parent-id]"),i=parseInt(e.getAttribute("data-node-index"));this.activePreview=e,this.shadowRoot.querySelector("simple-popover").removeAttribute("hidden"),this.shadowRoot.querySelector("simple-popover").target=e,this.activePreviewIndex=i,t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation()}modifyContentAction(t,e,i){if(!e.metadata.locked){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let e=t.target.closest("[data-content-parent-id]"),s=e.getAttribute("data-content-parent-id"),n=parseInt(e.getAttribute("data-node-index")),o=this.items.find((t=>t.id===s));if(o.contents){let t=globalThis.document.createElement("div");t.innerHTML=o.contents;let e="";switch(i){case"up":0!==n&&t.childNodes[n].previousElementSibling.insertAdjacentElement("beforebegin",t.childNodes[n]);break;case"down":n!==t.childNodes.length-1&&t.childNodes[n].nextElementSibling.insertAdjacentElement("afterend",t.childNodes[n])}for(let s=0;s<t.childNodes.length;s++){let o=t.childNodes[s];if(s<n)e+=o.outerHTML;else if(s===n)switch(i){case"delete":this.setAttribute("stop-animation","true");break;case"up":case"down":e+=o.outerHTML;break;case"in":case"out":let t,s=parseInt(o.tagName.toLowerCase().replace("h",""));"in"===i&&s>1?(t=globalThis.document.createElement("h"+(s-1)),t.innerText=o.innerText):"out"===i&&s<6?(t=globalThis.document.createElement(`h${s+1}`),t.innerText=o.innerText):t=o,e+=t.outerHTML}else e+=o.outerHTML}o.contents=e,this.resetPopOver(),this.__syncUIAndDataModel()}}}pageBreakHere(t,e){if(!e.metadata.locked){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let e,i=t.target.closest("[data-content-parent-id]"),s=i.getAttribute("data-content-parent-id"),n=parseInt(i.getAttribute("data-node-index")),o=this.items.find((t=>t.id===s));if(this.items.map(((t,i)=>t.id===s?e=i:null)),o.contents){let t=globalThis.document.createElement("div");t.innerHTML=o.contents;let i="",s="",a=this.t.newPage;for(let e=0;e<t.childNodes.length;e++){let o=t.childNodes[e];e<n?i+=o.outerHTML:e===n?""!=o.innerText&&(a=o.innerText):s+=o.outerHTML}o.contents=i;let l=new r;l.title=a,l.order=o.order+1,l.parent=o.parent,l.indent=o.indent,l.metadata.locked=!1,l.new=!0,l.contents=s,this.items[e].modified=!0,this.items.splice(e+1,0,l),this.resetPopOver(),this.__syncUIAndDataModel()}}}__syncUIAndDataModel(){this._recurseUpdateIndent(),this._schemaOrderUpdate(),setTimeout((()=>{this.requestUpdate(),setTimeout((()=>{this.removeAttribute("stop-animation")}),300)}),0)}collapseAll(){this.items.map(((t,e)=>{this.hasChildren(t.id)&&!t.collapsed&&(this.items[e].collapsed=!0)})),setTimeout((()=>{this.requestUpdate()}),0)}expandAll(){this.items.map(((t,e)=>{this.hasChildren(t.id)&&t.collapsed&&(this.items[e].collapsed=!1)})),setTimeout((()=>{this.requestUpdate()}),0)}getItemParents(t){let e=this.items.find((e=>e.id==t.parent)),i="";for(;e;)i+=e.id+" ",e=this.items.find((t=>t.id==e.parent));return i}getItemParentsCollapsed(t){let e=this.items.find((e=>e.id==t.parent)),i="";for(;e;)e.collapsed&&e.id&&(i+=`collapsed-by-${e.id} `),e=this.items.find((t=>t.id==e.parent));return i}isCollapsed(t){return!!this.items.find((e=>e.id==t)).collapsed}hasChildren(t){return!!this.items.find((e=>e.parent==t))}collapseExpand(t){let e=t.target.closest("[data-item-id]").getAttribute("data-item-id");this.items.map(((t,i)=>{t.id!==e||this.isLocked(i)||(this.items[i].collapsed?this.items[i].collapsed=!1:this.items[i].collapsed=!0,this.requestUpdate())}))}toggleContent(t){let e=t.target.closest("[data-item-id]");if(e&&!t.target.disabled){let t=e.getAttribute("data-item-id");this.items.map(((e,i)=>{e.id===t&&(this.items[i].showContent?this.items[i].showContent=!1:this.items[i].showContent=!0)})),this.requestUpdate()}}editTitle(t){t.target.classList.remove("shown");let e=t.target.nextElementSibling;if(e.setAttribute("contenteditable","true"),e.classList.add("shown"),e.innerText=t.target.innerText,e.focus(),this.shadowRoot.getSelection){var i=globalThis.document.createRange();i.selectNodeContents(e),this.shadowRoot.getSelection().removeAllRanges(),this.shadowRoot.getSelection().addRange(i)}else try{globalThis.document.execCommand("selectAll",!1,null)}catch(t){console.warn(t)}}monitorTitle(t){if("Enter"===t.key){t.target.classList.remove("shown"),t.target.previousElementSibling.classList.add("shown"),t.target.removeAttribute("contenteditable");let e=t.target.closest("[data-item-id]").getAttribute("data-item-id");for(let i=0;i<this.items.length;i++)this.items[i].id===e&&""!=t.target.innerText&&(this.items[i].new||(this.items[i].modified=!0),this.items[i].title=t.target.innerText);this.requestUpdate()}}monitorHeading(t){if("Enter"===t.key){t.target.classList.remove("shown"),t.target.previousElementSibling.classList.add("shown"),t.target.removeAttribute("contenteditable");let e=t.target.closest("[data-content-parent-id]"),i=e.getAttribute("data-content-parent-id"),s=parseInt(e.getAttribute("data-node-index")),n=this.items.find((t=>t.id===i));if(n.contents){let e=globalThis.document.createElement("div");e.innerHTML=n.contents;let i="";for(let n=0;n<e.childNodes.length;n++){let o=e.childNodes[n];n<s?i+=o.outerHTML:n===s?(o.innerText=t.target.innerText,i+=o.outerHTML):i+=o.outerHTML}n.contents=i,this.resetPopOver(),this.requestUpdate()}}}monitorEsc(t){"Escape"===t.key?(t.target.classList.remove("shown"),t.target.removeAttribute("contenteditable"),t.target.previousElementSibling.classList.add("shown"),t.target.innerText=t.target.previousElementSibling.innerText):"Enter"===t.key&&(this._blurBlock=!0)}blurTitle(t){this._blurBlock||(t.target.classList.remove("shown"),t.target.removeAttribute("contenteditable"),t.target.previousElementSibling.classList.add("shown"),t.target.innerText=t.target.previousElementSibling.innerText),setTimeout((()=>{this._blurBlock=!1}),0)}_mouseDownDrag(t){let e=t.target.closest("[data-item-id]").getAttribute("data-item-id");this.items.map(((t,i)=>{t.id===e&&this.hasChildren(t.id)&&(this.items[i].collapsed=!0)})),setTimeout((()=>{this.requestUpdate()}),0)}_dragEnter(t){this._targetDrop!==t.target.closest("[data-item-id]")&&(t.preventDefault(),t.target.closest("[data-item-id]").classList.add("outline-designer-hovered"),this._targetDrop=t.target.closest("[data-item-id]"))}_dragLeave(t){this._targetDrop!==t.target.closest("[data-item-id]")&&t.target.closest("[data-item-id]").classList.remove("outline-designer-hovered")}_dragEnd(t){if(this._targetDrag&&this._targetDrop){let t=null,e=null;for(let i=0;i<this.items.length;i++){let s=this.items[i];s.id===this._targetDrop.getAttribute("data-item-id")&&(t=i),s.id===this._targetDrag.getAttribute("data-item-id")&&(e=i)}null!==e&&null!==t&&(this.items[e].new||(this.items[e].modified=!0),this.items[e].order=this.items[t].order,0===this.items[e].order&&(this.items[e].order=-1),this.items[e].indent=this.items[t].indent,this.items[e].parent=this.items[t].parent,this.hasChildren(this.items[e].id)&&(this.items[e].collapsed=!1)),this._targetDrag=null,this._targetDrop=null,this.setAttribute("stop-animation","true"),this.__syncUIAndDataModel()}}_dragStart(t){if(null==t.target.getAttribute("disabled")){let e=t.target.closest("[data-item-id]");this._targetDrop=null,this._targetDrag=e,this._mouseDownDrag(t),t.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.dropEffect="move",t.dataTransfer.setDragImage(e,24,16)),t.stopPropagation(),t.stopImmediatePropagation()}}static get properties(){return{haxGizmos:{type:Array},hideDelete:{type:Boolean},activeItemForActions:{type:String},storeTools:{type:Boolean},eventData:{type:Object},items:{type:Array},appReady:{type:Boolean},activePreview:{type:Object},activePreviewIndex:{type:Number},hideContentOps:{type:Boolean,reflect:!0,attribute:"hide-content-ops"},fidelity:{type:String}}}updated(t){super.updated(t),t.forEach(((t,e)=>{"fidelity"===e&&this[e]&&this[e],"activePreview"===e&&t&&t.classList.remove("active-preview-item"),"activePreview"===e&&this[e]&&this[e].classList.add("active-preview-item")}))}firstUpdated(t){super.firstUpdated&&super.firstUpdated(t),this.items&&setTimeout((()=>{this.__syncUIAndDataModel()}),0)}static get tag(){return"outline-designer"}addItemToTop(){this.setAttribute("stop-animation","true"),this.addNewItem("top"),this.__syncUIAndDataModel()}async getData(){let t=this.eventData;if(t.items=[...this.items],this.storeTools){const e=this.shadowRoot.querySelector("#itemselector").value,i=this.shadowRoot.querySelector("#targetselector").value;let s=0;await t.items.map((async(n,o)=>{if(e&&null==n.parent){s++;let n=await a.findItemAsObject(e);switch(i){case"below":t.items[o].parent=n.parent,t.items[o].order=parseInt(n.order)+s;break;case"above":t.items[o].parent=n.parent,t.items[o].order=parseInt(n.order)-s;break;case"children":t.items[o].parent=e}}}))}return t}isLocked(t){return!!(!1!==t&&this.items[t]&&this.items[t].metadata&&this.items[t].metadata.locked)}addNewItem(t,e=!1,i=[]){let s=1;"top"===t&&(t=0,s=-1);let n={indent:0,parent:null,order:0};this.items&&this.items.length>0&&this.items[t]&&(n=this.items[t]);let o=new r;if(o.order=n.order+s,o.parent=n.parent,o.indent=n.indent,o.metadata.locked=!1,o.new=!0,e?(o.title=`${this.t.copyOf} ${n.title}`,o.contents=n.contents,o.duplicate=n.id):o.contents="<p></p>",i.push(o),this.items&&this.items.length>0&&this.items[t]&&this.hasChildren(this.items[t].id)&&e){let e={};e[this.items[t].id]=o.id,i=this.recurseCopyChildren(this.items[t].id,e,i)}this.items&&this.items.length>0?i.forEach(((e,i)=>this.items.splice(t+i+1,0,e))):i.forEach((t=>this.items.push(t)))}recurseCopyChildren(t,e,i){let s=this.items.filter((e=>e.parent==t));for(let t=0;t<s.length;t++){const n=s[t];let o=new r;o.order=n.order,o.parent=e[n.parent],o.indent=n.indent,o.metadata.locked=!1,o.new=!0,o.title=`${this.t.copyOf} ${n.title}`,o.contents=n.contents,o.collapsed=n.collapsed,o.duplicate=s[t].id,e[s[t].id]=o.id,i.push(o),this.hasChildren(s[t].id)&&this.recurseCopyChildren(s[t].id,e,i)}return i}recurseAction(t,e,i=!0){let s=this.items.filter((e=>e.parent==t));for(let t=0;t<s.length;t++)this.items.map(((n,o)=>{if(n.id===s[t].id)switch(e){case"delete":this.items[o].delete=i;break;case"lock":this.items[o].metadata.locked=i}})),this.hasChildren(s[t].id)&&this.recurseAction(s[t].id,e,i);return!0}itemOp(t,e){if(!1!==t&&this.items[t]&&e){if(this.items[t].metadata.locked)"lock"===e&&(this.items[t].metadata.locked=!1,this.hasChildren(this.items[t].id)&&this.recurseAction(this.items[t].id,e,this.items[t].metadata.locked));else switch(e){case"goto":this.dispatchEvent(new CustomEvent("simple-modal-hide",{bubbles:!0,cancelable:!0,detail:{}}));let i=this.items[t].slug||this.items[t].location;globalThis.location.href=i;case"lock":this.items[t].metadata.locked=!0,this.hasChildren(this.items[t].id)&&this.recurseAction(this.items[t].id,e,this.items[t].metadata.locked);break;case"delete":this.items[t].delete?this.items[t].delete=!1:this.items[t].delete=!0,this.hasChildren(this.items[t].id)&&this.recurseAction(this.items[t].id,e,this.items[t].delete);break;case"add":this.setAttribute("stop-animation","true"),this.addNewItem(t);break;case"duplicate":this.setAttribute("stop-animation","true"),this.addNewItem(t,!0);break;case"in":if(0!==t&&this.items[t].parent!=this.items[t-1].id){let e=this.items[t-1];this.items[t].parent=e.id,this.items[t].order=0,this.items[t].indent=parseInt(e.indent)+1,this.items[t].new||(this.items[t].modified=!0)}break;case"out":if(null!==this.items[t].parent){let e=this.items.find((e=>this.items[t].parent===e.id));this.items[t].parent=e.parent,this.items[t].order=parseInt(e.order)+1,this.items[t].indent=parseInt(e.indent),this.items[t].new||(this.items[t].modified=!0)}break;case"up":case"down":this.setAttribute("stop-animation","true");let s=this.items[t],n=[];this.items.map((t=>{t.parent===s.parent&&n.push(t)})),n.sort(((t,e)=>t.order<e.order?-1:t.order>e.order?1:0));let o=null;if(n.map(((t,i)=>{"up"===e&&i>0&&t.id===s.id?o=n[i-1]:"down"===e&&i<n.length-1&&t.id===s.id&&(o=n[i+1])})),o){const t=parseInt(o.order+".0"),e=parseInt(s.order+".0");this.items.map(((i,n)=>{i.id===o.id?(this.items[n].order=e,this.items[n].new||(this.items[n].modified=!0)):i.id===s.id&&(this.items[n].order=t,this.items[n].new||(this.items[n].modified=!0))}))}}this.__syncUIAndDataModel()}}_recurseUpdateIndent(t={id:null},e=0){this.items.map(((i,s)=>{i.parent==t.id&&(this.items[s].indent=e,this._recurseUpdateIndent(this.items[s],e+1))}))}_schemaOrderUpdate(){let t=new c,e=t.itemsToNodes(this.items),i=t.nodesToItems(e),s=[];for(var n in i){let t=this.items.find((t=>t.id===i[n].id));t&&(delete t.children,s.push(t))}this.items=s}}customElements.define(OutlineDesigner.tag,OutlineDesigner);