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

support route parameters and inject them into the component #354

Merged
merged 21 commits into from
Feb 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/neat-wasps-mix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'preact-iso': minor
---

Support route params and inject them into the rendered route, add the `useRoute` hook so we can retrieve route parameters from anywhere in the subtree.
7 changes: 6 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ on:
- main
paths:
- packages/wmr/**
- packages/preact-iso/**
pull_request:
paths:
- packages/wmr/**
- packages/preact-iso/**

jobs:
build:
Expand All @@ -28,8 +30,11 @@ jobs:
run: yarn --frozen-lockfile
- name: Build
run: yarn workspace wmr build
- name: Test
- name: Test wmr
run: yarn workspace wmr test
- name: Test preact-iso
run: yarn workspace preact-iso test

lhci:
runs-on: ubuntu-latest
steps:
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
},
"eslintIgnore": [
"*.cjs",
"*.ts",
"packages/wmr/test/fixtures/**/*.expected.*",
"packages/wmr/test/fixtures/*/dist",
"packages/wmr/test/fixtures/*/.cache"
Expand Down
8 changes: 6 additions & 2 deletions packages/preact-iso/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,20 +85,24 @@ import { LocationProvider, Router, useLoc } from 'preact-iso/router';
// Asynchronous (throws a promise)
const Home = lazy(() => import('./routes/home.js'));
const Profile = lazy(() => import('./routes/profile.js'));
const Profiles = lazy(() => import('./routes/profiles.js'));

const App = () => (
<LocationProvider>
<ErrorBoundary>
<Router>
<Home path="/" />
<Profile path="/profile" />
<Profiles path="/profiles" />
<Profile path="/profiles/:id" />
</Router>
</ErrorBoundary>
</LocationProvider>
);
```

During prerendering, the generated HTML includes our full `<Home>` and `<Profile>` component output because it waits for the `lazy()`-wrapped `import()` to resolve.
During prerendering, the generated HTML includes our full `<Home>` and `<Profiles>` component output because it waits for the `lazy()`-wrapped `import()` to resolve.

You can use the `useRoute` hook to get information of the route you are currently on.

**Progressive Hydration:** When the app is hydrated on the client, the route (`Home` or `Profile` in this case) suspends. This causes hydration for that part of the page to be deferred until the route's `import()` is resolved, at which point that part of the page automatically finishes hydrating.

Expand Down
9 changes: 1 addition & 8 deletions packages/preact-iso/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import { VNode } from 'preact';
import { PrerenderOptions } from './prerender';

export { default as prerender } from './prerender';
export { Router, LocationProvider, useLoc, useLocation } from './router';
export { default as lazy, ErrorBoundary } from './lazy';
export { default as hydrate } from './hydrate';

export default function prerender(
vnode: VNode,
options?: PrerenderOptions
): Promise<{ html: string; links: Set<string> }>;
4 changes: 4 additions & 0 deletions packages/preact-iso/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
"module": "./index.js",
"types": "./index.d.ts",
"type": "module",
"scripts": {
"test": "node --experimental-vm-modules node_modules/.bin/jest"
},
"exports": {
".": "./index.js",
"./router": "./router.js",
Expand All @@ -21,6 +24,7 @@
},
"license": "MIT",
"devDependencies": {
"jest": "26.6.3",
"preact": "^10.5.7",
"preact-render-to-string": "^5.1.12"
},
Expand Down
7 changes: 6 additions & 1 deletion packages/preact-iso/prerender.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ export interface PrerenderOptions {
props?: Record<string, unknown>;
}

export interface PrerenderResult {
html: string;
links?: Set<string>
}

export default function prerender(
vnode: VNode,
options?: PrerenderOptions
): Promise<{ html: string; links: Set<string> }>;
): Promise<PrerenderResult>;
12 changes: 10 additions & 2 deletions packages/preact-iso/router.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,17 @@ export const LocationProvider: FunctionComponent;

export function Router(props: { onLoadEnd?: () => void; onLoadStart?: () => void; children?: VNode[] }): VNode;

type LocationHook = { url: string; path: string; query: Record<string, string>; route: (url: string) => void };
export const useLoc: () => LocationHook;
interface LocationHook {
url: string;
path: string;
query: Record<string, string>;
route: (url: string) => void;
};
export const useLocation: () => LocationHook;
/** @deprecated renamed to useLocation() */
export const useLoc: () => LocationHook;

export const useRoute: () => { [key: string]: string };

interface RoutableProps {
path?: string;
Expand Down
40 changes: 33 additions & 7 deletions packages/preact-iso/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,28 @@ const UPDATE = (state, url, push) => {
return url;
};

export const exec = (url, route, matches) => {
url = url.trim('/').split('/');
route = (route || '').trim('/').split('/');
for (let i = 0, val; i < Math.max(url.length, route.length); i++) {
let [, m, param, flag] = (route[i] || '').match(/^(:?)(.*?)([+*?]?)$/);
val = url[i];
// segment match:
if (!m && param == val) continue;
// segment mismatch / missing required field:
if (!m || (!val && flag != '?' && flag != '*')) return;
// field match:
matches[param] = val && decodeURIComponent(val);
// normal/optional field:
if (flag >= '?') continue;
// rest (+/*) match:
matches[param] = url.slice(i).map(decodeURIComponent).join('/');
break;
}

return matches;
};

export function LocationProvider(props) {
const [url, route] = useReducer(UPDATE, location.pathname + location.search);

Expand Down Expand Up @@ -82,20 +104,24 @@ export function Router(props) {
} else commit();
}, [url]);

const children = [].concat(...props.children);
let p, d, m;
[].concat(props.children || []).some(vnode => {
const matches = exec(path, vnode.props.path, (m = { path, query }));
if (matches) {
return (p = h(RouteContext.Provider, { value: m }, cloneElement(vnode, m)));
}

let a = children.filter(c => c.props.path === path);

if (a.length == 0) a = children.filter(c => c.props.default);

curChildren.current = a.map((p, i) => cloneElement(p, { path, query }));
if (vnode.props.default) d = cloneElement(vnode, m);
});

return curChildren.current.concat(prevChildren.current || []);
return [(curChildren.current = p || d), prevChildren.current];
}

Router.Provider = LocationProvider;

LocationProvider.ctx = createContext(/** @type {{ url: string, path: string, query: object, route }} */ ({}));
const RouteContext = createContext({});

export const useLoc = () => useContext(LocationProvider.ctx);
export const useLocation = useLoc;
export const useRoute = () => useContext(RouteContext);
27 changes: 27 additions & 0 deletions packages/preact-iso/test/match.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { exec } from '../router.js';

describe('match', () => {
it('Base route', () => {
const accurateResult = exec('/', '/', { path: '/' });
expect(accurateResult).toEqual({ path: '/' });

const inaccurateResult = exec('/user/1', '/', { path: '/' });
expect(inaccurateResult).toEqual(undefined);
});

it('Param route', () => {
const accurateResult = exec('/user/2', '/user/:id', { path: '/' });
expect(accurateResult).toEqual({ path: '/', id: '2' });

const inaccurateResult = exec('/', '/user/:id', { path: '/' });
expect(inaccurateResult).toEqual(undefined);
});

it('Optional param route', () => {
const accurateResult = exec('/user', '/user/:id?', { path: '/' });
expect(accurateResult).toEqual({ path: '/' });

const inaccurateResult = exec('/', '/user/:id?', { path: '/' });
expect(inaccurateResult).toEqual(undefined);
});
});
6 changes: 3 additions & 3 deletions packages/wmr/demo/public/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { h, render } from 'preact';
import { Loc, Router } from './lib/loc.js';
import { LocationProvider, Router } from './lib/loc.js';
import lazy, { ErrorBoundary } from './lib/lazy.js';
import Home from './pages/home.js';
// import About from './pages/about/index.js';
Expand All @@ -15,7 +15,7 @@ const Environment = lazy(async () => (await import('./pages/environment/index.js

export function App() {
return (
<Loc>
<LocationProvider>
<div class="app">
<Header />
<ErrorBoundary>
Expand All @@ -30,7 +30,7 @@ export function App() {
</Router>
</ErrorBoundary>
</div>
</Loc>
</LocationProvider>
);
}

Expand Down
77 changes: 66 additions & 11 deletions packages/wmr/demo/public/lib/loc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,51 +5,89 @@ const UPDATE = (state, url, push) => {
if (url && url.type === 'click') {
const link = url.target.closest('a[href]');
if (!link || link.origin != location.origin) return state;

url.preventDefault();
push = true;
url = link.href.replace(location.origin, '');
} else if (typeof url !== 'string') url = location.pathname + location.search;
} else if (typeof url !== 'string') {
url = location.pathname + location.search;
}

if (push === true) history.pushState(null, '', url);
else if (push === false) history.replaceState(null, '', url);
return url;
};

export function Loc(props) {
const exec = (url, route, matches) => {
url = url.trim('/').split('/');
route = (route || '').trim('/').split('/');
for (let i = 0, val; i < Math.max(url.length, route.length); i++) {
let [, m, param, flag] = (route[i] || '').match(/^(\:?)(.*?)([+*?]?)$/);
val = url[i];
// segment match:
if (!m && param == val) continue;
// segment mismatch / missing required field:
if (!m || (!val && flag != '?' && flag != '*')) return;
// field match:
matches[param] = val && decodeURIComponent(val);
// normal/optional field:
if (flag >= '?') continue;
// rest (+/*) match:
matches[param] = url.slice(i).map(decodeURIComponent).join('/');
break;
}

return matches;
};

export function LocationProvider(props) {
const [url, route] = useReducer(UPDATE, location.pathname + location.search);

const value = useMemo(() => {
const u = new URL(url, location.origin);
const path = u.pathname.replace(/(.)\/$/g, '$1');
// @ts-ignore-next
return { url, path, query: Object.fromEntries(u.searchParams), route };
}, [url]);

useEffect(() => {
addEventListener('click', route);
addEventListener('popstate', route);

return () => {
removeEventListener('click', route);
removeEventListener('popstate', route);
};
});
return h(Loc.ctx.Provider, { value }, props.children);

// @ts-ignore
return h(LocationProvider.ctx.Provider, { value }, props.children);
}

export function Router(props) {
const [, update] = useReducer(c => c + 1, 0);

const loc = useLoc();

const { url, path, query } = loc;

const cur = useRef(loc);
const prev = useRef();
const curChildren = useRef();
const prevChildren = useRef();
const pending = useRef();

if (url !== cur.current.url) {
pending.current = null;
prev.current = cur.current;
prevChildren.current = curChildren.current;
cur.current = loc;
}

this.componentDidCatch = err => {
if (err && err.then) pending.current = err;
};

useEffect(() => {
let p = pending.current;
const commit = () => {
Expand All @@ -58,20 +96,37 @@ export function Router(props) {
prev.current = prevChildren.current = null;
update(0);
};

if (p) {
if (props.onLoadStart) props.onLoadStart(url);
p.then(commit);
} else commit();
}, [url]);
const children = [].concat(...props.children);
let a = children.filter(c => c.props.path === path);
if (a.length == 0) a = children.filter(c => c.props.default);
curChildren.current = a.map((p, i) => cloneElement(p, { path, query }));
return curChildren.current.concat(prevChildren.current || []);

let p, d, m;
[].concat(props.children || []).some(vnode => {
const matches = exec(path, vnode.props.path, (m = { path, query }));
if (matches) {
return p = (
<RouteContext.Provider value={{ ...matches }}>
{cloneElement(vnode, { ...m, ...matches })}
</RouteContext.Provider>
);
} else {
if (vnode.props.default) d = cloneElement(vnode, m);
return undefined;
}
});

return [(curChildren.current = p || d), prevChildren.current];
}

Loc.Router = Router;
Router.Provider = LocationProvider;

LocationProvider.ctx = createContext(/** @type {{ url: string, path: string, query: object, route }} */ ({}));

Loc.ctx = createContext(/** @type {{ url: string, path: string, query: object, route }} */ ({}));
const RouteContext = createContext({});

export const useLoc = () => useContext(Loc.ctx);
export const useLoc = () => useContext(LocationProvider.ctx);
export const useLocation = useLoc;
export const useRoute = () => useContext(RouteContext);
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5627,7 +5627,7 @@ jest-worker@^26.2.1, jest-worker@^26.6.2:
merge-stream "^2.0.0"
supports-color "^7.0.0"

jest@^26.1.0:
jest@26.6.3, jest@^26.1.0:
version "26.6.3"
resolved "https://registry.yarnpkg.com/jest/-/jest-26.6.3.tgz#40e8fdbe48f00dfa1f0ce8121ca74b88ac9148ef"
integrity sha512-lGS5PXGAzR4RF7V5+XObhqz2KZIDUA1yD0DG6pBVmy10eh0ZIXQImRuzocsI/N2XZ1GrLFwTS27In2i2jlpq1Q==
Expand Down