0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-03-24 23:21:57 -05:00

feat(spa): allow persistent option

This commit is contained in:
Nate Moore 2022-03-26 05:19:52 -05:00
parent 3b13dd4109
commit 51daacfabd
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({ 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() { 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'; import type { AstroIntegration } from 'astro';
export default function createPlugin(): AstroIntegration { export interface SpaOptions {
persistent?: boolean;
}
export default function createPlugin({ persistent = true }: SpaOptions): AstroIntegration {
return { return {
name: '@astrojs/spa', name: '@astrojs/spa',
hooks: { 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 // 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 // from our own package so that package managers like pnpm don't get mad and
// can follow the import correctly. // 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} });`);
}, },
}, },
}; };