clear-react-router 2.4.1 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -127,7 +127,9 @@ Component for client-side navigation with prefetch support, active state detecti
127
127
 
128
128
  | Prop | Type | Default | Description |
129
129
  |------|------|---------|-------------|
130
- | `to` | `string` | required | Target path |
130
+ | `to` | `string` | required (unless `path` is set) | Target path as a raw URL. Mutually exclusive with `path` |
131
+ | `path` | `string` (route pattern) | required (unless `to` is set) | Route pattern with `:segments`, e.g. `/product/:productId`. Segments are filled from `params` |
132
+ | `params` | `Record<string, string \| number>` | required if `path` has `:segments` | Values for the pattern segments (URL-encoded). A missing param throws at runtime |
131
133
  | `search` | `string \| Record<string, string \| number \| boolean \| null \| undefined> \| undefined` | `undefined` | Query string or object appended to the target path |
132
134
  | `state` | `unknown` | `undefined` | Arbitrary value attached to the navigation entry |
133
135
  | `as` | `(props: ElementProps<T>, state: { isActive: boolean; isPending: boolean }) => ReactElement` | renders `<a>` | Render function for using a custom element/component instead of the default <a>. Receives the props to spread onto your element (href, ref, event handlers, className, style, children) as the first argument, and `{ isActive, isPending }` as a separate second argument — kept separate so these values are never accidentally forwarded to the DOM |
@@ -578,6 +580,93 @@ const params = useParams<{ userId: string }>();
578
580
  // URL: /user/123 → params.userId === '123'
579
581
  ```
580
582
 
583
+ Pass a path pattern instead of a shape to infer it — no manual type needed:
584
+
585
+ ```tsx
586
+ const { productId } = useParams<'/product/:productId'>();
587
+ // productId: string
588
+ ```
589
+
590
+ ### Typed paths with `path` + `params`
591
+
592
+ `Link` and `useNavigate` accept raw URLs via `to` / `pathname` as usual. For type-checked
593
+ navigation, pass a route pattern via `path` with matching `params` instead — the router
594
+ interpolates the segments (values are URL-encoded, a missing param throws):
595
+
596
+ ```tsx
597
+ <Link path="/product/:productId" params={{ productId: '7' }} />
598
+ navigate({ path: '/product/:productId', params: { productId: '7' } });
599
+ ```
600
+
601
+ Parameter names and presence are checked from the literal itself: a missing `params`
602
+ or a wrong param name is a compile error. `params` values accept `string | number`.
603
+
604
+ Declarative and imperative forms are equivalent — this link:
605
+
606
+ ```tsx
607
+ <Link path="/nest/:nestId/item/:itemId" params={{ nestId, itemId }}>
608
+ {itemId}
609
+ </Link>
610
+ ```
611
+
612
+ does the same as this button:
613
+
614
+ ```tsx
615
+ const navigate = useNavigate();
616
+
617
+ <button onClick={() => navigate({ path: '/nest/:nestId/item/:itemId', params: { nestId, itemId } })}>
618
+ {itemId}
619
+ </button>
620
+ ```
621
+
622
+ Same type-checking, same interpolation. Use links for navigation, buttons with `navigate`
623
+ for actions that end in navigation (submit-then-go, confirm dialogs).
624
+
625
+ The library's part ends here: generic types (`LinkProps<T, TPath>`, `NavigatePathArg`,
626
+ `ParamsFor`) that pick up whatever union you give them. Everything above that is a
627
+ userland pattern — adopt it ladder-style, each rung optional:
628
+
629
+ - **Rung 0 — nothing.** Plain `<Link to="...">` works exactly as before, no unions,
630
+ no imports, no files. Proven by the library's own suite, which has no union anywhere.
631
+ - **Rung 1 — `path` + `params` on plain `Link`.** No union, no wrapper, no setup:
632
+ TypeScript infers the pattern from the `path` literal itself and checks `params`
633
+ against it:
634
+ ```tsx
635
+ <Link path="/product/:productId" params={{ productId: '7' }} /> // ok
636
+ <Link path="/product/:productId" /> // error: params missing
637
+ <Link path="/product/:productId" params={{ id: '7' }} /> // error: wrong param name
638
+ ```
639
+ But path *existence* is unchecked — there is no list to check against, so this
640
+ compiles silently:
641
+ ```tsx
642
+ <Link path="/playgroud/cache" /> // typo, no error (no union knows the routes)
643
+ ```
644
+ In other words: rung 1 checks internal consistency (`path` ↔ `params`), not the
645
+ outside world (path ↔ app routes). That half needs a union — rung 3.
646
+ - **Rung 2 — thin wrapper, no union.** Gives the pattern a name without any type file:
647
+ ```tsx
648
+ import { Link, type LinkProps } from 'clear-react-router';
649
+
650
+ export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T>) => (
651
+ <Link {...props} />
652
+ );
653
+ ```
654
+ - **Rung 3 — wrapper + union.** Binds one union for existence checking:
655
+ ```tsx
656
+ type AppPaths = '/cache' | '/product/:productId';
657
+
658
+ export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T, AppPaths>) => (
659
+ <Link {...props} />
660
+ );
661
+
662
+ <AppLink path="/product/:productId" params={{ productId: '7' }} /> // ok
663
+ <AppLink path="/playgroud/cache" /> // error: not in AppPaths
664
+ ```
665
+
666
+ The union is generated by script or hand-written.
667
+ Keep it next to the routes so drift is visible in review; a forgotten path fails
668
+ compilation at usage (fail-closed), a leftover entry is harmless.
669
+
581
670
  ### `useLocation()`
582
671
 
583
672
  Returns current location `{ pathname, search, state }`.
@@ -1,5 +1,5 @@
1
1
  import { type CSSProperties, ReactNode, MouseEvent, ReactElement, Ref } from 'react';
2
- import { RouterProps, SearchObject } from '../types';
2
+ import { LinkDestination, RouterProps, SearchObject } from '../types';
3
3
  type ElementState = {
4
4
  isActive: boolean;
5
5
  isPending: boolean;
@@ -16,8 +16,7 @@ export type ElementProps<T extends HTMLElement = HTMLElement> = {
16
16
  'aria-current'?: 'page';
17
17
  'aria-busy'?: boolean;
18
18
  } & Record<`data-${string}` | `aria-${string}`, unknown>;
19
- type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
20
- to: string;
19
+ export type LinkProps<T extends HTMLElement = HTMLAnchorElement, TPath extends string = string> = {
21
20
  search?: string | SearchObject;
22
21
  state?: unknown;
23
22
  children?: ReactNode;
@@ -30,6 +29,6 @@ type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
30
29
  beforeNavigate?(): Promise<void>;
31
30
  style?: CSSProperties | ((arg: ElementState) => CSSProperties);
32
31
  exact?: boolean;
33
- } & Record<`data-${string}` | `aria-${string}`, unknown>;
34
- export declare const Link: <T extends HTMLElement = HTMLAnchorElement>({ children, to, search, state, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, ...rest }: LinkProps<T>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
32
+ } & LinkDestination<TPath> & Record<`data-${string}` | `aria-${string}`, unknown>;
33
+ export declare const Link: <T extends HTMLElement = HTMLAnchorElement, const TPath extends string = string>({ children, to, path, params, search, state, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, ...rest }: LinkProps<T, TPath>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
35
34
  export {};
@@ -1 +1,4 @@
1
- export declare const useNavigate: () => (arg: import("..").NavigationLocation | string | -1) => Promise<void>;
1
+ export declare const useNavigate: () => {
2
+ (arg: import("..").NavigationLocation | string | -1): Promise<void>;
3
+ <const TPath extends string>(arg: import("..").NavigatePathArg<TPath>): Promise<void>;
4
+ };
@@ -1 +1,9 @@
1
- export declare const useParams: <T>() => T;
1
+ import type { ParamsFor } from '../types';
2
+ /**
3
+ * Route params of the current location.
4
+ *
5
+ * - `useParams()` — plain record, convenient but key typos are NOT caught.
6
+ * - `useParams<'/post/:postId'>()` — infers `{ postId: string }` from the pattern; typos are compile errors.
7
+ * - `useParams<{ ... }>()` — legacy manual shape, kept for compatibility.
8
+ */
9
+ export declare const useParams: <T = Record<string, string>>() => T extends string ? ParamsFor<T> : T;
package/dist/index.d.ts CHANGED
@@ -14,5 +14,5 @@ export { useSubmitAction } from './hooks/useSubmitAction';
14
14
  export { useRestoreScroll } from './hooks/useRestoreScroll';
15
15
  export { createRouter } from './creators/createRouter';
16
16
  export { lazy } from './utils/lazy';
17
- export type { RouteItem, BlockerState, Location, RouterProps, NavigationLocation, Status } from './types';
18
- export type { ElementProps } from './components/Link';
17
+ export type { RouteItem, BlockerState, Location, RouterProps, NavigationLocation, NavigatePathArg, PathParams, ParamsFor, Status, } from './types';
18
+ export type { ElementProps, LinkProps } from './components/Link';
package/dist/index.js CHANGED
@@ -188,6 +188,11 @@ var updateScrollMap = (routeDataState, scrollMapState) => {
188
188
  };
189
189
  });
190
190
  };
191
+ var interpolatePath = (pattern, params = {}) => pattern.replace(/:([^/]+)/g, (_, name) => {
192
+ const value = params[name];
193
+ if (value === void 0) throw new Error(`Missing param "${name}" for path "${pattern}"`);
194
+ return encodeURIComponent(String(value));
195
+ });
191
196
  var formatSearchObject = (searchObject) => {
192
197
  const params = new URLSearchParams();
193
198
  Object.entries(searchObject).forEach(([key, value]) => {
@@ -662,12 +667,25 @@ var createRouterInstance = (synchronizer) => {
662
667
  });
663
668
  return;
664
669
  }
665
- const search = typeof arg.search === "object" ? formatSearchObject(arg.search) : arg.search;
666
- await navigate({
667
- ...arg,
668
- search,
669
- prevLocation
670
- });
670
+ if (typeof arg === "object" && arg !== null && "path" in arg && arg.path !== void 0) {
671
+ const { path, params, ...rest } = arg;
672
+ const search = typeof rest.search === "object" ? formatSearchObject(rest.search) : rest.search ?? "";
673
+ await navigate({
674
+ ...rest,
675
+ pathname: interpolatePath(path, params ?? {}),
676
+ search,
677
+ prevLocation
678
+ });
679
+ return;
680
+ }
681
+ if (typeof arg === "object" && arg !== null && !("path" in arg)) {
682
+ const search = typeof arg.search === "object" ? formatSearchObject(arg.search) : arg.search;
683
+ await navigate({
684
+ ...arg,
685
+ search,
686
+ prevLocation
687
+ });
688
+ }
671
689
  },
672
690
  useAction: (action, options = {}) => {
673
691
  return async (input) => {
@@ -873,24 +891,25 @@ var useNavigate = router.hooks.useNavigate;
873
891
  //#region components/Link.tsx
874
892
  var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
875
893
  var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
876
- var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
894
+ var Link = ({ children, to, path, params, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
895
+ const pathname = path !== void 0 ? interpolatePath(path, params ?? {}) : to ?? "";
877
896
  const { useRouteDataSelector } = router.hooks;
878
- const isPending = useRouteDataSelector(({ location: { pathname }, status }) => pathname === to && status === "pending");
897
+ const isPending = useRouteDataSelector(({ location: { pathname: currentPathname }, status }) => currentPathname === pathname && status === "pending");
879
898
  const navigate = useNavigate();
880
- const isActive = useRouteDataSelector(({ location: { pathname } }) => comparator(to, pathname, exact));
899
+ const isActive = useRouteDataSelector(({ location: { pathname: currentPathname } }) => comparator(pathname, currentPathname, exact));
881
900
  const timeout = useRef(0);
882
901
  const elementRef = useRef(null);
883
902
  const getPrefetchStrategy = useCallback(() => linkPrefetch || routerConfig.defaultPrefetch, [linkPrefetch]);
884
903
  const getPrefetchDelay = useCallback(() => hoverPrefetchDelay ?? routerConfig.defaultHoverPrefetchDelay, [hoverPrefetchDelay]);
885
904
  const searchString = typeof search === "object" ? formatSearchObject(search) : search;
886
905
  const location = useMemo(() => ({
887
- pathname: to,
906
+ pathname,
888
907
  search: searchString,
889
908
  state
890
909
  }), [
891
910
  searchString,
892
911
  state,
893
- to
912
+ pathname
894
913
  ]);
895
914
  const onMouseEnter = useCallback(() => {
896
915
  const prefetchDelay = getPrefetchDelay();
@@ -954,7 +973,7 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
954
973
  "style": normalizedStyle,
955
974
  "className": resultClassName,
956
975
  "onClick": clickHandler,
957
- href: `${to}${searchString}`,
976
+ href: `${pathname}${searchString}`,
958
977
  onMouseEnter,
959
978
  onMouseLeave,
960
979
  children,
@@ -968,7 +987,14 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
968
987
  };
969
988
  //#endregion
970
989
  //#region hooks/useParams.ts
971
- var useParams = router.hooks.useParams;
990
+ /**
991
+ * Route params of the current location.
992
+ *
993
+ * - `useParams()` — plain record, convenient but key typos are NOT caught.
994
+ * - `useParams<'/post/:postId'>()` — infers `{ postId: string }` from the pattern; typos are compile errors.
995
+ * - `useParams<{ ... }>()` — legacy manual shape, kept for compatibility.
996
+ */
997
+ var useParams = () => router.hooks.useParams();
972
998
  //#endregion
973
999
  //#region hooks/useLocation.ts
974
1000
  var useLocation = () => router.hooks.useRouteDataSelector((state) => state.location);
package/dist/types.d.ts CHANGED
@@ -139,7 +139,10 @@ export type RouterType = {
139
139
  useContextState(): ReturnType<typeof useGlobalState<Record<string, unknown>>>;
140
140
  useBlockedTargetState(): ReturnType<typeof useGlobalState<Location | null>>;
141
141
  useParams<T>(): T;
142
- useNavigate(): (arg: NavigationLocation | string | -1) => Promise<void>;
142
+ useNavigate(): {
143
+ (arg: NavigationLocation | string | -1): Promise<void>;
144
+ <const TPath extends string>(arg: NavigatePathArg<TPath>): Promise<void>;
145
+ };
143
146
  useAction(action: string, options?: Options): (arg: Record<string, unknown>) => Promise<{
144
147
  data: unknown;
145
148
  error: Error | null;
@@ -168,5 +171,58 @@ export type SearchObject = Record<string, string | number | boolean | null | und
168
171
  export type NavigationLocation = Omit<Location, 'search'> & {
169
172
  search?: string | SearchObject;
170
173
  };
174
+ export type PathParams = Record<string, string | number>;
175
+ export type ParamsFor<TPath extends string> = TPath extends `${string}:${infer Param}/${infer Rest}` ? {
176
+ [K in Param | keyof ParamsFor<Rest> as K & string]: string;
177
+ } : TPath extends `${string}:${infer Param}` ? {
178
+ [K in Param]: string;
179
+ } : Record<string, never>;
180
+ export type ParamsInput<TPath extends string> = {
181
+ [K in keyof ParamsFor<TPath>]: string | number;
182
+ };
183
+ export type HasPathSegments<TPath extends string> = TPath extends `${string}:${string}` ? true : false;
184
+ type StrictLinkDestination<TPath extends string> = TPath extends unknown ? HasPathSegments<TPath> extends true ? {
185
+ to?: never;
186
+ path: TPath;
187
+ params: ParamsInput<TPath>;
188
+ } : {
189
+ to?: never;
190
+ path: TPath;
191
+ params?: never;
192
+ } : never;
193
+ export type LinkDestination<TPath extends string> = {
194
+ to: string;
195
+ path?: never;
196
+ params?: never;
197
+ } | (string extends TPath ? {
198
+ to?: never;
199
+ path: string;
200
+ params?: PathParams;
201
+ } : StrictLinkDestination<TPath>);
202
+ type StrictNavigateArg<TPath extends string> = TPath extends unknown ? HasPathSegments<TPath> extends true ? {
203
+ path: TPath;
204
+ params: ParamsInput<TPath>;
205
+ pathname?: never;
206
+ search?: string | SearchObject;
207
+ state?: unknown;
208
+ } : {
209
+ path: TPath;
210
+ params?: never;
211
+ pathname?: never;
212
+ search?: string | SearchObject;
213
+ state?: unknown;
214
+ } : never;
215
+ export type NavigatePathArg<TPath extends string> = string extends TPath ? {
216
+ path: string;
217
+ params?: PathParams;
218
+ search?: string | SearchObject;
219
+ state?: unknown;
220
+ } : StrictNavigateArg<TPath>;
221
+ export type NavigatePathInput = {
222
+ path: string;
223
+ params?: PathParams;
224
+ search?: string | SearchObject;
225
+ state?: unknown;
226
+ };
171
227
  export type Synchronizer = <T>(subscribe: (updater: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T;
172
228
  export {};
@@ -14,4 +14,5 @@ export declare const getPartialLoaderArgs: (contextState: RouterState["contextSt
14
14
  };
15
15
  export declare const isVerticalScroll: (el: Element | null) => boolean;
16
16
  export declare const updateScrollMap: (routeDataState: Store<RouteData>, scrollMapState: Store<ScrollMap>) => void;
17
+ export declare const interpolatePath: (pattern: string, params?: Record<string, string | number>) => string;
17
18
  export declare const formatSearchObject: (searchObject: SearchObject) => string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.4.1",
3
+ "version": "2.4.2",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {