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 4 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
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.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"arrowParens": "avoid"
},
"lint-staged": {
"packages/{src,test}/**/*.js": [
"packages/**/{src,test}/**/*.js": [
marvinhagemeister marked this conversation as resolved.
Show resolved Hide resolved
"eslint --fix",
"prettier --write"
],
Expand Down
40 changes: 32 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;
};

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,17 @@ 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 {
return vnode.props.default ? d = cloneElement(vnode, m) : 0, undefined
}
});

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

Router.Provider = LocationProvider;
Expand Down
1 change: 0 additions & 1 deletion packages/sw-plugin/example/public/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import swURL from 'sw:./sw.js';

console.log(swURL);
navigator.serviceWorker.register(swURL);
JoviDeCroock marked this conversation as resolved.
Show resolved Hide resolved
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
69 changes: 58 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,29 @@ 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 {
return vnode.props.default ? d = cloneElement(vnode, m) : 0, undefined
JoviDeCroock marked this conversation as resolved.
Show resolved Hide resolved
}
});

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;