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

fix: Strengthen route typings #9366

Merged
merged 16 commits into from Sep 30, 2022
Merged
Show file tree
Hide file tree
Changes from 10 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
1 change: 1 addition & 0 deletions contributors.yml
Expand Up @@ -36,6 +36,7 @@
- goldins
- gowthamvbhat
- GraxMonzo
- GuptaSiddhant
- haivuw
- hernanif1
- hongji00
Expand Down
3 changes: 3 additions & 0 deletions packages/react-router-dom/index.tsx
Expand Up @@ -78,8 +78,10 @@ export type {
DataRouteObject,
Fetcher,
Hash,
IndexRouteObject,
IndexRouteProps,
JsonFunction,
LayoutRouteObject,
LayoutRouteProps,
LoaderFunction,
LoaderFunctionArgs,
Expand All @@ -97,6 +99,7 @@ export type {
PathMatch,
Pathname,
PathPattern,
PathRouteObject,
PathRouteProps,
RedirectFunction,
RelativeRoutingType,
Expand Down
3 changes: 3 additions & 0 deletions packages/react-router-native/index.tsx
Expand Up @@ -27,8 +27,10 @@ export type {
DataRouteObject,
Fetcher,
Hash,
IndexRouteObject,
IndexRouteProps,
JsonFunction,
LayoutRouteObject,
LayoutRouteProps,
LoaderFunction,
LoaderFunctionArgs,
Expand All @@ -46,6 +48,7 @@ export type {
PathMatch,
Pathname,
PathPattern,
PathRouteObject,
PathRouteProps,
RedirectFunction,
RelativeRoutingType,
Expand Down
24 changes: 24 additions & 0 deletions packages/react-router/__tests__/createRoutesFromChildren-test.tsx
Expand Up @@ -196,4 +196,28 @@ describe("creating routes from JSX", () => {
]
`);
});

it("throws when the index route has a path", () => {
expect(() => {
createRoutesFromChildren(
<Route path="/">
{/* @ts-expect-error */}
<Route index path="foo" />
</Route>
);
}).toThrow("An index route cannot have a path or child routes.");
});

it("throws when the index route has children", () => {
expect(() => {
createRoutesFromChildren(
<Route path="/">
{/* @ts-expect-error */}
<Route index>
<Route path="users" />
</Route>
</Route>
);
}).toThrow("An index route cannot have a path or child routes.");
});
});
31 changes: 29 additions & 2 deletions packages/react-router/__tests__/index-routes-test.tsx
Expand Up @@ -8,9 +8,10 @@ describe("index route matching", () => {
{
path: "/users",
children: [
// This config is not valid because index routes cannot have children
// @ts-expect-error
{
index: true,
// This config is not valid because index routes cannot have children
children: [{ path: "not-valid" }],
},
{ path: ":id" },
Expand All @@ -19,6 +20,32 @@ describe("index route matching", () => {
],
"/users/mj"
);
}).toThrow("must not have child routes");
}).toThrowErrorMatchingInlineSnapshot(
`"Index routes must not have a path or child routes. Please update the index route at the path \\"/users/\\"."`
);
});

it("throws when the index route has a path", () => {
expect(() => {
matchRoutes(
[
{
path: "/users",
children: [
// This config is not valid because index routes cannot have paths
// @ts-expect-error
{
index: true,
path: "not-valid",
},
{ path: ":id" },
],
},
],
"/users/mj"
);
}).toThrowErrorMatchingInlineSnapshot(
`"Index routes must not have a path or child routes. Please update the index route at the path \\"/users/not-valid\\"."`
);
});
});
23 changes: 4 additions & 19 deletions packages/react-router/__tests__/matchRoutes-test.tsx
@@ -1,3 +1,4 @@
import { AgnosticRouteObject } from "@remix-run/router";
import * as React from "react";
import type { RouteObject } from "react-router";
import { matchRoutes } from "react-router";
Expand Down Expand Up @@ -26,15 +27,6 @@ describe("matchRoutes", () => {
element: <h1>Users</h1>,
children: [{ index: true, element: <h1>Index</h1> }, userProfileRoute],
};
let indexWithPathRoute: RouteObject = {
path: "/withpath",
index: true,
};
let layoutRouteIndex: RouteObject = {
path: "/layout",
index: true,
element: <h1>Layout</h1>,
};
let layoutRoute: RouteObject = {
path: "/layout",
children: [
Expand All @@ -43,8 +35,7 @@ describe("matchRoutes", () => {
{ path: "*", element: <h1>Not Found</h1> },
],
};

let routes = [
let routes: RouteObject[] = [
{ path: "/", element: <h1>Root Layout</h1> },
{
path: "/home",
Expand All @@ -54,9 +45,7 @@ describe("matchRoutes", () => {
{ path: "*", element: <h1>Not Found</h1> },
],
},
indexWithPathRoute,
layoutRoute,
layoutRouteIndex,
usersRoute,
{ path: "*", element: <h1>Not Found</h1> },
];
Expand All @@ -66,12 +55,8 @@ describe("matchRoutes", () => {
expect(pickPaths(routes, "/hometypo")).toEqual(["*"]);
});

it("matches index routes with path correctly", () => {
expect(pickPaths(routes, "/withpath")).toEqual(["/withpath"]);
});
brophdawg11 marked this conversation as resolved.
Show resolved Hide resolved

it("matches index routes with path over layout", () => {
expect(matchRoutes(routes, "/layout")[0].route.index).toBe(true);
it("matches layout routes", () => {
expect(matchRoutes(routes, "/layout")?.length).toBe(1);
expect(pickPaths(routes, "/layout")).toEqual(["/layout"]);
});

Expand Down
6 changes: 6 additions & 0 deletions packages/react-router/index.ts
Expand Up @@ -64,8 +64,11 @@ import {
import type {
DataRouteMatch,
DataRouteObject,
IndexRouteObject,
LayoutRouteObject,
Navigator,
NavigateOptions,
PathRouteObject,
RouteMatch,
RouteObject,
RelativeRoutingType,
Expand Down Expand Up @@ -116,8 +119,10 @@ export type {
DataRouteObject,
Fetcher,
Hash,
IndexRouteObject,
IndexRouteProps,
JsonFunction,
LayoutRouteObject,
LayoutRouteProps,
LoaderFunction,
LoaderFunctionArgs,
Expand All @@ -135,6 +140,7 @@ export type {
PathMatch,
Pathname,
PathPattern,
PathRouteObject,
PathRouteProps,
RedirectFunction,
RelativeRoutingType,
Expand Down
56 changes: 22 additions & 34 deletions packages/react-router/lib/components.tsx
Expand Up @@ -26,6 +26,9 @@ import type {
RouteObject,
Navigator,
RelativeRoutingType,
PathRouteObject,
LayoutRouteObject,
IndexRouteObject,
} from "./context";
import {
LocationContext,
Expand Down Expand Up @@ -220,49 +223,28 @@ export function Outlet(props: OutletProps): React.ReactElement | null {
return useOutlet(props.context);
}

interface DataRouteProps {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Got rid of the duplication here - <Route> props are now just RouteObject equivalents that expect ReactNode children instead of ReactElement children

id?: RouteObject["id"];
loader?: RouteObject["loader"];
action?: RouteObject["action"];
errorElement?: RouteObject["errorElement"];
shouldRevalidate?: RouteObject["shouldRevalidate"];
handle?: RouteObject["handle"];
}

export interface RouteProps extends DataRouteProps {
caseSensitive?: boolean;
children?: React.ReactNode;
element?: React.ReactNode | null;
index?: boolean;
path?: string;
}
// Create JSX-specific types from the RouteObjects, essentially changing
// ReactElement to ReactNode
export type PathRouteProps = Omit<PathRouteObject, "children"> & {
children?: React.ReactNode | null;
};

export interface PathRouteProps extends DataRouteProps {
caseSensitive?: boolean;
children?: React.ReactNode;
element?: React.ReactNode | null;
index?: false;
path: string;
}
export type LayoutRouteProps = Omit<LayoutRouteObject, "children"> & {
children?: React.ReactNode | null;
};

export interface LayoutRouteProps extends DataRouteProps {
children?: React.ReactNode;
element?: React.ReactNode | null;
}
export type IndexRouteProps = Omit<IndexRouteObject, "children"> & {
children?: undefined;
};

export interface IndexRouteProps extends DataRouteProps {
element?: React.ReactNode | null;
index: true;
}
export type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;

/**
* Declares an element that should be rendered at a certain URL path.
*
* @see https://reactrouter.com/docs/en/v6/components/route
*/
export function Route(
_props: PathRouteProps | LayoutRouteProps | IndexRouteProps
): React.ReactElement | null {
export function Route(_props: RouteProps): React.ReactElement | null {
invariant(
false,
`A <Route> is only ever to be used as the child of <Routes> element, ` +
Expand Down Expand Up @@ -569,6 +551,12 @@ export function createRoutesFromChildren(
}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`
);

invariant(
!element.props.index ||
(element.props.path == null && !element.props.children),
"An index route cannot have a path or child routes."
);

let treePath = [...parentPath, index];
let route: RouteObject = {
id: element.props.id || treePath.join("-"),
Expand Down
27 changes: 22 additions & 5 deletions packages/react-router/lib/context.ts
Expand Up @@ -6,23 +6,40 @@ import type {
Router,
StaticHandlerContext,
To,
AgnosticRouteObject,
AgnosticRouteMatch,
AgnosticIndexRouteObject,
AgnosticLayoutRouteObject,
AgnosticPathRouteObject,
} from "@remix-run/router";
import type { Action as NavigationType } from "@remix-run/router";

// Create react-specific types from the agnostic types in @remix-run/router to
// export from react-router
export interface RouteObject extends AgnosticRouteObject {
export type IndexRouteObject = Omit<AgnosticIndexRouteObject, "children"> & {
children?: undefined;
Copy link

@lilonghe lilonghe Nov 22, 2022

Choose a reason for hiding this comment

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

why children?: undefined;, maybe we can remove this line?

element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
};
export type PathRouteObject = Omit<AgnosticPathRouteObject, "children"> & {
children?: RouteObject[];
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
}
};
export type LayoutRouteObject = Omit<AgnosticLayoutRouteObject, "children"> & {
children?: RouteObject[];
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
};

export interface DataRouteObject extends RouteObject {
export type RouteObject =
| IndexRouteObject
| PathRouteObject
| LayoutRouteObject;

export type DataRouteObject = RouteObject & {
children?: DataRouteObject[];
id: string;
}
};

export interface RouteMatch<
ParamKey extends string = string,
Expand Down
40 changes: 39 additions & 1 deletion packages/router/__tests__/router-test.ts
Expand Up @@ -28,7 +28,7 @@ import {
} from "../index";

// Private API
import type { TrackedPromise } from "../utils";
import type { AgnosticRouteObject, TrackedPromise } from "../utils";
import { AbortedDeferredError } from "../utils";

///////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -1002,6 +1002,44 @@ describe("a router", () => {
);
});

it("throws if it finds invalid route objects", async () => {
let routes: AgnosticRouteObject[] = [
// @ts-expect-error
{
path: "path",
index: true,
},
];
expect(() =>
createRouter({
routes,
history: createMemoryHistory(),
})
).toThrowErrorMatchingInlineSnapshot(
`"Cannot specify paths or children on an index route"`
);

routes = [
// @ts-expect-error
{
index: true,
children: [
{
path: "nope",
},
],
},
];
expect(() =>
createRouter({
routes,
history: createMemoryHistory(),
})
).toThrowErrorMatchingInlineSnapshot(
`"Cannot specify paths or children on an index route"`
);
});

it("supports a basename prop for route matching", async () => {
let history = createMemoryHistory({
initialEntries: ["/base/name/path"],
Expand Down