A routing Lit container (Light DOM) Base Class for modern Web Component-based SPA apps.
PureSPA
is a Lit Web Component that renders your SPA pages based on an extensible JavaScript configuration file that contains the routes and each route's responsible logic (the SPA pages).
Because PureSPA uses relatively new Browser APIs, polyfills are provided for functionality that is not yet available in some browsers, like Safari and Firefox.
npm i pure-spa --savedev
Create a class that extends PureSPA
, and return a router config in the static config
property:
import { PureSPA } from "pure-spa";
import { config } from "./my-app-config.js";
customElements.define(
"my-app",
class MyApp extends PureSPA {
/**
* Set app.config structure
*/
static get config() {
return config;
}
}
);
import { PageAbout } from "./pages/page-about";
import { PageHome } from "./pages/page-home";
export const config = {
routes: {
"/": {
name: "Home",
run: PageHome,
},
"/about": {
run: PageAbout,
},
},
};
PureSPA
's Lit render() method renders a route based on the page a user navigates to.
import { config } from "./my-app-config";
import { PureSPA } from "pure-spa";
import { html } from "lit";
import { ref, createRef } from "lit/directives/ref.js";
customElements.define(
"my-app",
class MyApp extends PureSPA {
#h1 = createRef();
static get config() {
return config;
}
render() {
return html`
<header>
<h1 ${ref(this.#h1)}></h1>
</header>
<main>${super.render()}</main>
`;
}
firstUpdated() {
super.firstUpdated();
this.on("routecomplete", () => {
this.#h1.value.textContent = this.activeRoute.name;
});
}
}
);
Sub routes are declared as a routes
nesting on a route:
"/program": {
run: PageProgram,
routes: {
"/activation": {
run: PageProgramActivation,
},
},
In the case of an URLPattern
(RegExp) capturing, the captured data will be passed to a Lit property in the page component:
import { PageAbout } from "./pages/page-about";
import { PageHome } from "./pages/page-home";
import { PageProfile } from "./pages/page-profile";
export const config = {
routes: {
"/": {
name: "Home",
run: PageHome,
},
"/about": {
run: PageAbout,
},
"/profile": {
run: PageProfile,
routes: {
"/:selector": {},
},
},
},
};
In this case, the PageProfile
class can retrieve the captured route data using the Lit static properties, using routeOrigin
:
static get properties() {
return {
profile: { type: Object },
selector: { type: String, attribute: true, routeOrigin: 'pathname' },
loading: { type: Boolean },
};
}
As you can see in the example above, if you use this subroute syntax, the parent route's configured component will also be triggered for the sub route.