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

feat: Adds scope prop to LocationProvider, limiting link intercepts #42

Merged
merged 6 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ export async function prerender(data) {

A context provider that provides the current location to its children. This is required for the router to function.

Props:

- `limit?: string | RegExp` - Sets a limit on the paths that the router will handle (intercept). If a path does not match the limit, either by starting with the provided string or matching the RegExp, the router will ignore it and default browser navigation will apply.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name limit bothers me a bit, I would prefer something like include/exclude personally

Copy link
Member Author

@rschristian rschristian Oct 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, "include" means something quite different though. To include something is to have it be part of a whole; this limits the whole to only the matching value.

There's probably a better name somewhere (haven't yet found/thought of one myself), though I think "include" would give a very different idea than what we're going for. Just my initial thoughts though.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe scope? I'm not dead-set against include, can do it, though not my fav.


Typically, you would wrap your entire app in this provider:

```js
Expand Down
5 changes: 4 additions & 1 deletion src/router.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { AnyComponent, FunctionComponent, VNode } from 'preact';

export const LocationProvider: FunctionComponent;
export function LocationProvider(props: {
limit?: string | RegExp;
children?: VNode[];
}): VNode;

type NestedArray<T> = Array<T | NestedArray<T>>;

Expand Down
14 changes: 10 additions & 4 deletions src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { useContext, useMemo, useReducer, useLayoutEffect, useRef } from 'preact
* @typedef {import('./internal.d.ts').VNode} VNode
*/

let push;
let push, limit;
const UPDATE = (state, url) => {
push = undefined;
if (url && url.type === 'click') {
Expand All @@ -16,12 +16,17 @@ const UPDATE = (state, url) => {
return state;
}

const link = url.target.closest('a[href]');
const link = url.target.closest('a[href]'),
href = link.getAttribute('href');
if (
!link ||
link.origin != location.origin ||
/^#/.test(link.getAttribute('href')) ||
!/^(_?self)?$/i.test(link.target)
/^#/.test(href) ||
!/^(_?self)?$/i.test(link.target) ||
limit && (typeof limit == 'string'
? !href.startsWith(limit)
: !limit.test(href)
)
) {
return state;
}
Expand Down Expand Up @@ -72,6 +77,7 @@ export const exec = (url, route, matches) => {

export function LocationProvider(props) {
const [url, route] = useReducer(UPDATE, props.url || location.pathname + location.search);
if (props.limit) limit = props.limit;
const wasPush = push === true;

const value = useMemo(() => {
Expand Down
147 changes: 146 additions & 1 deletion test/router.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,6 @@ describe('Router', () => {
const shouldIntercept = [null, '', '_self', 'self', '_SELF'];
const shouldNavigate = ['_top', '_parent', '_blank', 'custom', '_BLANK'];

// prevent actual navigations (not implemented in JSDOM)
const clickHandler = sinon.fake(e => e.preventDefault());

const Route = sinon.fake(
Expand Down Expand Up @@ -583,6 +582,152 @@ describe('Router', () => {
}
});

describe('intercepted VS external links with `limit`', () => {
const shouldIntercept = ['/app', '/app/deeper'];
const shouldNavigate = ['/site', '/site/deeper'];

const clickHandler = sinon.fake(e => e.preventDefault());

const Route = sinon.fake(
() => (
<div>
<a href="/app">Internal Link</a>
<a href="/app/deeper">Internal Deeper Link</a>
<a href="/site">External Link</a>
<a href="/site/deeper">External Deeper Link</a>
</div>
)
);

let pushState;

before(() => {
pushState = sinon.spy(history, 'pushState');
addEventListener('click', clickHandler);
});

after(() => {
pushState.restore();
removeEventListener('click', clickHandler);
});

beforeEach(async () => {
Route.resetHistory();
clickHandler.resetHistory();
pushState.resetHistory();
});

it('should intercept clicks on links matching the `limit` props (string)', async () => {
render(
<LocationProvider limit="/app">
<Router>
<Route default />
</Router>
<ShallowLocation />
</LocationProvider>,
scratch
);
Route.resetHistory();
await sleep(10);

for (const url of shouldIntercept) {
const el = scratch.querySelector(`a[href="${url}"]`);
el.click();
await sleep(1);
expect(loc).to.deep.include({ url });
expect(Route).to.have.been.calledOnce;
expect(pushState).to.have.been.calledWith(null, '', url);
expect(clickHandler).to.have.been.called;

Route.resetHistory();
pushState.resetHistory();
clickHandler.resetHistory();
}
});

it('should allow default browser navigation for links not matching the `limit` props (string)', async () => {
render(
<LocationProvider limit="app">
<Router>
<Route default />
</Router>
<ShallowLocation />
</LocationProvider>,
scratch
);
Route.resetHistory();
await sleep(10);

for (const url of shouldNavigate) {
const el = scratch.querySelector(`a[href="${url}"]`);
el.click();
await sleep(1);
expect(Route).not.to.have.been.called;
expect(pushState).not.to.have.been.called;
expect(clickHandler).to.have.been.called;

Route.resetHistory();
pushState.resetHistory();
clickHandler.resetHistory();
}
});

it('should intercept clicks on links matching the `limit` props (regex)', async () => {
render(
<LocationProvider limit={/^\/app/}>
<Router>
<Route default />
</Router>
<ShallowLocation />
</LocationProvider>,
scratch
);
Route.resetHistory();
await sleep(10);

for (const url of shouldIntercept) {
const el = scratch.querySelector(`a[href="${url}"]`);
el.click();
await sleep(1);
expect(loc).to.deep.include({ url });
expect(Route).to.have.been.calledOnce;
expect(pushState).to.have.been.calledWith(null, '', url);
expect(clickHandler).to.have.been.called;

Route.resetHistory();
pushState.resetHistory();
clickHandler.resetHistory();
}
});

it('should allow default browser navigation for links not matching the `limit` props (regex)', async () => {
render(
<LocationProvider limit={/^\/app/}>
<Router>
<Route default />
</Router>
<ShallowLocation />
</LocationProvider>,
scratch
);
Route.resetHistory();
await sleep(10);

for (const url of shouldNavigate) {
const el = scratch.querySelector(`a[href="${url}"]`);
el.click();
await sleep(1);
expect(Route).not.to.have.been.called;
expect(pushState).not.to.have.been.called;
expect(clickHandler).to.have.been.called;

Route.resetHistory();
pushState.resetHistory();
clickHandler.resetHistory();
}
});
});

it('should scroll to top when navigating forward', async () => {
const scrollTo = sinon.spy(window, 'scrollTo');

Expand Down