feat(spa): allow persistent option

This commit is contained in:
Nate Moore 2022-03-26 05:19:52 -05:00 committed by Nate Moore
parent 1efab4aa88
commit 1b4aa8f6a7
2 changed files with 27 additions and 7 deletions

View file

@ -1,9 +1,25 @@
import listen from 'micromorph/spa'
import listen from 'micromorph/spa';
export default () => {
export default ({ persistent }) => {
listen({
beforeDiff(doc) {
if (!persistent) return;
for (const island of doc.querySelectorAll('astro-root')) {
const uid = island.getAttribute('uid');
const current = document.querySelector(`astro-root[uid="${uid}"]`);
if (current) {
current.dataset.persist = true;
island.replaceWith(current);
}
}
},
afterDiff() {
window.dispatchEvent(new CustomEvent('astro:locationchange'))
}
if (persistent) {
for (const island of doc.querySelectorAll('astro-root')) {
delete island.dataset.persist
}
}
window.dispatchEvent(new CustomEvent('astro:locationchange'));
},
});
}
};

View file

@ -1,6 +1,10 @@
import type { AstroIntegration } from 'astro';
export default function createPlugin(): AstroIntegration {
export interface SpaOptions {
persistent?: boolean;
}
export default function createPlugin({ persistent = true }: SpaOptions): AstroIntegration {
return {
name: '@astrojs/spa',
hooks: {
@ -8,7 +12,7 @@ export default function createPlugin(): AstroIntegration {
// This gets injected into the user's page, so we need to re-export Turbolinks
// from our own package so that package managers like pnpm don't get mad and
// can follow the import correctly.
injectScript('page', `import listen from "@astrojs/spa/client.js"; listen();`);
injectScript('page', `import listen from "@astrojs/spa/client.js"; listen({ persistent: ${persistent} });`);
},
},
};