text: define(["exports","meta","require","../../../../lit-element/lit-element.js","../../../../@polymer/polymer/lib/utils/settings.js","../../../json-outline-schema/json-outline-schema.js","../../../utils/utils.js","../../../../mobx/lib/mobx.module.js","./haxcms-site-store.js","../../../../@polymer/iron-ajax/iron-ajax.js"],function(_exports,meta,_require,_litElement,_settings,_jsonOutlineSchema,_utils,_mobxModule,_haxcmsSiteStore,_ironAjax){"use strict";Object.defineProperty(_exports,"__esModule",{value:!0});_exports.HAXCMSSiteBuilder=void 0;meta=babelHelpers.interopRequireWildcard(meta);_require=babelHelpers.interopRequireWildcard(_require);function _templateObject2_8ec859d0679e11eaa25e79cdef13391f(){var data=babelHelpers.taggedTemplateLiteral(["\n        :host {\n          display: block;\n        }\n        :host #slot {\n          background-color: var(--haxcms-color, white);\n          opacity: 0.2;\n          visibility: hidden;\n        }\n        :host([dashboard-opened]) {\n          display: inline-block !important;\n          margin-left: 50vw;\n          height: 100vh;\n          pointer-events: none;\n          opacity: 0.5;\n          width: 100vw;\n        }\n        :host([theme-loaded]) #slot {\n          opacity: 1;\n          visibility: visible;\n        }\n        paper-progress {\n          display: block;\n          width: 100%;\n          position: fixed;\n          top: 0;\n          left: 0;\n          right: 0;\n          background-color: transparent;\n          z-index: 1000;\n          --paper-progress-active-color: var(\n            --haxcms-color,\n            rgba(255, 255, 255, 0.5)\n          );\n          --paper-progress-container-color: transparent;\n        }\n      "]);_templateObject2_8ec859d0679e11eaa25e79cdef13391f=function _templateObject2_8ec859d0679e11eaa25e79cdef13391f(){return data};return data}function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable});keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1,source;i<arguments.length;i++){source=null!=arguments[i]?arguments[i]:{};if(i%2){ownKeys(Object(source),!0).forEach(function(key){babelHelpers.defineProperty(target,key,source[key])})}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}}return target}function _templateObject_8ec859d0679e11eaa25e79cdef13391f(){var data=babelHelpers.taggedTemplateLiteral(["\n      <haxcms-site-router base-uri=\"","\"></haxcms-site-router>\n      <paper-progress .hidden=\"","\" indeterminate></paper-progress>\n      <iron-ajax\n        id=\"manifest\"\n        .url=\"","","","\"\n        handle-as=\"json\"\n        @last-response-changed=\"","\"\n        @last-error-changed=\"","\"\n      ></iron-ajax>\n      <iron-ajax\n        id=\"activecontent\"\n        .url=\"","","","\"\n        handle-as=\"text\"\n        @loading-changed=\"","\"\n        @last-response-changed=\"","\"\n        @last-error-changed=\"","\"\n      ></iron-ajax>\n      <div id=\"slot\"><slot></slot></div>\n      <simple-colors-polymer></simple-colors-polymer>\n    "]);_templateObject_8ec859d0679e11eaa25e79cdef13391f=function _templateObject_8ec859d0679e11eaa25e79cdef13391f(){return data};return data}/**
   * `haxcms-site-builder`
   * `build the site and everything off of this`
   * @microcopy - the mental model for this element
   * - This is a factory element, it doesn't do much on its own visually
   * - it loads a site.json file and then utilizes this data in order to construct
   *   what theme it should load (element) in order to get everything off and running
   */var HAXCMSSiteBuilder=/*#__PURE__*/function(_LitElement){babelHelpers.inherits(HAXCMSSiteBuilder,_LitElement);babelHelpers.createClass(HAXCMSSiteBuilder,[{key:"render",// render function
  value:function render(){return(0,_litElement.html)(_templateObject_8ec859d0679e11eaa25e79cdef13391f(),this.baseURI,!this.loading,this.outlineLocation,this.file,this._timeStamp,this._updateManifest,this.lastErrorChanged,this.outlineLocation,this.activeItemLocation,this._timeStamp,this._updateLoading,this._updateActiveItemContent,this.lastErrorChanged)}/**
     * Simple "two way" data binding from the element below via events
     */},{key:"_updateManifest",value:function _updateManifest(e){this.manifest=_objectSpread({},e.detail.value)}},{key:"_updateLoading",value:function _updateLoading(e){this.loading=e.detail.value}},{key:"_updateActiveItemContent",value:function _updateActiveItemContent(e){this.activeItemContent=e.detail.value}},{key:"firstUpdated",value:function firstUpdated(){this.shadowRoot.querySelector("#manifest").generateRequest()}/**
     * life cycle updated
     */},{key:"updated",value:function updated(changedProperties){var _this2=this;changedProperties.forEach(function(oldValue,propName){if("dashboardOpened"==propName){_this2._dashboardOpenedChanged(_this2[propName],oldValue)}else if("themeData"==propName){_this2._themeChanged(_this2[propName],oldValue)}else if("themeName"==propName){_this2._themeNameChanged(_this2[propName],oldValue)}else if("file"==propName){_this2._fileChanged(_this2[propName],oldValue)}else if("outlineLocation"==propName){// fire an to match notify
  _this2.dispatchEvent(new CustomEvent("outline-location-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:_this2[propName]}))}else if("manifest"==propName){// fire an to match notify
  _this2.dispatchEvent(new CustomEvent("manifest-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:_this2[propName]}));_this2._manifestChanged(_this2[propName],oldValue)}else if("activeItem"==propName){// fire an to match notify
  _this2.dispatchEvent(new CustomEvent("active-item-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:_this2[propName]}));_this2._activeItemChanged(_this2[propName],oldValue)}else if("activeItemContent"==propName){// fire an to match notify
  _this2.dispatchEvent(new CustomEvent("active-item-content-changed",{bubbles:!0,cancelable:!0,composed:!0,detail:_this2[propName]}));_this2._activeItemContentChanged(_this2[propName],oldValue)}})}},{key:"_themeNameChanged",value:function _themeNameChanged(newValue){if(newValue){_haxcmsSiteStore.store.themeElement=document.createElement(newValue);(0,_utils.wipeSlot)(this,"*");this.appendChild(_haxcmsSiteStore.store.themeElement)}else if(newValue&&oldValue){// theme changed
  _haxcmsSiteStore.store.themeElement.remove();// wipe out what we got
  (0,_utils.wipeSlot)(this,"*");_haxcmsSiteStore.store.themeElement=document.createElement(newValue);this.appendChild(_haxcmsSiteStore.store.themeElement)}}/**
     * Alert there was an internal error in getting the file
     */},{key:"lastErrorChanged",value:function lastErrorChanged(e){if(e.detail.value){console.error(e);var evt=new CustomEvent("simple-toast-show",{bubbles:!0,composed:!0,cancelable:!1,detail:{text:e.detail.value.status+" "+e.detail.value.statusText}});window.dispatchEvent(evt)}}/**
     * ready life cycle
     */}],[{key:"styles",get:function get(){return[(0,_litElement.css)(_templateObject2_8ec859d0679e11eaa25e79cdef13391f())]}/**
     * Store the tag name to make it easier to obtain directly.
     */},{key:"tag",get:function get(){return"haxcms-site-builder"}},{key:"properties",get:function get(){return{activeItemLocation:{type:String,attribute:"active-item-location"},_timeStamp:{type:String},dashboardOpened:{type:Boolean,reflect:!0,attribute:"dashboard-opened"},/**
         * queryParams
         */queryParams:{type:Object},/**
         * Loading status of the page to render.
         */loading:{type:Boolean,reflect:!0},/**
         * support for alternate locations.
         */outlineLocation:{type:String,attribute:"outline-location"},/**
         * Manifest from file
         */manifest:{type:Object},/**
         * Theme, used to boot a design element
         */themeData:{type:Object},/**
         * Theme name, which we then use to setup the theme
         */themeName:{type:String},/**
         * Imported items so we can allow theme flipping dynamically
         */__imported:{type:Object},/**
         * theme loaded to indicate to the theme we have a theme ready to go
         */themeLoaded:{type:Boolean,reflect:!0,attribute:"theme-loaded"},/**
         * Active item which is in JSON Outline Schema
         */activeItem:{type:Object},/**
         * Active item content
         */activeItemContent:{type:String},/**
         * Location of the site.json file
         */file:{type:String},/**
         * Injected by HAXcms
         */baseURI:{type:String}}}}]);function HAXCMSSiteBuilder(){var _this;babelHelpers.classCallCheck(this,HAXCMSSiteBuilder);_this=babelHelpers.possibleConstructorReturn(this,babelHelpers.getPrototypeOf(HAXCMSSiteBuilder).call(this));// attempt to set polymer passive gestures globally
  // this decreases logging and improves performance on scrolling
  (0,_settings.setPassiveTouchGestures)(!0);_this.__disposer=[];_this.queryParams={};_this.loading=!1;_this.__imported={};_this.themeLoaded=!1;_this._timeStamp="";_this.outlineLocation="";_this.activeItemLocation="";new Promise(function(res,rej){return _require.default(["./haxcms-site-router.js"],res,rej)});new Promise(function(res,rej){return _require.default(["../../../../@polymer/paper-progress/paper-progress.js"],res,rej)});new Promise(function(res,rej){return _require.default(["../../../simple-toast/simple-toast.js"],res,rej)});new Promise(function(res,rej){return _require.default(["../../../simple-colors/lib/simple-colors-polymer.js"],res,rej)});setTimeout(function(){window.addEventListener("hax-store-ready",_this.storeReady.bind(babelHelpers.assertThisInitialized(_this)));window.addEventListener("haxcms-trigger-update",_this._triggerUpdatedData.bind(babelHelpers.assertThisInitialized(_this)));window.addEventListener("haxcms-trigger-update-node",_this._triggerUpdatedNode.bind(babelHelpers.assertThisInitialized(_this)));(0,_mobxModule.autorun)(function(reaction){_this.dashboardOpened=(0,_mobxModule.toJS)(_haxcmsSiteStore.store.dashboardOpened);_this.__disposer.push(reaction)});(0,_mobxModule.autorun)(function(reaction){_this.themeData=(0,_mobxModule.toJS)(_haxcmsSiteStore.store.themeData);if(_this.themeData&&_this.themeData.element!==_this.themeName){_this.themeName=_this.themeData.element}_this.__disposer.push(reaction)});(0,_mobxModule.autorun)(function(reaction){_this.activeItem=(0,_mobxModule.toJS)(_haxcmsSiteStore.store.activeItem);if(_this.activeItem&&_this.activeItem.location){_this.activeItemLocation=_this.activeItem.location}_this.__disposer.push(reaction)})},0);return _this}babelHelpers.createClass(HAXCMSSiteBuilder,[{key:"_dashboardOpenedChanged",value:function _dashboardOpenedChanged(newValue,oldValue){if(newValue){this.setAttribute("aria-hidden","aria-hidden");this.setAttribute("tabindex","-1")}else if(!newValue&&oldValue){this.removeAttribute("aria-hidden");this.removeAttribute("tabindex")}}},{key:"connectedCallback",value:function connectedCallback(){var _this3=this;babelHelpers.get(babelHelpers.getPrototypeOf(HAXCMSSiteBuilder.prototype),"connectedCallback",this).call(this);this.dispatchEvent(new CustomEvent("haxcms-ready",{bubbles:!0,composed:!0,cancelable:!1,detail:this}));// dyanmcially import the editor builder which figures out if we should have one
  new Promise(function(res,rej){return _require.default(["./haxcms-editor-builder.js"],res,rej)}).then(function(response){_this3.editorBuilder=document.createElement("haxcms-editor-builder");// attach editor builder after we've appended to the screen
  document.body.appendChild(_this3.editorBuilder);// get fresh data if not published / demo which is a form of published
  if("published"!==_this3.editorBuilder.getContext()&&"demo"!==_this3.editorBuilder.getContext()){_this3._timeStamp="?"+Math.floor(Date.now()/1e3)}}).catch(function(error){/* Error handling */console.log(error)});var evt=document.createEvent("UIEvents");evt.initUIEvent("resize",!0,!1,window,0);window.dispatchEvent(evt)}/**
     * Detached life cycle
     */},{key:"disconnectedCallback",value:function disconnectedCallback(){for(var i in this.__disposer){this.__disposer[i].dispose()}babelHelpers.get(babelHelpers.getPrototypeOf(HAXCMSSiteBuilder.prototype),"disconnectedCallback",this).call(this)}},{key:"storeReady",value:function storeReady(e){// append UI element to body to avoid stack order issues
  if(_haxcmsSiteStore.store.cmsSiteEditor&&_haxcmsSiteStore.store.cmsSiteEditor.instance&&window.HaxStore.instance.activeHaxBody&&_haxcmsSiteStore.store.activeItemContent){window.HaxStore.instance.activeHaxBody.importContent(_haxcmsSiteStore.store.activeItemContent)}}/**
     * React to content being loaded from a page.
     */},{key:"_activeItemContentChanged",value:function _activeItemContentChanged(newValue,oldValue){var _this4=this;if(newValue){var html=newValue;// only append if not empty
  if(null!==html){(0,_utils.wipeSlot)(_haxcmsSiteStore.store.themeElement,"*");html=(0,_utils.encapScript)(newValue);// set in the store
  _haxcmsSiteStore.store.activeItemContent=html;// insert the content as quickly as possible, then work on the dynamic imports
  setTimeout(function(){if(0===_haxcmsSiteStore.store.themeElement.childNodes.length){var frag=document.createRange().createContextualFragment(html);_haxcmsSiteStore.store.themeElement.appendChild(frag);_this4.dispatchEvent(new CustomEvent("json-outline-schema-active-body-changed",{bubbles:!0,composed:!0,cancelable:!1,detail:html}))}},5);// if there are, dynamically import them
  if((0,_utils.varExists)(this.manifest,"metadata.node.dynamicElementLoader")){var i;(function(){var tagsFound=(0,_utils.findTagsInHTML)(html),basePath=_this4.pathFromUrl(decodeURIComponent(meta.url)),_loop=function _loop(){var tagName=tagsFound[i];if(_this4.manifest.metadata.node.dynamicElementLoader[tagName]&&!window.customElements.get(tagName)){new Promise(function(res,rej){return _require.default(["".concat(basePath,"../../../../").concat(_this4.manifest.metadata.node.dynamicElementLoader[tagName])],res,rej)}).then(function(response){// useful to debug if dynamic references are coming in
  //console.log(tagName + ' dynamic import');
  }).catch(function(error){/* Error handling */console.log(error);console.log(tagName)})}};for(i in tagsFound){_loop()}})()}}}}/**
     * Active item updated, let's request the content from it
     */},{key:"_activeItemChanged",value:function _activeItemChanged(newValue,oldValue){if(this.shadowRoot&&newValue&&babelHelpers.typeof(newValue.id)!==("undefined"===typeof void 0?"undefined":babelHelpers.typeof(void 0))){this.queryParams.nodeId=newValue.id;// if published, keep it static on request
  // @todo might revisit this in the future
  if(this.editorBuilder&&"published"===this.editorBuilder.getContext()){this._timeStamp=""}else{this._timeStamp="?"+Math.floor(Date.now()/1e3)}this.shadowRoot.querySelector("#activecontent").generateRequest()}// we had something, now we don't. wipe out the content area of the theme
  else if(oldValue&&!newValue){// fire event w/ nothing, this is because there is no content
  this.dispatchEvent(new CustomEvent("json-outline-schema-active-body-changed",{bubbles:!0,composed:!0,cancelable:!1,detail:null}))}}/**
     * got a message that we need to update our json manifest data
     */},{key:"_triggerUpdatedData",value:function _triggerUpdatedData(e){// get fresh data if not published
  if(this.editorBuilder&&"published"!==this.editorBuilder.getContext()){this._timeStamp="?"+Math.floor(Date.now()/1e3)}this.shadowRoot.querySelector("#manifest").generateRequest()}/**
     * got a message that we need to update our page content
     */},{key:"_triggerUpdatedNode",value:function _triggerUpdatedNode(e){// get fresh data if not published
  if(this.editorBuilder&&"published"!==this.editorBuilder.getContext()&&"demo"!==this.editorBuilder.getContext()){this._timeStamp="?"+Math.floor(Date.now()/1e3)}// ensure we don't get a miss on initial load
  if(this.activeItem.location){this.shadowRoot.querySelector("#activecontent").generateRequest()}}/**
     * File changed so let's pull from the location
     */},{key:"_fileChanged",value:function _fileChanged(newValue,oldValue){if(this.shadowRoot.querySelector("#manifest").generateRequest&&babelHelpers.typeof(newValue)!==("undefined"===typeof void 0?"undefined":babelHelpers.typeof(void 0))){this.shadowRoot.querySelector("#manifest").generateRequest()}}/**
     * notice manifest changes and ensure slot is rebuilt.
     */},{key:"_manifestChanged",value:function _manifestChanged(newValue,oldValue){if(newValue&&newValue.metadata&&newValue.items){// @todo replace this with a schema version mapper
  // once we have versions
  if((0,_utils.varExists)(newValue,"metadata.siteName")){var git=(0,_utils.varGet)(newValue,"publishing.git",{});newValue.metadata.site={name:newValue.metadata.siteName,git:git,created:newValue.metadata.created,updated:newValue.metadata.updated};newValue.metadata.theme.variables={image:newValue.metadata.image,icon:newValue.metadata.icon,hexCode:newValue.metadata.hexCode,cssVariable:newValue.metadata.cssVariable};newValue.metadata.node={dynamicElementLoader:newValue.metadata.dynamicElementLoader,fields:newValue.metadata.fields};delete newValue.metadata.publishing;delete newValue.metadata.created;delete newValue.metadata.updated;delete newValue.metadata.siteName;delete newValue.metadata.image;delete newValue.metadata.icon;delete newValue.metadata.hexCode;delete newValue.metadata.cssVariable;delete newValue.metadata.dynamicElementLoader;delete newValue.metadata.fields}var site=new _jsonOutlineSchema.JsonOutlineSchema,nodes=site.itemsToNodes(newValue.items),correctOrder=site.nodesToItems(nodes),newItems=[];// we already have our items, pass them in
  // build a new array in the correct order by pushing the old items around
  for(var key in correctOrder){newItems.push(newValue.items.find(function(element){return element.id===correctOrder[key].id}))}newValue.items=newItems;_haxcmsSiteStore.store.manifest=newValue;this.dispatchEvent(new CustomEvent("json-outline-schema-changed",{bubbles:!0,composed:!0,cancelable:!1,detail:newValue}))}}// simple path from a url modifier
  },{key:"pathFromUrl",value:function pathFromUrl(url){return url.substring(0,url.lastIndexOf("/")+1)}/**
     * notice theme changes and ensure slot is rebuilt.
     */},{key:"_themeChanged",value:function _themeChanged(newValue,oldValue){var _this5=this;if(newValue){this.themeLoaded=!1;var theme=newValue;// create the 'theme' as a new element
  // weird but definition already here so we should be able
  // to just use this without an import, it's possible..
  if(babelHelpers.typeof(this.__imported[theme.element])!==("undefined"===typeof void 0?"undefined":babelHelpers.typeof(void 0))){this.themeLoaded=!0}else{// import the reference to the item dynamically, if we can
  try{new Promise(function(res,rej){return _require.default([_this5.pathFromUrl(decodeURIComponent(meta.url))+"../../../../"+newValue.path],res,rej)}).then(function(e){// add it into ourselves so it unpacks and we kick this off!
  _this5.__imported[theme.element]=theme.element;_this5.themeLoaded=!0})}catch(err){// error in the event this is a double registration
  // also strange to be able to reach this but technically possible
  this.themeLoaded=!0}}}}}]);return HAXCMSSiteBuilder}(_litElement.LitElement);_exports.HAXCMSSiteBuilder=HAXCMSSiteBuilder;window.customElements.define(HAXCMSSiteBuilder.tag,HAXCMSSiteBuilder);// this global allows a backdoor into activating the HAXcms editor UI
  // this is only going to be visually enabled but it won't actually
  // be able to talk to the backend correctly bc the JWT won't exist
  // the endpoints are also fictional. also useful for testing purposes
  window.HAXme=function(){var context=0<arguments.length&&arguments[0]!==void 0?arguments[0]:null;if(null==context){// fake a demo
  context="demo";// fake endpoints
  window.appSettings={login:"dist/dev/login.json",logout:"dist/dev/logout.json",saveNodePath:"dist/dev/saveNode.json",saveManifestPath:"dist/dev/saveManifestPath.json",createNodePath:"dist/dev/saveNode.json",deleteNodePath:"dist/dev/saveNode.json",saveOutlinePath:"dist/dev/saveNode.json",publishSitePath:"dist/dev/saveNode.json",syncSitePath:"dist/dev/saveNode.json",getNodeFieldsPath:"dist/dev/getNodeFieldsPath.json",getSiteFieldsPath:"dist/dev/getSiteFieldsPath.json",revertSitePath:"dist/dev/saveNode.json",getFormToken:"adskjadshjudfu823u823u8fu8fij",appStore:{url:"dist/dev/appstore.json"},// add your custom theme here if testing locally and wanting to emulate the theme selector
  // this isn't really nessecary though
  themes:{"haxcms-dev-theme":{element:"haxcms-dev-theme",path:"@lrnwebcomponents/haxcms-elements/lib/haxcms-dev-theme.js",name:"Developer theme"}}}}if("demo"==context){window.__haxCMSContextDemo=!0}// apply context
  document.body.querySelector("haxcms-editor-builder").__appliedContext=!1;document.body.querySelector("haxcms-editor-builder").applyContext(context)}});