/**
 * Copyright 2019 The Pennsylvania State University
 * @license Apache-2.0, see License.md for full text.
 */
import{LitElement as e,html as t,css as i}from"../../lit/index.js";import{getRange as n}from"../utils/utils.js";import"../json-outline-schema/json-outline-schema.js";import"../simple-icon/simple-icon.js";import"../simple-icon/lib/simple-icons.js";import{normalizeEventPath as l}from"../utils/utils.js";class EditableOutline extends e{static get styles(){return[i`
        :host {
          display: block;
          font-family: "Noto Serif", serif;
        }

        :host([hidden]) {
          display: none;
        }

        .button-wrapper {
          line-height: 36px;
          position: -webkit-sticky;
          position: sticky;
          top: 0px;
          background-color: white;
          display: block;
          justify-content: space-evenly;
        }
        @media (max-width: 1000px) {
          button span {
            opacity: 0;
            visibility: hidden;
            position: absolute;
            left: -9999px;
          }
        }

        button {
          height: 32px;
          font-size: 10px;
          margin: 0;
          padding: 0 8px;
        }

        button span {
          padding-left: 4px;
          pointer-events: none;
        }

        #outline {
          margin: 0;
        }

        ul {
          font-size: 16px;
          line-height: 32px;
          padding-left: 32px;
          visibility: visible;
          opacity: 1;
          overflow: hidden;
          height: auto;
          transition: 0.2s ease-in-out all;
        }

        li {
          font-size: 16px;
          line-height: 32px;
          padding: 4px;
          transition: 0.2s linear all;
        }

        ul:hover {
          outline: 1px solid #eeeeee;
        }

        li.collapsed-title {
          background-color: #dddddd;
        }

        li.collapsed-title:after {
          content: "    ( Double-click to expand )";
        }

        li:after {
          transition: 0.4s ease-in-out all;
          opacity: 0;
          font-size: 11px;
          visibility: hidden;
        }

        li.collapsed-title:hover:after {
          font-style: italic;
          opacity: 1;
          visibility: visible;
        }

        ul.collapsed-content {
          visibility: hidden;
          opacity: 0;
          height: 0;
        }

        li:focus,
        li:active,
        li:hover {
          background-color: #eeeeee;
          outline: 1px solid #cccccc;
        }

        simple-icon {
          pointer-events: none;
        }

        li[data-jos-published="false"] {
          text-decoration: line-through;
        }
      `]}render(){return t` <div class="button-wrapper">
        <button @click="${this.buttonEvents}" id="add" title="Add a new node">
          <simple-icon icon="icons:add"></simple-icon><span>Add</span>
        </button>
        <button
          @click="${this.buttonEvents}"
          id="collapse"
          title="Toggle active node collapsed status"
        >
          <simple-icon icon="icons:swap-vert"></simple-icon
          ><span>Toggle active</span>
        </button>
        <button
          @click="${this.buttonEvents}"
          id="collapseall"
          title="Collapse all nodes"
        >
          <simple-icon icon="icons:swap-vert"></simple-icon
          ><span>Collapse all</span>
        </button>
        <button
          @click="${this.buttonEvents}"
          id="expandall"
          title="Expand all nodes"
        >
          <simple-icon icon="icons:swap-vert"></simple-icon
          ><span>Expand all</span>
        </button>
        <button
          @click="${this.buttonEvents}"
          id="down"
          title="Move active node down"
        >
          <simple-icon icon="icons:arrow-downward"></simple-icon
          ><span>Move down</span>
        </button>
        <button
          @click="${this.buttonEvents}"
          id="up"
          title="Move active node up"
        >
          <simple-icon icon="icons:arrow-upward"></simple-icon
          ><span>Move up</span>
        </button>
        <button
          @click="${this.buttonEvents}"
          id="outdent"
          title="Outdent active node"
        >
          <simple-icon icon="editor:format-indent-decrease"></simple-icon
          ><span>Outdent</span>
        </button>
        <button
          @click="${this.buttonEvents}"
          id="indent"
          title="Indent active node"
        >
          <simple-icon icon="editor:format-indent-increase"></simple-icon
          ><span>Indent</span>
        </button>
        <button
          @click="${this.buttonEvents}"
          id="duplicate"
          title="Duplicate active node tree"
        >
          <simple-icon icon="icons:content-copy"></simple-icon
          ><span>Duplicate</span>
        </button>
      </div>
      <ul id="outline"></ul>`}static get properties(){return{...super.properties,items:{type:Array},editMode:{type:Boolean,attribute:"edit-mode"},__outlineNode:{type:Object}}}constructor(){super(),this.items=[],this.editMode=!1,this.jos=window.JSONOutlineSchema.requestAvailability(),setTimeout((()=>{this.addEventListener("dblclick",this._collapseClickHandler.bind(this))}),0)}static get tag(){return"editable-outline"}_collapse(e){let t=this.getSelectionNode();t&&"LI"===t.tagName&&t.nextElementSibling&&"UL"===t.nextElementSibling.tagName&&(t.classList.toggle("collapsed-title"),t.nextElementSibling.classList.toggle("collapsed-content"))}_expandall(e){this.shadowRoot.querySelectorAll("li").forEach((e=>{e.classList.remove("collapsed-title")})),this.shadowRoot.querySelectorAll("ul").forEach((e=>{e.classList.remove("collapsed-content")}))}_collapseall(e){this.shadowRoot.querySelectorAll("li").forEach((e=>{e.nextElementSibling&&"UL"===e.nextElementSibling.tagName&&(e.classList.add("collapsed-title"),e.nextElementSibling.classList.add("collapsed-content"))}))}_onKeyDown(e){if(this.editMode)switch(e.key){case"Enter":this._enterPressed(e);break;case"ArrowUp":this._upPressed(e);break;case"ArrowDown":this._downPressed(e);break;case"Tab":e.shiftKey?this._tabBackKeyPressed(e):this._tabKeyPressed(e)}}_collapseClickHandler(e){let t,i=0,n=!0;for(var o=l(e);n&&o.length>i+1;)t=o[i],"LI"===t.tagName&&t.nextElementSibling&&"UL"===t.nextElementSibling.tagName&&(t.classList.toggle("collapsed-title"),t.nextElementSibling.classList.toggle("collapsed-content"),n=!1),i++}firstUpdated(){this.__outlineNode=this.shadowRoot.querySelector("#outline"),this.__outlineNode.addEventListener("keydown",this._onKeyDown.bind(this)),this._observer=new MutationObserver(this._observeRecord.bind(this)),this._observer.observe(this.__outlineNode,{childList:!0,subtree:!0})}updated(e){e.forEach(((e,t)=>{if(["editMode","items"].includes(t)){let e=`${t.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase()}-changed`;this.dispatchEvent(new CustomEvent(e,{detail:{value:this[t]}}))}}))}_observeRecord(e){for(var t in e){let i=e[t];if(i.addedNodes.length>0)for(let e in i.addedNodes)i.addedNodes[e].tagName&&("LI"===i.addedNodes[e].tagName?(this.__blockScrub||this.jos.scrubElementJOSData(i.addedNodes[e]),i.addedNodes[e].setAttribute("contenteditable","true")):"UL"===i.addedNodes[e].tagName&&(this.__blockScrub||this.jos.scrubElementJOSData(i.addedNodes[e])))}setTimeout((()=>{this.__blockScrub=!1}),100)}disconnectedCallback(){this.__outlineNode.removeEventListener("keydown",this._onKeyDown.bind(this)),this._observer.disconnect(),super.disconnectedCallback()}buttonEvents(e){switch(e.target.id){case"add":this._add(e);break;case"collapse":this._collapse(e);break;case"collapseall":this._collapseall(e);break;case"expandall":this._expandall(e);break;case"indent":this._indent();break;case"outdent":this._outdent();break;case"up":this._move("up");break;case"down":this._move("down");break;case"duplicate":this._duplicate()}}_duplicate(){try{this.__blockScrub=!1;let e=this.getSelectionNode();if(e&&"LI"===e.tagName)if(null!==e.nextElementSibling&&"UL"===e.nextElementSibling.tagName){const t=e.nextElementSibling.cloneNode(!0);e.parentNode.insertBefore(t,e.nextElementSibling.nextElementSibling);const i=e.cloneNode(!0);e.parentNode.insertBefore(i,e.nextElementSibling.nextElementSibling)}else{const t=e.cloneNode(!0);e.parentNode.insertBefore(t,e.nextElementSibling)}}catch(e){console.log(e)}}_move(e){try{let t=this.getSelectionNode(),i=t,n=!1;if(null==t)return!1;for(;!n&&i.parentNode;)"outline"===i.id&&(n=!0),i=i.parentNode;n&&t&&"LI"===t.tagName&&("up"===e?null!==t.previousElementSibling&&(t.nextElementSibling&&"UL"===t.nextElementSibling.tagName?("UL"===t.previousElementSibling.tagName&&(this.__blockScrub=!0,t.parentNode.insertBefore(t.previousElementSibling,t.nextElementSibling.nextElementSibling)),this.__blockScrub=!0,t.parentNode.insertBefore(t.previousElementSibling,t.nextElementSibling.nextElementSibling),t.focus()):("UL"===t.previousElementSibling.tagName&&(this.__blockScrub=!0,t.parentNode.insertBefore(t.previousElementSibling,t.nextElementSibling)),this.__blockScrub=!0,t.parentNode.insertBefore(t.previousElementSibling,t.nextElementSibling),t.focus())):"down"===e&&null!==t.nextElementSibling&&(t.nextElementSibling&&"UL"===t.nextElementSibling.tagName&&null!==t.nextElementSibling.nextElementSibling?("LI"===t.nextElementSibling.nextElementSibling.tagName&&null!==t.nextElementSibling.nextElementSibling.nextElementSibling&&"UL"===t.nextElementSibling.nextElementSibling.nextElementSibling.tagName&&(this.__blockScrub=!0,t.parentNode.insertBefore(t.nextElementSibling.nextElementSibling,t)),this.__blockScrub=!0,t.parentNode.insertBefore(t.nextElementSibling.nextElementSibling,t),t.focus()):"LI"===t.nextElementSibling.tagName&&(null!==t.nextElementSibling.nextElementSibling&&"UL"===t.nextElementSibling.nextElementSibling.tagName&&(this.__blockScrub=!0,t.parentNode.insertBefore(t.nextElementSibling,t)),this.__blockScrub=!0,t.parentNode.insertBefore(t.nextElementSibling,t),t.focus())))}catch(e){console.log(e)}}importJsonOutlineSchemaItems(){this.__blockScrub=!0,setTimeout((()=>{for(;this.__outlineNode.firstChild;)this.__outlineNode.removeChild(this.__outlineNode.firstChild);0===this.items.length&&(this.items=[...this.jos.items]);let e=this.jos.itemsToNodes(this.items);for(;e.firstChild;)this.__blockScrub=!0,this.__outlineNode.appendChild(e.firstChild);return this.shadowRoot.querySelectorAll("li").forEach((e=>{e.setAttribute("contenteditable","true")})),e}),0)}exportJsonOutlineSchemaItems(e=!1){return this.jos.nodesToItems(this.__outlineNode,e)}_upPressed(e){let t=this.getSelectionNode();t&&t.previousSibling&&"LI"===t.previousSibling.tagName?t.previousSibling.focus():t&&t.previousSibling&&"UL"===t.previousSibling.tagName&&t.previousSibling.firstChild&&"LI"===t.previousSibling.firstChild.tagName?t.previousSibling.firstChild.focus():t&&null==t.previousSibling&&"UL"===t.parentNode.tagName&&t.parentNode.previousSibling&&"LI"===t.parentNode.previousSibling.tagName&&t.parentNode.previousSibling.focus()}_downPressed(e){let t=this.getSelectionNode();t&&t.nextSibling&&"LI"===t.nextSibling.tagName?t.nextSibling.focus():t&&t.nextSibling&&"UL"===t.nextSibling.tagName&&t.nextSibling.firstChild&&"LI"===t.nextSibling.firstChild.tagName?t.nextSibling.firstChild.focus():t&&null==t.nextSibling&&"UL"===t.parentNode.tagName&&t.parentNode.nextSibling&&"LI"===t.parentNode.nextSibling.tagName&&t.parentNode.nextSibling.focus()}_tabKeyPressed(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),e.detail.keyboardEvent&&(e.detail.keyboardEvent.preventDefault(),e.detail.keyboardEvent.stopPropagation(),e.detail.keyboardEvent.stopImmediatePropagation());try{this._indent()}catch(e){}}_tabBackKeyPressed(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),e.detail.keyboardEvent&&(e.detail.keyboardEvent.preventDefault(),e.detail.keyboardEvent.stopPropagation(),e.detail.keyboardEvent.stopImmediatePropagation());try{this._outdent()}catch(e){}}_enterPressed(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),e.detail.keyboardEvent&&(e.detail.keyboardEvent.preventDefault(),e.detail.keyboardEvent.stopPropagation(),e.detail.keyboardEvent.stopImmediatePropagation()),this._add()}_add(){let e=document.createElement("li");e.setAttribute("contenteditable","true");let t=this.getSelectionNode();if(null==this.__outlineNode.querySelector("li")||!t||t.tagName&&"UL"!=t.tagName&&"LI"!=t.tagName)this.__outlineNode.appendChild(e);else{null!=t.tagName&&"LI"==t.tagName||!t.parentNode||(t=t.parentNode),null==t.nextSibling?t.parentNode.appendChild(e):t.parentNode.insertBefore(e,t.nextSibling);try{e.focus()}catch(e){}}}_outdent(){this.__blockScrub=!0;try{let e=this.getSelectionNode();if(null==e)return!1;const t=e.parentNode;e.parentNode&&e.parentNode!=this.__outlineNode&&null!=e.parentNode.nextSibling?(e.parentNode.parentNode.insertBefore(e,e.parentNode.nextSibling),0==t.children.length&&t.remove()):e.parentNode&&e.parentNode!=this.__outlineNode&&null==e.parentNode.nextSibling&&(e.parentNode.parentNode.appendChild(e),0==t.children.length&&t.remove()),e.focus()}catch(e){console.warn(e)}}_indent(){this.__blockScrub=!0;try{let e=this.getSelectionNode();if(null==e)return!1;if(null!=e.previousSibling&&"LI"===e.previousSibling.tagName){let t;e.nextSibling&&"UL"===e.nextSibling.tagName?t=e.nextSibling:(t=document.createElement("ul"),e.parentNode.insertBefore(t,e)),t.appendChild(e),e.focus()}else null!=e.previousSibling&&"UL"===e.previousSibling.tagName&&(e.previousSibling.appendChild(e),e.focus())}catch(e){console.warn(e)}}getSelectionNode(){let e=this.getDeepSelection().anchorNode;return e&&(null==e.tagName||"LI"!=e.tagName)&&e.parentNode&&(e=e.parentNode),e}getDeepSelection(){return this.shadowRoot.getSelection?this.shadowRoot.getSelection():n(this.__outlineNode.parentNode)?n(this.__outlineNode.parentNode):window.getSelection()}getDeepRange(){let e=this.getSelection();return e&&e.getRangeAt&&e.rangeCount?e.getRangeAt(0):e||!1}}customElements.define(EditableOutline.tag,EditableOutline);export{EditableOutline};