0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-03-17 23:11:29 -05:00

feat: add router package and example

This commit is contained in:
Nate Moore 2022-03-27 09:30:12 -05:00
parent da77db8555
commit 2a30904fe3
23 changed files with 311 additions and 0 deletions

17
examples/router/.gitignore vendored Normal file
View file

@ -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
examples/router/.npmrc Normal file
View file

@ -0,0 +1,2 @@
# Expose Astro dependencies for `pnpm` users
shamefully-hoist=true

View file

@ -0,0 +1,6 @@
{
"startCommand": "npm start",
"env": {
"ENABLE_CJS_IMPORTS": true
}
}

View file

@ -0,0 +1,4 @@
{
"recommendations": ["astro-build.astro-vscode"],
"unwantedRecommendations": []
}

11
examples/router/.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "./node_modules/.bin/astro dev",
"name": "Development server",
"request": "launch",
"type": "node-terminal"
}
]
}

43
examples/router/README.md Normal file
View file

@ -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).

View file

@ -0,0 +1,9 @@
import { defineConfig } from 'astro/config';
import spa from "@astrojs/spa";
// https://astro.build/config
export default defineConfig({
integrations: [
spa()
]
});

View file

@ -0,0 +1,18 @@
{
"name": "@example/router",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview"
},
"devDependencies": {
"@astrojs/spa": "^0.0.1",
"astro": "^0.25.2"
},
"dependencies": {
"@astrojs/router": "^0.0.1"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View file

@ -0,0 +1,11 @@
{
"infiniteLoopProtection": true,
"hardReloadOnChange": false,
"view": "browser",
"template": "node",
"container": {
"port": 3000,
"startScript": "start",
"node": "14"
}
}

View file

@ -0,0 +1,28 @@
---
import { Link, Outlet } from '@astrojs/router';
---
<html lang="en">
<head>
<title>Router</title>
<style>
main {
display: flex;
}
</style>
<script type="module" hoist src="@astrojs/router/client.js" />
</head>
<body>
<h1>Router</h1>
<main>
<ul>
<li><Link for="tabs" to="/dashboard">Dashboard</Link></li>
<li><Link for="tabs" to="/about">About</Link></li>
</ul>
<Outlet id="tabs" default="/dashboard" />
</main>
</body>
</html>

View file

@ -0,0 +1,3 @@
<h3>One</h3>
<img src="https://images.unsplash.com/photo-1608178398319-48f814d0750c" width="640">

View file

@ -0,0 +1,3 @@
<h3>Three</h3>
<img src="https://images.unsplash.com/photo-1462331940025-496dfbfc7564" width="640">

View file

@ -0,0 +1,3 @@
<h3>Two</h3>
<img src="https://images.unsplash.com/photo-1610296669228-602fa827fc1f" width="640">

View file

@ -0,0 +1,3 @@
<h2>About</h2>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Sed saepe iste ex laboriosam? A quasi tempora provident voluptate itaque ea laboriosam numquam adipisci quidem porro. Nulla saepe illo odit assumenda.</p>

View file

@ -0,0 +1,15 @@
---
import { Link, Outlet } from '@astrojs/router';
---
<h2>Dashboard</h2>
<div>
<ul>
<li><Link for="dashboard" to="/one">One</Link></li>
<li><Link for="dashboard" to="/two">Two</Link></li>
<li><Link for="dashboard" to="/three">Three</Link></li>
</ul>
<Outlet id="dashboard" default="/one" />
</div>

View file

@ -0,0 +1,5 @@
{
"compilerOptions": {
"moduleResolution": "node"
}
}

View file

@ -0,0 +1,5 @@
---
const { for: htmlFor, to, ...props } = Astro.props;
---
<router-link {...props} for={htmlFor} to={to}><a href="#"><slot /></a></router-link>

View file

@ -0,0 +1,25 @@
---
const { default: route, id } = Astro.props;
function getRoutePath(...args) {
return args.map(arg => arg.replace(/^\/|\/$/g, '')).join('/');
}
let Child = Fragment;
if (route) {
try {
const { default: Component } = await import(`/src/pages/routes/${getRoutePath(id, route)}.astro`);
if (Component) {
Child = Component;
}
} catch (e) {}
try {
const { default: Component } = await import(`/src/pages/routes/${getRoutePath(id, route)}/index.astro`);
if (Component) {
Child = Component;
}
} catch (e) {}
}
---
<router-outlet id={id} route={route}><Child /></router-outlet>

54
packages/router/client.js Normal file
View file

@ -0,0 +1,54 @@
import morph from 'micromorph';
function getRoutePath(...args) {
return args.map(arg => arg.replace(/^\/|\/$/, '')).join('/');
}
const p = new DOMParser();
class RouterOutlet extends HTMLElement {
connectedCallback() {
this.isUpdating = false;
this.updateLinks();
}
updateLinks() {
document.querySelectorAll(`router-link[for="${this.getAttribute('id')}"]`).forEach(link => {
link.ariaCurrent = (link.to === this.route);
})
}
static get observedAttributes() { return ['route']; }
async attributeChangedCallback(_, oldValue, newValue) {
if (!this.isConnected) return;
if (this.isUpdating) return;
if (oldValue === newValue) return;
this.isUpdating = true;
const text = await fetch(`/routes/${getRoutePath(this.getAttribute('id'), newValue)}`).then(res => res.text());
const children = p.parseFromString(text, 'text/html').body.children;
const clone = this.cloneNode(true)
clone.replaceChildren(...children);
await morph(this, clone);
this.updateLinks();
this.isUpdating = false;
}
}
customElements.define('router-outlet', RouterOutlet);
class RouterLink extends HTMLElement {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
event.preventDefault();
event.stopPropagation();
this.target.setAttribute('route', this.getAttribute('to'));
}
connectedCallback() {
this.target = document.querySelector(`router-outlet#${this.getAttribute('for')}`);
this.addEventListener('click', this.handleClick);
}
disconnectedCallback() {
this.target = null;
this.removeEventListener('click', this.handleClick);
}
}
customElements.define('router-link', RouterLink);

2
packages/router/index.js Normal file
View file

@ -0,0 +1,2 @@
export { default as Link } from './Link.astro';
export { default as Outlet } from './Outlet.astro';

View file

@ -0,0 +1,30 @@
{
"name": "@astrojs/router",
"description": "Astro Routing",
"version": "0.0.1",
"type": "module",
"author": "withastro",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/withastro/astro.git",
"directory": "packages/router"
},
"keywords": [
"astro-component"
],
"bugs": "https://github.com/withastro/astro/issues",
"homepage": "https://astro.build",
"exports": {
".": "./index.js",
"./client.js": "./client.js",
"./package.json": "./package.json"
},
"dependencies": {
"micromorph": "^0.1.2"
},
"devDependencies": {
"astro": "workspace:*",
"astro-scripts": "workspace:*"
}
}

14
pnpm-lock.yaml generated
View file

@ -286,10 +286,13 @@ importers:
examples/spa:
specifiers:
'@astrojs/router': ^0.0.1
'@astrojs/spa': ^0.0.1
'@astrojs/vue': ^0.0.2
astro: ^0.25.2
vue: ^3.2.30
dependencies:
'@astrojs/router': link:../../packages/router
devDependencies:
'@astrojs/spa': link:../../packages/integrations/spa
'@astrojs/vue': link:../../packages/integrations/vue
@ -1484,6 +1487,17 @@ importers:
vite: 2.8.6
vue: 3.2.31
packages/router:
specifiers:
astro: workspace:*
astro-scripts: workspace:*
micromorph: ^0.1.2
dependencies:
micromorph: 0.1.2
devDependencies:
astro: link:../astro
astro-scripts: link:../../scripts
packages/webapi:
specifiers:
'@rollup/plugin-alias': ^3.1.9