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 9 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.
9 changes: 6 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ on:
branches:
- main
paths:
- packages/wmr/**
- packages/{wmr,preact-iso}/**
pull_request:
paths:
- packages/wmr/**
- packages/{wmr,preact-iso}/**

jobs:
build:
Expand All @@ -28,8 +28,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
6 changes: 4 additions & 2 deletions packages/preact-iso/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,20 +85,22 @@ 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.

**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
11 changes: 11 additions & 0 deletions packages/preact-iso/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@
"module": "./index.js",
"types": "./index.d.ts",
"type": "module",
"scripts": {
"test": "jest"
},
"babel": {
"plugins": [
"@babel/plugin-transform-modules-commonjs"
]
},
"exports": {
".": "./index.js",
"./router": "./router.js",
Expand All @@ -21,6 +29,9 @@
},
"license": "MIT",
"devDependencies": {
"@babel/plugin-transform-modules-commonjs": "7.12.13",
"babel-jest": "^26.1.0",
"jest": "26.6.3",
"preact": "^10.5.7",
"preact-render-to-string": "^5.1.12"
},
Expand Down
41 changes: 33 additions & 8 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('/');
marvinhagemeister marked this conversation as resolved.
Show resolved Hide resolved
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,15 +104,18 @@ export function Router(props) {
} 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 }));
let p, d, m;
[].concat(props.children || []).some(vnode => {
const matches = exec(path, vnode.props.path, m = { path, query });
if (matches) {
return p = cloneElement(vnode, { ...m, ...matches })
} else {
if (vnode.props.default) d = cloneElement(vnode, m);
return undefined;
}
});
JoviDeCroock marked this conversation as resolved.
Show resolved Hide resolved

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

Router.Provider = LocationProvider;
Expand Down
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
70 changes: 59 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++) {
marvinhagemeister marked this conversation as resolved.
Show resolved Hide resolved
let [, m, param, flag] = (route[i] || '').match(/^(\:?)(.*?)([+*?]?)$/);
val = url[i];
// segment match:
if (!m && param==val) continue;
JoviDeCroock marked this conversation as resolved.
Show resolved Hide resolved
// 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,30 @@ 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 = cloneElement(vnode, { ...m, ...matches })
} else {
if (vnode.props.default) d = cloneElement(vnode, m);
return undefined;
}
});

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

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

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

export const useLoc = () => useContext(Loc.ctx);
export const useLoc = () => useContext(LocationProvider.ctx);
export const useLocation = useLoc;
4 changes: 2 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@
"@babel/helper-plugin-utils" "^7.12.13"
babel-plugin-dynamic-import-node "^2.3.3"

"@babel/plugin-transform-modules-commonjs@^7.10.4", "@babel/plugin-transform-modules-commonjs@^7.12.13":
"@babel/plugin-transform-modules-commonjs@7.12.13", "@babel/plugin-transform-modules-commonjs@^7.10.4", "@babel/plugin-transform-modules-commonjs@^7.12.13":
version "7.12.13"
resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.12.13.tgz#5043b870a784a8421fa1fd9136a24f294da13e50"
integrity sha512-OGQoeVXVi1259HjuoDnsQMlMkT9UkZT9TpXAsqWplS/M0N1g3TJAn/ByOCeQu7mfjc5WpSsRU+jV1Hd89ts0kQ==
Expand Down 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