single-spa-layout
Version:
Layout engine for single-spa applications
3 lines (2 loc) • 11.9 kB
JavaScript
/* single-spa-layout@1.0.0-beta.2 - esm */
import{pathToActiveWhen as e,mountRootParcel as t}from"single-spa";function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function i(e){return function(e){if(Array.isArray(e))return c(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return c(e,void 0);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?c(e,void 0):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=e[n];return o}var u="undefined"!=typeof window;function s(e,t){if("object"!==n(t)||Array.isArray(t)||null===t)throw Error("Invalid ".concat(e,": received ").concat(Array.isArray(t)?"array":t," but expected a plain object"))}function l(e,t,n,o){if(!o){var r=Object.keys(t),a=[];r.forEach((function(e){n.indexOf(e)<0&&a.push(e)})),a.length>0&&console.warn(Error("Invalid ".concat(e,": received invalid properties '").concat(a.join(", "),"', but valid properties are ").concat(n.join(", "))))}}function d(e,t){if("string"!=typeof t||""===t.trim())throw Error("Invalid ".concat(e,": received '").concat(t,"', but expected a non-blank string"))}function p(e,t,o){if(!Array.isArray(t)&&("object"!==n(n(t))||"number"!==t.length))throw Error("Invalid ".concat(e,": received '").concat(t,"', but expected an array"));for(var r=arguments.length,a=new Array(r>3?r-3:0),i=3;i<r;i++)a[i-3]=arguments[i];for(var c=0;c<t.length;c++)o.apply(void 0,[t[c],"".concat(e,"[").concat(c,"]")].concat(a))}function f(e,t){d("path",t);var n=a({},e),o=e.base.slice(0,e.base.length-1);if(0===t.indexOf(o)){var r=u?window.location.origin:"http://localhost",i=new URL(h(r,t));n.routes=function e(t,n){var o=[];return n.forEach((function(n){"application"===n.type?o.push(n):"route"===n.type?n.activeWhen(t)&&o.push(a(a({},n),{},{routes:e(t,n.routes)})):Array.isArray(n.routes)&&o.push(a(a({},n),{},{routes:e(t,n.routes)}))})),o}(i,e.routes)}else n.routes=[];return n}function h(e,t){return"/"===e.substr(-1)?"/"===t[0]?e+t.slice(1):e+t:"/"===t[0]?e+t:e+"/"+t}function v(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return e[n];return null}function m(t,o){if(t&&t.nodeName)t=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("template"===e.nodeName.toLowerCase()&&(e=(e.content||e).querySelector("single-spa-router")),"single-spa-router"!==e.nodeName.toLowerCase())throw Error("single-spa-layout: The HTMLElement passed to constructRoutes must be <single-spa-router> or a <template> containing the router. Received ".concat(e.nodeName));u&&e.isConnected&&e.parentNode.removeChild(e);var n={routes:[]};y(e,"mode")&&(n.mode=y(e,"mode")),y(e,"base")&&(n.base=y(e,"base"));for(var o=0;o<e.childNodes.length;o++){var r;(r=n.routes).push.apply(r,i(b(e.childNodes[o],t)))}return n}(t,o);else if(o)throw Error("constructRoutes should be called either with an HTMLElement and layoutData, or a single json object.");return function(t){s("routesConfig",t);var o,r=t.disableWarnings;l("routesConfig",t,["mode","base","containerEl","routes","disableWarnings"],r),t.hasOwnProperty("containerEl")?function(e,t){if("string"==typeof t?""===t.trim():!(u&&t instanceof HTMLElement))throw Error("Invalid ".concat("routesConfig.containerEl",": received ").concat(t," but expected either non-blank string or HTMLElement"))}(0,t.containerEl):t.containerEl="body",t.hasOwnProperty("mode")||(t.mode="history"),function(e,t,n){if(n.indexOf(t)<0)throw Error("Invalid ".concat("routesConfig.mode",": received '").concat(t,"' but expected ").concat(n.join(", ")))}(0,t.mode,["history","hash"]),t.hasOwnProperty("base")?(d("routesConfig.base",t.base),t.base=(0!==(o=t.base).indexOf("/")&&(o="/"+o),"/"!==o[o.length-1]&&(o+="/"),o)):t.base="/";var a=u?window.location.pathname:"/",i="hash"===t.mode?a+"#":"";p("routesConfig.routes",t.routes,(function t(o,a,i){var c,u=i.parentPath,f=i.siblingActiveWhens;if(s(a,o),"application"===o.type)l(a,o,["type","name","props","loader"],r),o.props&&s("".concat(a,".props"),o.props),d("".concat(a,".name"),o.name);else if("route"===o.type){l(a,o,["type","path","routes","props","default"],r);var v,m=o.hasOwnProperty("path"),y=o.hasOwnProperty("default");if(m)d("".concat(a,".path"),o.path),v=h(u,o.path),o.activeWhen=e(v),f.push(o.activeWhen);else{if(!y)throw Error("Invalid ".concat(a,": routes must have either a path or default property."));!function(e,t){if("boolean"!=typeof t)throw Error("Invalid ".concat(e,": received ").concat(n(t),", but expected a boolean"))}("".concat(a,".default"),o.default),v=u,o.activeWhen=(c=f,function(e){return!c.some((function(t){return t(e)}))})}if(m&&y&&o.default)throw Error("Invalid ".concat(a,": cannot have both path and set default to true."));o.routes&&p("".concat(a,".routes"),o.routes,t,{parentPath:v,siblingActiveWhens:[]})}else{if("undefined"!=typeof Node&&o instanceof Node);else for(var b in o)"routes"!==b&&d("".concat(a,"['").concat(b,"']"),o[b]);o.routes&&p("".concat(a,".routes"),o.routes,t,{parentPath:u,siblingActiveWhens:f})}}),{parentPath:i+t.base,siblingActiveWhens:[]}),delete t.disableWarnings}(t),t}function y(e,t){if(u)return e.getAttribute(t);var n=v(e.attrs,(function(e){return e.name===t}));return n?n.value:null}function b(e,t){if("application"===e.nodeName.toLowerCase()){if(e.childNodes.length>0)throw Error("<application> elements must not have childNodes. You must put in a closing </application> - self closing is not allowed");var n={type:"application",name:y(e,"name")},o=y(e,"loader");if(o){if(!t.loaders||!t.loaders.hasOwnProperty(o))throw Error("Application loader '".concat(o,"' was not defined in the htmlLayoutData"));n.loader=t.loaders[o]}return g(e,n,["name","loader"],t),[n]}if("route"===e.nodeName.toLowerCase()){var r={type:"route",routes:[]},a=y(e,"path");a&&(r.path=a),function(e,t){return u?e.hasAttribute("default"):e.attrs.some((function(e){return"default"===e.name}))}(e)&&(r.default=!0),g(e,r,["path","default"],t);for(var c=0;c<e.childNodes.length;c++){var s;(s=r.routes).push.apply(s,i(b(e.childNodes[c],t)))}return[r]}if("undefined"!=typeof Node&&e instanceof Node){if(e.nodeType===Node.TEXT_NODE&&""===e.textContent.trim())return[];if(e.childNodes&&e.childNodes.length>0){e.routes=[];for(var l=0;l<e.childNodes.length;l++){var d;(d=e.routes).push.apply(d,i(b(e.childNodes[l],t)))}}return[e]}if(e.childNodes){for(var p={type:e.nodeName.toLowerCase(),routes:[]},f=0;f<e.childNodes.length;f++){var h;(h=p.routes).push.apply(h,i(b(e.childNodes[f],t)))}return[p]}return[]}function g(e,t,n,o){for(var r=e.attributes||e.attrs,a=0;a<r.length;a++){var i=r[a],c=i.name,u=i.value;if(!(n.indexOf(c)>=0)){t.props||(t.props={});var s=""!==u.trim()?u:c;if(!o.props||!o.props.hasOwnProperty(s))throw Error("Prop '".concat(c,"' was not defined in the htmlLayoutData. Either remove this attribute from the HTML element or provide the prop's value"));t.props[c]=o.props[s]}}}function w(e){var t=e.routes,n=(e.applications,e.active),o=void 0===n||n,r=!1,a=[],i=t.base.slice(0,t.base.length-1),c={isActive:function(){return r},activate:function(){r||(r=!0,u&&(window.addEventListener("single-spa:before-mount-routing-event",s),window.addEventListener("single-spa:routing-event",l),s()))},deactivate:function(){r&&(r=!1,u&&(window.removeEventListener("single-spa:before-mount-routing-event",s),window.removeEventListener("single-spa:routing-event",l)))}};return o&&c.activate(),c;function s(){if(0===location["hash"===t.mode?"hash":"pathname"].indexOf(i)){var e="string"==typeof t.containerEl?document.querySelector(t.containerEl):t.containerEl;!function e(t){var n=t.location,o=t.routes,r=t.parentContainer,a=t.previousSibling,i=t.shouldMount,c=t.pendingRemovals;return o.forEach((function(t,o){if("application"===t.type){var u=N(t.name),s=document.getElementById(u);i&&(s||((s=document.createElement("div")).id=u),E(s,r,a),a=s)}else if("route"===t.type)a=e({location:n,routes:t.routes,parentContainer:r,previousSibling:a,shouldMount:i&&t.activeWhen(n),pendingRemovals:c});else if(t instanceof Node)if(i){if(!t.connectedNode){var l=t.cloneNode(!1);t.connectedNode=l}E(t.connectedNode,r,a),t.routes&&e({location:n,routes:t.routes,parentContainer:t.connectedNode,previousSibling:null,shouldMount:i,pendingRemovals:c}),a=t.connectedNode}else c.push((function(){var e;(e=t.connectedNode)&&(e.remove?e.remove():e.parentNode.removeChild(e)),delete t.connectedNode}))})),a}({location:window.location,routes:t.routes,parentContainer:e,shouldMount:!0,pendingRemovals:a})}}function l(e){var t=e.detail.appsByNewStatus;a.forEach((function(e){return e()})),a=[],t.NOT_MOUNTED.concat(t.NOT_LOADED).forEach((function(e){var t=document.getElementById(N(e));t&&t.isConnected&&t.parentNode.removeChild(t)}))}}function E(e,t,n){n&&n.nextSibling?n.parentNode.insertBefore(e,n.nextSibling):t.appendChild(e)}function N(e){return"single-spa-application:".concat(e)}function O(e){var n=e.routes,o=e.loadApp,r={};return function e(t,n,o,r){r.forEach((function(r){"application"===r.type?(t[r.name]||(t[r.name]=[]),t[r.name].push({activeWhen:n,props:P(o,r.props),loader:r.loader})):"route"===r.type?e(t,r.activeWhen,P(o,r.props),r.routes):r.routes&&e(t,n,o,r.routes)}))}(r,A,{},n.routes),Object.keys(r).map((function(e){var n=r[e];return{name:e,customProps:function(e,t){var o=v(n,(function(e){return e.activeWhen(t)}));return o?o.props:{}},activeWhen:n.map((function(e){return e.activeWhen})),app:function(){var r;u&&(r=v(n,(function(e){return e.activeWhen(window.location)})));var a=o({name:e});return r&&r.loader?function(e,n,o){return Promise.resolve().then((function(){var r,a=N(e),i=document.getElementById(a);i||((i=document.createElement("div")).id=a,i.style.display="none",r=!0,document.body.appendChild(i));var c,u,s,l="string"==typeof n.loader?(c=n.loader,u=(new DOMParser).parseFromString(c,"text/html").body.childNodes,s=[],{bootstrap:function(){return Promise.resolve()},mount:function(e){return Promise.resolve().then((function(){u.forEach((function(t){s.push(e.domElement.appendChild(t.cloneNode()))}))}))},unmount:function(e){return Promise.resolve().then((function(){s.forEach((function(t){e.domElement.removeChild(t)}))}))}}):n.loader,d=t(l,{name:"application-loader:".concat(e),domElement:i});return Promise.all([d.mountPromise,o]).then((function(e){return d.unmount().then((function(){return r&&(i.style.removeProperty("display"),""===i.getAttribute("style")&&i.removeAttribute("style")),e}))}))}))}(e,r,a):a}}}))}function P(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return a(a({},e),t)}function A(){return!0}export{O as constructApplications,w as constructLayoutEngine,m as constructRoutes,f as matchRoute};