Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SPA Integration #2899

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions examples/spa/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# build output
dist

# dependencies
node_modules/

# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# environment variables
.env
.env.production

# macOS-specific files
.DS_Store
2 changes: 2 additions & 0 deletions examples/spa/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Expose Astro dependencies for `pnpm` users
shamefully-hoist=true
6 changes: 6 additions & 0 deletions examples/spa/.stackblitzrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"startCommand": "npm start",
"env": {
"ENABLE_CJS_IMPORTS": true
}
}
4 changes: 4 additions & 0 deletions examples/spa/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"recommendations": ["astro-build.astro-vscode"],
"unwantedRecommendations": []
}
11 changes: 11 additions & 0 deletions examples/spa/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "./node_modules/.bin/astro dev",
"name": "Development server",
"request": "launch",
"type": "node-terminal"
}
]
}
43 changes: 43 additions & 0 deletions examples/spa/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Astro Starter Kit: Minimal

```
npm init astro -- --template minimal
```

[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/astro/tree/latest/examples/minimal)

> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!

## 🚀 Project Structure

Inside of your Astro project, you'll see the following folders and files:

```
/
├── public/
├── src/
│ └── pages/
│ └── index.astro
└── package.json
```

Astro looks for `.astro` or `.md` files in the `src/pages/` directory. Each page is exposed as a route based on its file name.

There's nothing special about `src/components/`, but that's where we like to put any Astro/React/Vue/Svelte/Preact components.

Any static assets, like images, can be placed in the `public/` directory.

## 🧞 Commands

All commands are run from the root of the project, from a terminal:

| Command | Action |
|:---------------- |:-------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:3000` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |

## 👀 Want to learn more?

Feel free to check [our documentation](https://github.com/withastro/astro) or jump into our [Discord server](https://astro.build/chat).
11 changes: 11 additions & 0 deletions examples/spa/astro.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineConfig } from 'astro/config';
import spa from "@astrojs/spa";
import vue from "@astrojs/vue";

// https://astro.build/config
export default defineConfig({
integrations: [
spa(),
vue()
]
});
17 changes: 17 additions & 0 deletions examples/spa/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "@example/spa",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview"
},
"devDependencies": {
"@astrojs/vue": "^0.1.5",
"@astrojs/spa": "^0.0.1",
"astro": "^1.0.0-beta.38",
"vue": "^3.2.36"
}
}
Binary file added examples/spa/public/favicon.ico
Binary file not shown.
11 changes: 11 additions & 0 deletions examples/spa/sandbox.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"infiniteLoopProtection": true,
"hardReloadOnChange": false,
"view": "browser",
"template": "node",
"container": {
"port": 3000,
"startScript": "start",
"node": "14"
}
}
52 changes: 52 additions & 0 deletions examples/spa/src/components/Counter.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<template>
<div id="vue" class="counter">
<p><slot /></p>
<div>
<button @click="subtract()">-</button>
<pre>{{ count }}</pre>
<button @click="add()">+</button>
</div>
</div>
</template>

<style scoped>
.counter {
display: flex;
text-align: center;
flex-direction: column;
padding: 0.5rem;
margin: 0.25rem;
border: 1px solid red;
min-width: 12em;
font-size: 1.25rem;
}
p {
flex: 1;
}
.counter > div {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
gap: 0.25rem;
}
</style>

<script>
import { ref } from 'vue';
export default {
props: {
initialCount: Number,
},
setup({ initialCount = 0 }) {
const count = ref(initialCount);
const add = () => (count.value = count.value + 1);
const subtract = () => (count.value = count.value - 1);
return {
count,
add,
subtract,
};
},
};
</script>
40 changes: 40 additions & 0 deletions examples/spa/src/pages/[pokemon].astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
import Counter from '../components/Counter.vue';

export async function getStaticPaths() {
const { results: allPokemon } = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=2000`).then(res => res.json());
return allPokemon.map((pokemon, i, all) => ({
params: { pokemon: pokemon.name },
props: {
prev: `/${all[i - 1]?.name ?? ''}`,
index: i,
pokemon,
next: `/${all[i + 1]?.name ?? ''}`,
}
}));
}

const { pokemon, prev, next } = Astro.props;
---
<html lang="en">
<head>
<title>{pokemon.name}</title>
<style>
main {
display: flex;
}
</style>
</head>

<body>
<h1>{pokemon.name}</h1>

<main>
<Counter client:visible>
Persistent!
</Counter>
</main>

<p><a href={prev}>Previous</a> / <a href={next}>Next</a></p>
</body>
</html>
5 changes: 5 additions & 0 deletions examples/spa/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"compilerOptions": {
"moduleResolution": "node"
}
}
1 change: 1 addition & 0 deletions packages/astro/src/runtime/client/media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export default async function onMedia(
mql.addEventListener('change', cb, { once: true });
}
}
window.addEventListener('astro:locationchange', media, { once: true })
}
media();
}
2 changes: 1 addition & 1 deletion packages/astro/src/runtime/client/visible.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default async function onVisible(
io.observe(child);
}
}
window.addEventListener('astro:locationchange', visible, { once: true })
}

visible();
}
21 changes: 21 additions & 0 deletions packages/integrations/spa/client-persist.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import listen from 'micromorph/spa';

export default () =>
listen({
beforeDiff(doc) {
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;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data-persist is a special attribute that instructs micromorph to leave a node in place during diffing.

island.replaceWith(current);
}
}
},
afterDiff() {
for (const island of document.querySelectorAll('astro-root')) {
delete island.dataset.persist;
}
window.dispatchEvent(new CustomEvent('astro:locationchange'));
natemoo-re marked this conversation as resolved.
Show resolved Hide resolved
},
});
8 changes: 8 additions & 0 deletions packages/integrations/spa/client-static.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import listen from 'micromorph/spa';

export default () =>
listen({
afterDiff() {
window.dispatchEvent(new CustomEvent('astro:locationchange'));
},
});
1 change: 1 addition & 0 deletions packages/integrations/spa/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default ({ persistent }) => (persistent ? import('./client-persist.js') : import('./client-static.js')).then(res => res.default())
37 changes: 37 additions & 0 deletions packages/integrations/spa/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "@astrojs/spa",
"description": "SPA Astro Integrations",
"version": "0.0.1",
"type": "module",
"types": "./dist/index.d.ts",
"author": "withastro",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/withastro/astro.git",
"directory": "packages/integrations/turbolinks"
},
"keywords": [
"astro-component",
"performance"
],
"bugs": "https://github.com/withastro/astro/issues",
"homepage": "https://astro.build",
"exports": {
".": "./dist/index.js",
"./client.js": "./client.js",
"./package.json": "./package.json"
},
"scripts": {
"build": "astro-scripts build \"src/**/*.ts\" && tsc",
"build:ci": "astro-scripts build \"src/**/*.ts\"",
"dev": "astro-scripts dev \"src/**/*.ts\""
},
"dependencies": {
"micromorph": "^0.1.2"
},
"devDependencies": {
"astro": "workspace:*",
"astro-scripts": "workspace:*"
}
}
19 changes: 19 additions & 0 deletions packages/integrations/spa/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { AstroIntegration } from 'astro';

export interface SpaOptions {
persistent?: boolean;
}

export default function createPlugin({ persistent = true }: SpaOptions = {}): AstroIntegration {
return {
name: '@astrojs/spa',
hooks: {
'astro:config:setup': ({ injectScript }) => {
// 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({ persistent: ${persistent} });`);
},
},
};
}
10 changes: 10 additions & 0 deletions packages/integrations/spa/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../../tsconfig.base.json",
"include": ["src"],
"compilerOptions": {
"allowJs": true,
"module": "ES2020",
"outDir": "./dist",
"target": "ES2020"
}
}
Loading