-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: new "whole page" hydration strategy
- Loading branch information
1 parent
1ea24a3
commit 2a09695
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import '@lit-labs/ssr-client/lit-element-hydrate-support.js'; | ||
|
||
import { RouteModule, type Parameters } from '@gracile/engine/routes/route'; | ||
import { hydrate } from '@lit-labs/ssr-client'; | ||
// eslint-disable-next-line import-x/no-unresolved | ||
import { routeImports } from 'gracile:client:routes'; | ||
import { premiseUrl } from '@gracile/internal-utils/paths'; | ||
import { URLPattern } from 'urlpattern-polyfill/urlpattern'; | ||
|
||
async function init() { | ||
const url = new URL(globalThis.document.location.href); | ||
const urlPattern = new URLPattern({ | ||
baseURL: url.href, | ||
}); | ||
|
||
let route: RouteModule | undefined; | ||
let parameters: Parameters = {}; | ||
for (const [pattern, routeImport] of routeImports.entries()) { | ||
const match = urlPattern.exec(pattern, url.href); | ||
if (match) { | ||
// eslint-disable-next-line unicorn/no-await-expression-member | ||
const loaded = (await routeImport()).default(RouteModule); | ||
route = loaded; | ||
parameters = match.pathname.groups; | ||
break; | ||
} | ||
} | ||
if (!route?.template) throw new ReferenceError('No route template found.'); | ||
|
||
const propertiesUrl = premiseUrl(url.pathname, 'props'); | ||
const properties = await fetch(propertiesUrl).then((r) => r.json()); | ||
|
||
const template = route.template({ | ||
url, | ||
params: parameters, | ||
props: properties, | ||
}); | ||
hydrate(template, document.body); | ||
} | ||
|
||
document.addEventListener('DOMContentLoaded', () => { | ||
void init(); | ||
}); |