single-spa-layout
Version:
Layout engine for single-spa applications
3 lines (2 loc) • 18 kB
JavaScript
/* single-spa-layout@3.0.0 - system */
System.register(["single-spa"],(function(e){"use strict";var t,n,r,o,a,i,c,u;return{setters:[function(e){t=e.pathToActiveWhen,n=e.addErrorHandler,r=e.removeErrorHandler,o=e.mountRootParcel,a=e.getMountedApps,i=e.checkActivityFunctions,c=e.getAppNames,u=e.navigateToUrl}],execute:function(){function s(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function l(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?s(Object(n),!0).forEach((function(t){f(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function d(e){return(d="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 f(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p(e){return function(e){if(Array.isArray(e))return v(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||h(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 h(e,t){if(e){if("string"==typeof e)return v(e,t);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)?v(e,t):void 0}}function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}e({constructApplications:function(e){var t=e.routes,n=e.loadApp,r={};return F(r,_,{},t.routes),Object.keys(r).map((function(e){var t=r[e];return{name:e,customProps:function(e,n){var r=C(t,(function(e){return e.activeWhen(n)}));return r?r.props:{}},activeWhen:t.map((function(e){return e.activeWhen})),app:function(){var r;m&&(r=C(t,(function(e){return e.activeWhen(window.location)})));var a=n({name:e});return r&&r.loader?function(e,t,n){return Promise.resolve().then((function(){var r,a=R(e),i=document.getElementById(a);i||((i=document.createElement("div")).id=a,i.style.display="none",document.body.appendChild(i),r=function(){i.style.removeProperty("display"),""===i.getAttribute("style")&&i.removeAttribute("style"),window.removeEventListener("single-spa:before-mount-routing-event",r)},window.addEventListener("single-spa:before-mount-routing-event",r));var c="string"==typeof t.loader?T(t.loader):t.loader,u=o(c,{name:"application-loader:".concat(e),domElement:i});function s(){return u.unmount().then((function(){r&&r()}))}return Promise.all([u.mountPromise,n]).then((function(e){var t,n=(2,function(e){if(Array.isArray(e))return e}(t=e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,o,a=[],i=!0,c=!1;try{for(n=n.call(e);!(i=(r=n.next()).done)&&(a.push(r.value),2!==a.length);i=!0);}catch(e){c=!0,o=e}finally{try{i||null==n.return||n.return()}finally{if(c)throw o}}return a}}(t)||h(t,2)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}());n[0];var r=n[1];return s().then((function(){return r}))}),(function(e){return s().then((function(){throw e}))}))}))}(e,r,a):a}}}))},constructLayoutEngine:function(e){var t=e.routes;e.applications;var i=e.active,c=void 0===i||i,s=!1,l={},f=m&&Boolean(window.singleSpaLayoutData);if(!t)throw Error("single-spa-layout constructLayoutEngine(opts): opts.routes must be provided. Value was ".concat(d(t)));var p=t.base.slice(0,t.base.length-1),h={isActive:function(){return s},activate:function(){s||(s=!0,m&&(window.addEventListener("single-spa:before-routing-event",y),window.addEventListener("single-spa:before-mount-routing-event",g),window.addEventListener("single-spa:routing-event",b),n(v),f&&w(E(),t.routes),g()))},deactivate:function(){s&&(s=!1,m&&(window.removeEventListener("single-spa:before-routing-event",y),window.removeEventListener("single-spa:before-mount-routing-event",g),window.removeEventListener("single-spa:routing-event",b),r(v)))}};return c&&h.activate(),h;function v(e){var n=D({applicationName:e.appOrParcelName,location:window.location,routes:t.routes});if(n&&n.error){var r=document.getElementById(R(n.name)),a="string"==typeof n.error?T(n.error):n.error;l[n.name]=o(a,{domElement:r,error:e})}setTimeout((function(){throw e}))}function y(e){var n=e.detail,r=n.cancelNavigation,o=n.newUrl,a=k(t,U(o)),i=function(e){var n=t.redirects[e];if(e===a){if(!r)throw Error("single-spa-layout: <redirect> requires single-spa@>=6.0.0");return r(),setTimeout((function(){u(n)})),{v:void 0}}};for(var c in t.redirects){var s=i(c);if("object"===d(s))return s.v}var f=[];q(o).forEach((function(e){l[e]&&(f.push(l[e].unmount()),delete l[e])})),f.length>0&&r(Promise.all(f).then((function(){return!1})))}function g(){if(0===k(t).indexOf(p)){var e=a().reduce((function(e,t){return e[t]=document.getElementById(R(t)),e}),{});M({location:window.location,routes:t.routes,parentContainer:E(),shouldMount:!0,applicationContainers:e})}}function b(e){var t=e.detail,n=t.navigationIsCanceled,r=t.newUrl;n||q(r).forEach((function(e){var t=document.getElementById(R(e));t&&t.isConnected&&t.parentNode.removeChild(t)}))}function w(e,t){if(e&&e.childNodes&&t)for(var n={nextSibling:e.childNodes[0]},r=0;r<t.length;r++){var o,a=t[r];if("route"!==a.type){for(var i=null===(o=n)||void 0===o?void 0:o.nextSibling;(null===(c=i)||void 0===c?void 0:c.nodeType)===Node.TEXT_NODE&&""===i.textContent.trim();){var c;i=i.nextSibling}n=i,W(a)&&I(i,a)&&(a.connectedNode=i),a.routes&&w(i,a.routes)}else w(e,a.routes)}}function E(){return"string"==typeof t.containerEl?document.querySelector(t.containerEl):t.containerEl}},constructRoutes:function(e,n){if(e&&e.nodeName||"string"==typeof e){if(m&&!n&&window.singleSpaLayoutData&&(n=window.singleSpaLayoutData),"string"==typeof e){if(!m)throw Error("calling constructRoutes with a string on the server is not yet supported");if(!(e=(new DOMParser).parseFromString(e,"text/html").documentElement.querySelector("single-spa-router")))throw Error("constructRoutes should be called with a string HTML document that contains a <single-spa-router> element.")}e=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));m&&e.isConnected&&e.parentNode.removeChild(e);var n={routes:[],redirects:{}};P(e,"mode")&&(n.mode=P(e,"mode")),P(e,"base")&&(n.base=P(e,"base")),P(e,"containerEl")&&(n.containerEl=P(e,"containerEl"));for(var r=0;r<e.childNodes.length;r++){var o;(o=n.routes).push.apply(o,p(S(e.childNodes[r],t,n)))}return n}(e,n)}else if(n)throw Error("constructRoutes should be called either with an HTMLElement and layoutData, or a single json object.");return function(e){y("routesConfig",e);var n=e.disableWarnings;if(b("routesConfig",e,["mode","base","containerEl","routes","disableWarnings","redirects"],n),e.hasOwnProperty("containerEl")?function(e,t){if("string"==typeof t?""===t.trim():!(m&&t instanceof HTMLElement))throw Error("Invalid ".concat(e,": received ").concat(t," but expected either non-blank string or HTMLElement"))}("routesConfig.containerEl",e.containerEl):e.containerEl="body",e.hasOwnProperty("mode")||(e.mode="history"),function(e,t,n){if(n.indexOf(t)<0)throw Error("Invalid ".concat(e,": received '").concat(t,"' but expected ").concat(n.join(", ")))}("routesConfig.mode",e.mode,["history","hash"]),e.hasOwnProperty("base")?(w("routesConfig.base",e.base),e.base=(a=e.base,0!==a.indexOf("/")&&(a="/"+a),"/"!==a[a.length-1]&&(a+="/"),a)):e.base="/",e.hasOwnProperty("redirects"))for(var r in y("routesConfig.redirects",e.redirects),e.redirects){var o=e.redirects[r];E("routesConfig.redirects key",r),E("routesConfig.redirects['".concat(r,"']"),o)}var a;var i=m?window.location.pathname:"/",c="hash"===e.mode?i+"#":"";N("routesConfig.routes",e.routes,(function e(r,o,a){var i=a.parentPath,c=a.siblingActiveWhens,u=a.parentActiveWhen;if(y(o,r),"application"===r.type)b(o,r,["type","name","props","loader","error","className"],n),r.props&&y("".concat(o,".props"),r.props),w("".concat(o,".name"),r.name);else if("route"===r.type){b(o,r,["type","path","routes","props","default","exact"],n),r.hasOwnProperty("exact")&&g("".concat(o,".exact"),r.exact);var s,l=r.hasOwnProperty("path"),d=r.hasOwnProperty("default");if(l)w("".concat(o,".path"),r.path),s=O(i,r.path),r.activeWhen=t(s,r.exact),c.push(r.activeWhen);else{if(!d)throw Error("Invalid ".concat(o,": routes must have either a path or default property."));g("".concat(o,".default"),r.default),s=i,r.activeWhen=function(e,t){return function(n){return t(n)&&!e.some((function(e){return e(n)}))}}(c,u)}if(l&&d&&r.default)throw Error("Invalid ".concat(o,": cannot have both path and set default to true."));r.routes&&N("".concat(o,".routes"),r.routes,e,{parentPath:s,siblingActiveWhens:[],parentActiveWhen:r.activeWhen})}else{if("undefined"!=typeof Node&&r instanceof Node);else for(var f in r)"routes"!==f&&"attrs"!==f&&w("".concat(o,"['").concat(f,"']"),r[f],!1);r.routes&&N("".concat(o,".routes"),r.routes,e,{parentPath:i,siblingActiveWhens:c,parentActiveWhen:u})}}),{parentPath:c+e.base,parentActiveWhen:function(){return!0},siblingActiveWhens:[]}),delete e.disableWarnings}(e),e},matchRoute:function(e,t){w("path",t);var n=l({},e),r=e.base.slice(0,e.base.length-1);if(0===t.indexOf(r)){var o=m?window.location.origin:"http://localhost",a=new URL(O(o,t));n.routes=A(a,e.routes)}else n.routes=[];return n}});var m="undefined"!=typeof window;function y(e,t){if("object"!==d(t)||Array.isArray(t)||null===t)throw Error("Invalid ".concat(e,": received ").concat(Array.isArray(t)?"array":t," but expected a plain object"))}function g(e,t){if("boolean"!=typeof t)throw Error("Invalid ".concat(e,": received ").concat(d(t),", but expected a boolean"))}function b(e,t,n,r){if(!r){var o=Object.keys(t),a=[];o.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 w(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if("string"!=typeof t||n&&""===t.trim())throw Error("Invalid ".concat(e,": received '").concat(t,"', but expected a").concat(n?" non-blank":""," string"))}function E(e,t){if(w(e,t),t.indexOf("/")<0)throw Error("Invalid ".concat(e,": received '").concat(t,"', but expected an absolute path that starts with /"))}function N(e,t,n){if(!Array.isArray(t)&&("object"!==d(d(t))||"number"!==t.length))throw Error("Invalid ".concat(e,": received '").concat(t,"', but expected an array"));for(var r=arguments.length,o=new Array(r>3?r-3:0),a=3;a<r;a++)o[a-3]=arguments[a];for(var i=0;i<t.length;i++)n.apply(void 0,[t[i],"".concat(e,"[").concat(i,"]")].concat(o))}function A(e,t){var n=[];return t.forEach((function(t){"application"===t.type?n.push(t):"route"===t.type?t.activeWhen(e)&&n.push(l(l({},t),{},{routes:A(e,t.routes)})):Array.isArray(t.routes)?n.push(l(l({},t),{},{routes:A(e,t.routes)})):n.push(t)})),n}function O(e,t){var n;return"/"===(n="/"===e.substr(-1)?"/"===t[0]?e+t.slice(1):e+t:"/"===t[0]?e+t:e+"/"+t).substr(-1)&&n.length>1&&(n=n.slice(0,n.length-1)),n}function C(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return e[n];return null}var x="undefined"!=typeof Symbol?Symbol():"@";function P(e,t){if(m)return e.getAttribute(t);var n=C(e.attrs,(function(e){return e.name===t.toLowerCase()}));return n?n.value:null}function L(e,t){return m?e.hasAttribute(t):e.attrs.some((function(e){return e.name===t}))}function S(e,t,n){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 r={type:"application",name:P(e,"name")},o=P(e,"loader");if(o)if(t.loaders&&t.loaders.hasOwnProperty(o))r.loader=t.loaders[o];else if(m)throw Error("Application loader '".concat(o,"' was not defined in the htmlLayoutData"));var a=P(e,"error");if(a)if(t.errors&&t.errors.hasOwnProperty(a))r.error=t.errors[a];else if(m)throw Error("Application error handler '".concat(o,"' was not defined in the htmlLayoutData"));var i=P(e,"class");return i&&(r.className=i),j(e,r,t),[r]}if("route"===e.nodeName.toLowerCase()){var c={type:"route",routes:[]},u=P(e,"path");u&&(c.path=u),L(e,"default")&&(c.default=!0),L(e,"exact")&&(c.exact=!0),j(e,c,t);for(var s=0;s<e.childNodes.length;s++){var l;(l=c.routes).push.apply(l,p(S(e.childNodes[s],t,n)))}return[c]}if("redirect"===e.nodeName.toLowerCase())return n.redirects[O("/",P(e,"from"))]=O("/",P(e,"to")),[];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 d=0;d<e.childNodes.length;d++){var f;(f=e.routes).push.apply(f,p(S(e.childNodes[d],t,n)))}}return[e]}if(e.childNodes){for(var h={type:e.nodeName.toLowerCase(),routes:[],attrs:e.attrs},v=0;v<e.childNodes.length;v++){var y;(y=h.routes).push.apply(y,p(S(e.childNodes[v],t,n)))}return[h]}return"#comment"===e.nodeName?[{type:"#comment",value:e.data}]:"#text"===e.nodeName?[{type:"#text",value:e.value}]:void 0}function j(e,t,n){for(var r=(P(e,"props")||"").split(","),o=0;o<r.length;o++){var a=r[o].trim();if(0!==a.length)if(t.props||(t.props={}),n.props&&n.props.hasOwnProperty(a))t.props[a]=n.props[a];else{if(m)throw Error("Prop '".concat(a,"' was not defined in the htmlLayoutData. Either remove this attribute from the HTML element or provide the prop's value"));t.props[a]=x}}}function T(e){return{bootstrap:function(){return Promise.resolve()},mount:function(t){return Promise.resolve().then((function(){t.domElement.innerHTML=e}))},unmount:function(e){return Promise.resolve().then((function(){e.domElement.innerHTML=""}))}}}function W(e){return t=["application","route","fragment","assets","redirect"],n=e.type,!t.some((function(e){return e===n}));var t,n}function I(e,t){var n,r;return!!e&&(r=t instanceof Node?t:function(e){switch(e.type){case"#text":return document.createTextNode(e.value);case"#comment":return document.createComment(e.value);default:var t=document.createElement(e.type);return e.attrs.forEach((function(e){t.setAttribute(e.name,e.value)})),t}}(t),(n=e).nodeType===r.nodeType&&n.nodeName===r.nodeName&&function(e,t){var n=e.getAttributeNames?e.getAttributeNames().sort():[],r=e.getAttributeNames?e.getAttributeNames().sort():[];return n.length===r.length&&!n.some((function(n){return e.getAttribute(n)!==t.getAttribute(n)}))}(n,r))}function M(e){var t=e.location,n=e.routes,r=e.parentContainer,o=e.previousSibling,a=e.shouldMount,i=e.applicationContainers;return n.forEach((function(e,n){if("application"===e.type){if(a){var c,u=R(e.name);i[e.name]?c=i[e.name]:document.getElementById(u)?c=document.getElementById(u):(c=document.createElement("div")).id=u,"string"==typeof e.className?c.className=e.className:"string"!=typeof e.className&&"string"==typeof c.className&&c.removeAttribute("class"),H(c,r,o),o=c}}else if("route"===e.type)o=M({location:t,routes:e.routes,parentContainer:r,previousSibling:o,shouldMount:a&&e.activeWhen(t),applicationContainers:i});else if(e instanceof Node||"string"==typeof e.type)if(a){if(!e.connectedNode){var s=e instanceof Node?e.cloneNode(!1):B(e);e.connectedNode=s}H(e.connectedNode,r,o),e.routes&&M({location:t,routes:e.routes,parentContainer:e.connectedNode,previousSibling:null,shouldMount:a,applicationContainers:i}),o=e.connectedNode}else(l=e.connectedNode)&&(l.remove?l.remove():l.parentNode.removeChild(l)),delete e.connectedNode;var l})),o}function D(e){for(var t=e.applicationName,n=e.location,r=e.routes,o=0;o<r.length;o++){var a=r[o];if("application"===a.type){if(a.name===t)return a}else if("route"===a.type){if(a.activeWhen(n)){var i=D({applicationName:t,location:n,routes:a.routes});if(i)return i}}else if(a.routes){var c=D({applicationName:t,location:n,routes:a.routes});if(c)return c}}}function H(e,t,n){var r=n?n.nextSibling:t.firstChild;r!==e&&t.insertBefore(e,r)}function R(e){return"single-spa-application:".concat(e)}function B(e){if("#text"===e.type.toLowerCase())return document.createTextNode(e.value);if("#comment"===e.type.toLowerCase())return document.createComment(e.value);var t=document.createElement(e.type);return(e.attrs||[]).forEach((function(e){t.setAttribute(e.name,e.value)})),t.routes&&t.routes.forEach((function(e){t.appendChild(B(e))})),t}function k(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:location;return t["hash"===e.mode?"hash":"pathname"]}function U(e){try{return new URL(e)}catch(n){var t=document.createElement("a");return t.href=e,t}}function q(e){var t=[],n=i(e?U(e):location);return c().forEach((function(e){n.indexOf(e)<0&&t.push(e)})),t}function F(e,t,n,r){r.forEach((function(r){"application"===r.type?(e[r.name]||(e[r.name]=[]),e[r.name].push({activeWhen:t,props:X(n,r.props),loader:r.loader})):"route"===r.type?F(e,r.activeWhen,X(n,r.props),r.routes):r.routes&&F(e,t,n,r.routes)}))}function X(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return l(l({},e),t)}function _(){return!0}}}}));