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

Added support for regular expressions in paths #450

Merged
merged 7 commits into from
May 30, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,12 @@ useRoute("/app*");
// optional wildcards, matches "/orders", "/orders/"
// and "/orders/completed/list"
useRoute("/orders/*?");

// regex for matching complex patterns,
// matches "/hello:123"
useRoute(/^[/]([a-z]+):([0-9]+)[/]?$/);
// and with named capture groups
useRoute(/^[/](?<word>[a-z]+):(?<num>[0-9]+)[/]?$/);
```

The second item in the pair `params` is an object with parameters or null if there was no match. For wildcard segments the parameter name is `"*"`:
Expand Down Expand Up @@ -312,11 +318,29 @@ const User = () => {
const params = useParams();

params.id; // "1"

// alternatively, use the index to access the prop
params[0]; // "1"
};

<Route path="/user/:id" component={User}> />
```

It is the same for regex paths. Capture groups can be accessed by their index, or if there is a named capture group, that can be used instead.

```js
import { Route, useParams } from "wouter";

const User = () => {
const params = useParams();

params.id; // "1"
params[0]; // "1"
};

<Route path={/^[/]user[/](?<id>[0-9]+)[/]?$/} component={User}> />
```

### `useSearch`: query strings

Use this hook to get the current search (query) string value. It will cause your component to re-render only when the string itself and not the full location updates. The search string returned **does not** contain a `?` character.
Expand Down Expand Up @@ -421,6 +445,11 @@ If you call `useLocation()` inside the last route, it will return `/orders` and
</Route>
```

**Note:** The `nest` prop does not alter the regex passed into regex paths.
Instead, the `nest` prop will only determine if nested routes will match against the rest of path or the same path.
To make a strict path regex, use a regex pattern like `/^[/](your pattern)[/]?$/` (this matches an optional end slash and the end of the string).
To make a nestable regex, use a regex pattern like `/^[/](your pattern)(?=$|[/])/` (this matches either the end of the string or a slash for future segments).

### `<Link href={path} />`

Link component renders an `<a />` element that, when clicked, performs a navigation.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"packages/wouter-preact"
],
"scripts": {
"fix:p": "prettier --write './**/*.(js|ts){x,}'",
"fix:p": "prettier --write \"./**/*.(js|ts){x,}\"",
"test": "vitest",
"size": "size-limit",
"build": "npm run build -ws",
Expand Down
38 changes: 30 additions & 8 deletions packages/wouter-preact/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {

import {
Path,
PathPattern,
BaseLocationHook,
HookReturnValue,
HookNavigationOptions,
Expand All @@ -29,11 +30,16 @@ export * from "./router.js";

import { RouteParams } from "regexparam";

export type StringRouteParams<T extends string> = RouteParams<T> & {
[param: number]: string | undefined;
};
export type RegexRouteParams = { [key: string | number]: string | undefined };

/**
* Route patterns and parameters
*/
export interface DefaultParams {
readonly [paramName: string]: string | undefined;
readonly [paramName: string | number]: string | undefined;
}

export type Params<T extends DefaultParams = DefaultParams> = T;
Expand All @@ -57,23 +63,33 @@ export interface RouteComponentProps<T extends DefaultParams = DefaultParams> {

export interface RouteProps<
T extends DefaultParams | undefined = undefined,
RoutePath extends Path = Path
RoutePath extends PathPattern = PathPattern
> {
children?:
| ((
params: T extends DefaultParams ? T : RouteParams<RoutePath>
params: T extends DefaultParams
? T
: RoutePath extends string
? StringRouteParams<RoutePath>
: RegexRouteParams
) => ComponentChildren)
| ComponentChildren;
path?: RoutePath;
component?: ComponentType<
RouteComponentProps<T extends DefaultParams ? T : RouteParams<RoutePath>>
RouteComponentProps<
T extends DefaultParams
? T
: RoutePath extends string
? StringRouteParams<RoutePath>
: RegexRouteParams
>
>;
nest?: boolean;
}

export function Route<
T extends DefaultParams | undefined = undefined,
RoutePath extends Path = Path
RoutePath extends PathPattern = PathPattern
>(props: RouteProps<T, RoutePath>): ReturnType<FunctionComponent>;

/*
Expand Down Expand Up @@ -143,10 +159,16 @@ export function useRouter(): RouterObject;

export function useRoute<
T extends DefaultParams | undefined = undefined,
RoutePath extends Path = Path
RoutePath extends PathPattern = PathPattern
>(
pattern: RoutePath
): Match<T extends DefaultParams ? T : RouteParams<RoutePath>>;
): Match<
T extends DefaultParams
? T
: RoutePath extends string
? StringRouteParams<RoutePath>
: RegexRouteParams
>;

export function useLocation<
H extends BaseLocationHook = BrowserLocationHook
Expand All @@ -157,7 +179,7 @@ export function useSearch<
>(): ReturnType<H>;

export function useParams<T = undefined>(): T extends string
? RouteParams<T>
? StringRouteParams<T>
: T extends undefined
? DefaultParams
: T;
Expand Down
2 changes: 2 additions & 0 deletions packages/wouter-preact/types/location-hook.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

export type Path = string;

export type PathPattern = string | RegExp;

export type SearchString = string;

// the base useLocation hook type. Any custom hook (including the
Expand Down
5 changes: 4 additions & 1 deletion packages/wouter-preact/types/router.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import {
BaseSearchHook,
} from "./location-hook.js";

export type Parser = (route: Path) => { pattern: RegExp; keys: string[] };
export type Parser = (
route: Path,
loose?: boolean
) => { pattern: RegExp; keys: string[] };

export type HrefsFormatter = (href: string, router: RouterObject) => string;

Expand Down
36 changes: 30 additions & 6 deletions packages/wouter/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,21 +79,45 @@ export const useSearch = () => {
};

const matchRoute = (parser, route, path, loose) => {
// if the input is a regexp, skip parsing
const { pattern, keys } =
route instanceof RegExp
? { keys: false, pattern: route }
: parser(route || "*", loose);

// array destructuring loses keys, so this is done in two steps
const result = pattern.exec(path) || [];

// when parser is in "loose" mode, `$base` is equal to the
// first part of the route that matches the pattern
// (e.g. for pattern `/a/:b` and path `/a/1/2/3` the `$base` is `a/1`)
// we use this for route nesting
const { pattern, keys } = parser(route || "*", loose);
const [$base, ...matches] = pattern.exec(path) || [];
const [$base, ...matches] = result;

return $base !== undefined
? [
true,

// an object with parameters matched, e.g. { foo: "bar" } for "/:foo"
// we "zip" two arrays here to construct the object
// ["foo"], ["bar"] → { foo: "bar" }
Object.fromEntries(keys.map((key, i) => [key, matches[i]])),
(() => {
// for regex paths, `keys` will always be false

// an object with parameters matched, e.g. { foo: "bar" } for "/:foo"
// we "zip" two arrays here to construct the object
// ["foo"], ["bar"] → { foo: "bar" }
const groups =
keys !== false
? Object.fromEntries(keys.map((key, i) => [key, matches[i]]))
: result.groups;

// convert the array to an instance of object
// this makes it easier to integrate with the existing param implementation
let obj = { ...matches };

// merge named capture groups with matches array
groups && Object.assign(obj, groups);

return obj;
})(),

// the third value if only present when parser is in "loose" mode,
// so that we can extract the base path for nested routes
Expand Down
2 changes: 1 addition & 1 deletion packages/wouter/test/parser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ it("allows to change the behaviour of route matching", () => {

expect(result.current).toStrictEqual([
true,
{ pages: undefined, rest: "10/bio", 0: "home" },
{ 0: "home", 1: undefined, 2: "10/bio", pages: undefined, rest: "10/bio" },
]);
});
4 changes: 2 additions & 2 deletions packages/wouter/test/route.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ describe("`path` prop", () => {
assertType(<Route />);
});

it("should be a string", () => {
it("should be a string or RegExp", () => {
let a: ComponentProps<typeof Route>["path"];
expectTypeOf(a).toMatchTypeOf<string | undefined>();
expectTypeOf(a).toMatchTypeOf<string | RegExp | undefined>();
});
});

Expand Down
44 changes: 44 additions & 0 deletions packages/wouter/test/route.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,47 @@ it("supports `base` routers with relative path", () => {

unmount();
});

it("supports `path` prop with regex", () => {
const result = testRouteRender(
"/foo",
<Route path={/[/]foo/}>
<h1>Hello!</h1>
</Route>
);

expect(result.findByType("h1").props.children).toBe("Hello!");
});

it("supports regex path named params", () => {
const result = testRouteRender(
"/users/alex",
<Route path={/[/]users[/](?<name>[a-z]+)/}>
{(params) => <h1>{params.name}</h1>}
</Route>
);

expect(result.findByType("h1").props.children).toBe("alex");
});

it("supports regex path anonymous params", () => {
const result = testRouteRender(
"/users/alex",
<Route path={/[/]users[/]([a-z]+)/}>
{(params) => <h1>{params[0]}</h1>}
</Route>
);

expect(result.findByType("h1").props.children).toBe("alex");
});

it("rejects when a path does not match the regex", () => {
const result = testRouteRender(
"/users/1234",
<Route path={/[/]users[/](?<name>[a-z]+)/}>
{(params) => <h1>{params.name}</h1>}
</Route>
);

expect(() => result.findByType("h1")).toThrow();
});
20 changes: 19 additions & 1 deletion packages/wouter/test/router.test-d.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { ComponentProps } from "react";
import { it, expectTypeOf } from "vitest";
import { Router, Route, BaseLocationHook, useRouter } from "wouter";
import {
Router,
Route,
BaseLocationHook,
useRouter,
Parser,
Path,
} from "wouter";

it("should have at least one child", () => {
// @ts-expect-error
Expand Down Expand Up @@ -64,6 +71,17 @@ it("accepts `hrefs` function for transforming href strings", () => {
</Router>;
});

it("accepts `parser` function for generating regular expressions", () => {
const parser: Parser = (path: Path, loose?: boolean) => {
return {
pattern: new RegExp(`^${path}${loose === true ? "(?=$|[/])" : "[/]$"}`),
keys: [],
};
};

<Router parser={parser}>this is a valid router</Router>;
});

it("does not accept other props", () => {
const router = useRouter();

Expand Down
8 changes: 7 additions & 1 deletion packages/wouter/test/use-params.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@ it("returns an object with arbitrary parameters", () => {

expectTypeOf(params).toBeObject();
expectTypeOf(params.any).toEqualTypeOf<string | undefined>();
expectTypeOf(params[0]).toEqualTypeOf<string | undefined>();
});

it("can infer the type of parameters from the route path", () => {
const params = useParams<"/app/users/:name?/:id">();

expectTypeOf(params).toMatchTypeOf<{ id: string; name?: string }>();
expectTypeOf(params).toMatchTypeOf<{
0?: string;
1?: string;
id: string;
name?: string;
}>();
});

it("can accept the custom type of parameters as a generic argument", () => {
Expand Down
Loading
Loading