Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister committed Sep 3, 2021
1 parent 9a814a9 commit 5b82c8e
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 3 deletions.
1 change: 1 addition & 0 deletions packages/preact-iso/router.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ interface LocationHook {
url: string;
path: string;
query: Record<string, string>;
params: Record<string, string>;
route: (url: string) => void;
}
export const useLocation: () => LocationHook;
Expand Down
6 changes: 3 additions & 3 deletions packages/preact-iso/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function LocationProvider(props) {
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, wasPush };
return { url, path, query: Object.fromEntries(u.searchParams), route, wasPush, params: {} };
}, [url]);

useLayoutEffect(() => {
Expand All @@ -88,7 +88,7 @@ const RESOLVED = Promise.resolve();
export function Router(props) {
const [, update] = useReducer(c => c + 1, 0);

const { url, path, query, wasPush } = useLocation();
const { url, path, query, wasPush, params } = useLocation();

// Monotonic counter used to check if an un-suspending route is still the current route:
const count = useRef(0);
Expand All @@ -114,7 +114,7 @@ export function Router(props) {

let p, d, m;
toChildArray(props.children).some(vnode => {
const matches = exec(path, vnode.props.path, (m = { path, query, params: {} }));
const matches = exec(path, vnode.props.path, (m = { path, query, params }));
if (matches) return (p = cloneElement(vnode, m));
if (vnode.props.default) d = cloneElement(vnode, m);
});
Expand Down
40 changes: 40 additions & 0 deletions packages/preact-iso/test/router.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -436,4 +436,44 @@ describe('Router', () => {

pushState.mockRestore();
});

it.only('should append params in nested routes', async () => {
const pushState = jest.spyOn(history, 'pushState');
const Route = jest.fn(() => html`<a href="/foo#foo">foo</a>`);

let params;

const Inner = () => html`
<${Router}>
<${Route}
path="/foo/bar/bob"
component=${() => {
console.log(useLocation());
params = useLocation().params;
return null;
}}
/>
<//>
`;

render(
html`
<${LocationProvider}>
<${Router}>
<${Route} path="/foo/:id/*" component=${Inner} />
<//>
<a href="/foo/bar/bob"></a>
<//>
`,
scratch
);

scratch.querySelector('a[href="/foo/bar/bob"]').click();
await sleep(20);
expect(Route).toHaveBeenCalledTimes(1);
expect(params).toMatchObject({ url: '/foo#foo', path: '/foo' });
expect(pushState).toHaveBeenCalled();

pushState.mockRestore();
});
});

0 comments on commit 5b82c8e

Please sign in to comment.