text: /**
   * Copyright 2018 The Pennsylvania State University
   * @license Apache-2.0, see License.md for full text.
   */
  import{LitElement as e,html as t}from"../../../../lit-element/lit-element.js";import{store as s}from"./haxcms-site-store.js";import{autorun as i,toJS as a}from"../../../../mobx/lib/mobx.module.js";import"../../../../@polymer/iron-ajax/iron-ajax.js";import"../../../jwt-login/jwt-login.js";import"../../../h-a-x/h-a-x.js";import"../../../mdi-iconset-svg/lib/mdi-action-iconset-svg.js";import"../../../simple-toast/simple-toast.js";import"../../../simple-modal/simple-modal.js";import"../../../../@polymer/paper-button/paper-button.js";import"../../../simple-fields/lib/simple-fields-form.js";import"./haxcms-site-dashboard.js";class HAXCMSSiteEditor extends e{static get tag(){return"haxcms-site-editor"}constructor(){super(),this.__disposer=[],this.method="POST",this.editMode=!1}render(){return t`
        <style>
          :host {
            display: block;
          }
          #editbutton {
            position: fixed;
            bottom: 0;
            right: 0;
            margin: 16px;
            padding: 2px;
            width: 40px;
            height: 40px;
            visibility: visible;
            opacity: 1;
            transition: all 0.4s ease;
            z-index: 1000;
          }
          #outlinebutton {
            position: fixed;
            bottom: 0;
            right: 46px;
            margin: 16px;
            padding: 2px;
            width: 40px;
            height: 40px;
            visibility: visible;
            opacity: 1;
            transition: all 0.4s ease;
            z-index: 1000;
          }
          :host([edit-mode]) #editbutton {
            width: 100%;
            z-index: 100;
            right: 0;
            bottom: 0;
            border-radius: 0;
            height: 80px;
            margin: 0;
            padding: 8px;
            background-color: var(--paper-blue-500) !important;
          }
          h-a-x {
            margin: auto;
            display: none;
          }
          :host([edit-mode]) h-a-x {
            display: block;
          }
        </style>
        <iron-ajax
          reject-with-request
          .headers='{"Authorization": "Bearer ${this.jwt}"}'
          id="nodeupdateajax"
          .url="${this.saveNodePath}"
          .method="${this.method}"
          content-type="application/json"
          handle-as="json"
          @response="${this._handleNodeResponse}"
          @last-error-changed="${this.lastErrorChanged}"
        ></iron-ajax>
        <iron-ajax
          reject-with-request
          .headers='{"Authorization": "Bearer ${this.jwt}"}'
          id="outlineupdateajax"
          .url="${this.saveOutlinePath}"
          .method="${this.method}"
          content-type="application/json"
          handle-as="json"
          @response="${this._handleOutlineResponse}"
          @last-error-changed="${this.lastErrorChanged}"
        ></iron-ajax>
        <iron-ajax
          reject-with-request
          .headers='{"Authorization": "Bearer ${this.jwt}"}'
          id="manifestupdateajax"
          .url="${this.saveManifestPath}"
          .method="${this.method}"
          content-type="application/json"
          handle-as="json"
          @response="${this._handleManifestResponse}"
          @last-error-changed="${this.lastErrorChanged}"
        ></iron-ajax>
        <iron-ajax
          reject-with-request
          .headers='{"Authorization": "Bearer ${this.jwt}"}'
          id="publishajax"
          .loading="${this.publishing}"
          @loading-changed="${this.loadingChanged}"
          .url="${this.publishSitePath}"
          .method="${this.method}"
          content-type="application/json"
          handle-as="json"
          @response="${this._handlePublishResponse}"
          @last-error-changed="${this.lastErrorChanged}"
        ></iron-ajax>
        <iron-ajax
          reject-with-request
          .headers='{"Authorization": "Bearer ${this.jwt}"}'
          id="revertajax"
          .url="${this.revertSitePath}"
          .method="${this.method}"
          content-type="application/json"
          handle-as="json"
          @response="${this._handleRevertResponse}"
          @last-error-changed="${this.lastErrorChanged}"
        ></iron-ajax>
        <iron-ajax
          reject-with-request
          .headers='{"Authorization": "Bearer ${this.jwt}"}'
          id="syncajax"
          .url="${this.syncSitePath}"
          .method="${this.method}"
          content-type="application/json"
          handle-as="json"
          @response="${this._handleSyncResponse}"
          @last-error-changed="${this.lastErrorChanged}"
        ></iron-ajax>
        <iron-ajax
          reject-with-request
          .headers='{"Authorization": "Bearer ${this.jwt}"}'
          id="createajax"
          .url="${this.createNodePath}"
          .method="${this.method}"
          content-type="application/json"
          handle-as="json"
          @response="${this._handleCreateResponse}"
          @last-error-changed="${this.lastErrorChanged}"
          @last-response-changed="${this.__createNodeResponseChanged}"
        ></iron-ajax>
        <iron-ajax
          reject-with-request
          .headers='{"Authorization": "Bearer ${this.jwt}"}'
          id="deleteajax"
          .url="${this.deleteNodePath}"
          .method="${this.method}"
          content-type="application/json"
          handle-as="json"
          @response="${this._handleDeleteResponse}"
          @last-error-changed="${this.lastErrorChanged}"
          @last-response-changed="${this.__deleteNodeResponseChanged}"
        ></iron-ajax>
        <iron-ajax
          reject-with-request
          headers='{"Authorization": "Bearer ${this.jwt}"}'
          id="getuserdata"
          url="${this.getUserDataPath}"
          method="${this.method}"
          content-type="application/json"
          handle-as="json"
          @response="${this._handleUserDataResponse}"
          @last-error-changed="${this.lastErrorChanged}"
        ></iron-ajax>
        <h-a-x
          id="hax"
          element-align="left"
          offset-margin="0 0 0 48px"
          hide-panel-ops="hide-panel-ops"
        ></h-a-x>
      `}static get properties(){return{getUserDataPath:{type:String,attribute:"get-user-data-path"},method:{type:String},jwt:{type:String},saveNodePath:{type:String,attribute:"save-node-path"},createNodePath:{type:String,attribute:"create-node-path"},deleteNodePath:{type:String,attribute:"delete-node-path"},saveManifestPath:{type:String,attribute:"save-manifest-path"},publishSitePath:{type:String,attribute:"publish-site-path"},revertSitePath:{type:String,attribute:"revert-site-path"},appendTarget:{type:Object},appElement:{type:Object},syncSitePath:{type:String,attribute:"sync-site-path"},publishing:{type:Boolean},saveOutlinePath:{type:String,attribute:"save-outline-path"},appStore:{type:Object},editMode:{type:Boolean,reflect:!0,attribute:"edit-mode"},activeItem:{type:Object},manifest:{type:Object},getNodeFieldsPath:{type:String,attribute:"get-node-fields-path"},getSiteFieldsPath:{type:String,attribute:"save-site-fields-path"},getFormToken:{type:String,attribute:"get-form-token"},siteDashboard:{type:Object}}}__deleteNodeResponseChanged(e){this.__deleteNodeResponse=e.detail.value}__createNodeResponseChanged(e){this.__createNodeResponse=e.detail.value}_handleUserDataResponse(e){e.detail.response&&e.detail.response.data&&(s.userData=e.detail.response.data)}lastErrorChanged(e){if(e.detail.value){console.error(e);let t=null;switch(t=e.path&&e.path[0]?e.path[0]:e.originalTarget?e.originalTarget:e.target,parseInt(e.detail.value.status)){case 401:this.dispatchEvent(new CustomEvent("jwt-login-logout",{composed:!0,bubbles:!0,cancelable:!1,detail:{redirect:!0}}));break;case 403:this.dispatchEvent(new CustomEvent("jwt-login-refresh-token",{composed:!0,bubbles:!0,cancelable:!1,detail:{element:{obj:this,callback:"refreshRequest",params:[t]}}}));break;default:const s=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:e.detail.value.status+" "+e.detail.value.statusText}});window.dispatchEvent(s)}}}refreshRequest(e,t){this.jwt=e,t.body.jwt=e,t.headers={Authorization:`Bearer ${this.jwt}`},setTimeout(()=>{t.generateRequest()},0)}loadingChanged(e){this.loading=e.detail.value}createRenderRoot(){return this}firstUpdated(e){if(i(e=>{this.editMode=a(s.editMode),this.__disposer.push(e)}),i(e=>{this.manifest=a(s.manifest),this.__disposer.push(e)}),i(e=>{this.activeItem=a(s.activeItem),this.__disposer.push(e)}),window.SimpleToast.requestAvailability(),window.SimpleModal.requestAvailability(),window.addEventListener("jwt-login-refresh-error",this._tokenRefreshFailed.bind(this)),window.addEventListener("hax-store-ready",this._storeReadyToGo.bind(this)),window.addEventListener("json-outline-schema-active-item-changed",this._newActiveItem.bind(this)),window.addEventListener("json-outline-schema-active-body-changed",this._bodyChanged.bind(this)),window.addEventListener("haxcms-save-outline",this.saveOutline.bind(this)),window.addEventListener("haxcms-save-node",this.saveNode.bind(this)),window.addEventListener("haxcms-save-node-details",this.saveNodeDetails.bind(this)),window.addEventListener("haxcms-save-site-data",this.saveManifest.bind(this)),window.addEventListener("haxcms-load-node-fields",this.loadNodeFields.bind(this)),window.addEventListener("haxcms-load-site-dashboard",this.loadSiteDashboard.bind(this)),window.addEventListener("haxcms-load-user-data",this.loadUserData.bind(this)),window.addEventListener("haxcms-publish-site",this.publishSite.bind(this)),window.addEventListener("haxcms-sync-site",this.syncSite.bind(this)),window.addEventListener("haxcms-git-revert-last-commit",this.revertCommit.bind(this)),window.addEventListener("haxcms-create-node",this.createNode.bind(this)),window.addEventListener("haxcms-delete-node",this.deleteNode.bind(this)),window.HaxStore.ready){let e={detail:!0};this._storeReadyToGo(e)}window.dispatchEvent(new CustomEvent("haxcms-site-editor-loaded",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))}updated(e){e.forEach((e,t)=>{"appStore"==t&&this.querySelector("#hax").setAttribute("app-store",JSON.stringify(this[t])),"publishing"==t?this._publishingChanged(this[t],e):"activeItem"==t?(this.dispatchEvent(new CustomEvent("manifest-changed",{detail:this[t]})),this._activeItemChanged(this[t],e)):"manifest"==t&&(this.dispatchEvent(new CustomEvent("manifest-changed",{detail:this[t]})),this._manifestChanged(this[t],e))})}_tokenRefreshFailed(e){401==e.detail.value.status&&this.dispatchEvent(new CustomEvent("jwt-login-logout",{composed:!0,bubbles:!0,cancelable:!1,detail:{redirect:!0}}))}disconnectedCallback(){for(var e in this.siteDashboard&&(this.siteDashboard.remove(),delete this.siteDashboard),this.__disposer)this.__disposer[e].dispose();window.removeEventListener("jwt-login-refresh-error",this._tokenRefreshFailed.bind(this)),window.removeEventListener("hax-store-ready",this._storeReadyToGo.bind(this)),window.removeEventListener("haxcms-save-outline",this.saveOutline.bind(this)),window.removeEventListener("haxcms-save-node",this.saveNode.bind(this)),window.removeEventListener("haxcms-save-node-details",this.saveNodeDetails.bind(this)),window.removeEventListener("haxcms-save-site-data",this.saveManifest.bind(this)),window.removeEventListener("haxcms-publish-site",this.publishSite.bind(this)),window.removeEventListener("haxcms-sync-site",this.syncSite.bind(this)),window.removeEventListener("haxcms-git-revert-last-commit",this.revertCommit.bind(this)),window.removeEventListener("json-outline-schema-active-item-changed",this._newActiveItem.bind(this)),window.removeEventListener("json-outline-schema-active-body-changed",this._bodyChanged.bind(this)),window.removeEventListener("haxcms-load-node-fields",this.loadNodeFields.bind(this)),window.removeEventListener("haxcms-load-site-dashboard",this.loadSiteDashboard.bind(this)),window.removeEventListener("haxcms-load-user-data",this.loadUserData.bind(this)),window.removeEventListener("haxcms-create-node",this.createNode.bind(this)),window.removeEventListener("haxcms-delete-node",this.deleteNode.bind(this)),super.disconnectedCallback()}loadUserData(e){this.querySelector("#getuserdata").body={jwt:this.jwt},this.querySelector("#getuserdata").generateRequest()}loadNodeFields(e){this.__nodeFieldsInvoked=e.detail;let t=document.createElement("simple-fields-form");t.style.margin="0 0 50px 0",t.setAttribute("autoload","autoload"),t.method=this.method,t.headers={Authorization:`Bearer ${this.jwt}`,Accept:"application/json","Content-Type":"application/json"},t.body={jwt:this.jwt,token:this.getFormToken,site:{name:this.manifest.metadata.site.name},node:{id:this.activeItem.id}},t.loadEndpoint=this.getNodeFieldsPath,this.__fieldsForm=t;let i=document.createElement("paper-button"),a=document.createElement("iron-icon");a.icon="icons:save",i.appendChild(a),i.appendChild(document.createTextNode("Save fields")),i.style.color="white",i.style.backgroundColor="#2196f3",i.setAttribute("dialog-confirm","dialog-confirm"),i.addEventListener("click",this._saveNodeFieldsTap.bind(this));let n=document.createElement("paper-button");n.appendChild(document.createTextNode("cancel")),n.setAttribute("dialog-dismiss","dialog-dismiss");let o=document.createElement("div");o.style.position="absolute",o.style.bottom=0,o.style.left=0,o.style.right=0,o.style.zIndex=1e6,o.appendChild(i),o.appendChild(n);const d=new CustomEvent("simple-modal-show",{bubbles:!0,composed:!0,cancelable:!1,detail:{title:"Edit "+s.activeTitle+" fields",styles:{"--simple-modal-width":"70vw","--simple-modal-max-width":"70vw"},elements:{content:t,buttons:o},invokedBy:this.__nodeFieldsInvoked,clone:!1,modal:!0}});window.dispatchEvent(d)}loadSiteDashboard(e){if(this.__siteFieldsInvoked=e.detail,!this.siteDashboard){let e=document.getElementsByTagName("haxcms-site-builder")[0];this.siteDashboard=document.createElement("haxcms-site-dashboard"),this.siteDashboard.headers={Authorization:`Bearer ${this.jwt}`},this.siteDashboard.loadEndpoint=this.getSiteFieldsPath,this.siteDashboard.method=this.method,e.parentNode.insertBefore(this.siteDashboard,e)}this.siteDashboard.body={jwt:this.jwt,token:this.getFormToken,site:{name:this.manifest.metadata.site.name}},this.siteDashboard.headers={Authorization:`Bearer ${this.jwt}`},setTimeout(()=>{s.dashboardOpened=!s.dashboardOpened},300)}_schemaFormValueChanged(e){}_saveNodeFieldsTap(e){let t=this.__fieldsForm.submit();t.id=this.activeItem.id,window.dispatchEvent(new CustomEvent("haxcms-save-node-details",{bubbles:!0,composed:!0,cancelable:!0,detail:t})),window.dispatchEvent(new CustomEvent("simple-modal-hide",{bubbles:!0,composed:!0,cancelable:!0,detail:{}}))}_saveSiteFieldsTap(e){window.dispatchEvent(new CustomEvent("haxcms-save-site-data",{bubbles:!0,composed:!0,cancelable:!0,detail:this.querySelector("#siteform").submit()})),window.dispatchEvent(new CustomEvent("simple-modal-hide",{bubbles:!0,composed:!0,cancelable:!0,detail:{}}))}createNode(e){if(e.detail.values){this.querySelector("#createajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name},node:e.detail.values},this.querySelector("#createajax").generateRequest();const t=new CustomEvent("simple-modal-hide",{bubbles:!0,composed:!0,cancelable:!0,detail:{}});window.dispatchEvent(t)}}_handleCreateResponse(e){const t=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:`Created ${this.__createNodeResponse.title}!`,duration:2e3}});window.dispatchEvent(t),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))}deleteNode(e){this.querySelector("#deleteajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name},node:{id:e.detail.item.id}},this.querySelector("#deleteajax").generateRequest();const t=new CustomEvent("simple-modal-hide",{bubbles:!0,composed:!0,cancelable:!0,detail:{}});window.dispatchEvent(t)}_handleDeleteResponse(e){const t=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:`Deleted ${this.__deleteNodeResponse.title}`,duration:2e3}});this.dispatchEvent(t),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))}_storeReadyToGo(e){e.detail&&(window.HaxStore.instance.connectionRewrites.appendJwt="jwt")}_publishingChanged(e,t){if(e){const e=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:"Publishing...",duration:0}});window.dispatchEvent(e)}else if(!e&&t){const e=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:"Publishing...",duration:2e3}});window.dispatchEvent(e)}}_manifestChanged(e){this.activeItem&&e.metadata&&(window.HaxStore.instance.connectionRewrites.appendUploadEndPoint="siteName="+e.metadata.site.name+"&nodeId="+this.activeItem.id)}_newActiveItem(e){this.activeItem=e.detail}_activeItemChanged(e,t){e&&this.manifest&&(window.HaxStore.instance.connectionRewrites.appendUploadEndPoint="siteName="+this.manifest.metadata.site.name+"&nodeId="+e.id)}_handleNodeResponse(e){if(void 0!==e.detail.slug&&this.activeItem.slug!==e.detail.slug){window.location(e.detail.slug),window.history.pushState({},null,e.detail.slug),window.dispatchEvent(new PopStateEvent("popstate"));const t=this.manifest.items.find(t=>t.id===e.detail.id);this.activeItem=t,this.dispatchEvent(new CustomEvent("json-outline-schema-active-item-changed",{bubbles:!0,composed:!0,cancelable:!0,detail:t}))}const t=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:"Page saved!",duration:2e3}});window.dispatchEvent(t),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0})),this.dispatchEvent(new CustomEvent("haxcms-trigger-update-node",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))}_handleOutlineResponse(e){const t=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:"Outline saved!",duration:2e3}});setTimeout(()=>{window.dispatchEvent(t),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))},100)}_handleManifestResponse(e){this.dispatchEvent(new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:"Site details saved, reloading to reflect changes!",duration:3e3}})),s.dashboardOpened=!1,this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0})),setTimeout(()=>{window.location.reload()},3e3)}_handleRevertResponse(e){const t=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:"Last save undone",duration:2e3}});this.dispatchEvent(t),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))}_handleSyncResponse(e){const t=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:"Site synced",duration:2e3}});this.dispatchEvent(t),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0})),s.dashboardOpened=!1}_handlePublishResponse(e){let t=e.detail.response,i=document.createElement("span");i.innerHTML=`\n    <a href="${t.url}" target="_blank">\n      <paper-button raised style="color:yellow;text-transform: none;font-weight: bold;">\n      ${t.label}\n      </paper-button>\n    </a>`;const a=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:t.response,duration:1e4,slot:i.cloneNode(!0)}});window.dispatchEvent(a),s.dashboardOpened=!1}saveNode(e){if(this.saveNodePath){let e=window.HaxStore.instance.activeHaxBody.haxToContent();this.querySelector("#nodeupdateajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name},node:{id:this.activeItem.id,body:e,schema:window.HaxStore.htmlToHaxElements(e)}},this.querySelector("#nodeupdateajax").generateRequest()}}saveNodeDetails(e){this.saveNodePath&&(this.querySelector("#nodeupdateajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name},node:{id:e.detail.id,details:e.detail}},this.querySelector("#nodeupdateajax").generateRequest())}saveOutline(e){this.saveOutlinePath&&(this.querySelector("#outlineupdateajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name},items:e.detail},this.querySelector("#outlineupdateajax").generateRequest())}saveManifest(e){let t=e.detail;t.cssVariable&&(t.hexCode=window.SimpleColorsStyles.colors[t.cssVariable.replace("--simple-colors-default-theme-","").replace("-7","")][6]),t.jwt=this.jwt,t.site?t.site.name=this.manifest.metadata.site.name:t.site={name:this.manifest.metadata.site.name},this.saveManifestPath&&(this.querySelector("#manifestupdateajax").body=t,this.querySelector("#manifestupdateajax").generateRequest())}_bodyChanged(e){window.HaxStore.instance.activeHaxBody&&window.HaxStore.instance.activeHaxBody.importContent(e.detail)}publishSite(e){this.publishSitePath&&(this.querySelector("#publishajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name}},this.querySelector("#publishajax").generateRequest())}syncSite(e){this.syncSitePath&&(this.querySelector("#syncajax").body={jwt:this.jwt,site:{name:s.manifest.metadata.site.name}},this.querySelector("#syncajax").generateRequest())}revertCommit(e){this.revertSitePath&&(this.querySelector("#revertajax").body={jwt:this.jwt,site:{name:s.manifest.metadata.site.name}},this.querySelector("#revertajax").generateRequest())}}window.customElements.define(HAXCMSSiteEditor.tag,HAXCMSSiteEditor);export{HAXCMSSiteEditor};