Skip to content

Commit

Permalink
add some jsdocs & minor doc fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
marvin-j97 authored Nov 8, 2024
1 parent ebdde8f commit af7e46b
Show file tree
Hide file tree
Showing 3 changed files with 129 additions and 7 deletions.
15 changes: 8 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -818,7 +818,7 @@ if (unauthorized) {

### useLocation

Retrieves reactive `location` object useful for getting things like `pathname`
Retrieves reactive `location` object useful for getting things like `pathname`.

```js
const location = useLocation();
Expand Down Expand Up @@ -880,7 +880,8 @@ return <div classList={{ active: Boolean(match()) }} />;
For example if you stored breadcrumbs on your route definition you could retrieve them like so:
```js
const matches = useCurrentMatches();
const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb))

const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb));
```

### usePreloadRoute
Expand All @@ -898,11 +899,11 @@ preload(`/users/settings`, { preloadData: true });
`useBeforeLeave` takes a function that will be called prior to leaving a route. The function will be called with:

- from (_Location_): current location (before change).
- to (_string | number_}: path passed to `navigate`.
- options (_NavigateOptions_}: options passed to `navigate`.
- preventDefault (_void function_): call to block the route change.
- defaultPrevented (_readonly boolean_): true if any previously called leave handlers called preventDefault().
- retry (_void function_, _force?: boolean_ ): call to retry the same navigation, perhaps after confirming with the user. Pass `true` to skip running the leave handlers again (ie force navigate without confirming).
- to (_string | number_): path passed to `navigate`.
- options (_NavigateOptions_): options passed to `navigate`.
- preventDefault (_function_): call to block the route change.
- defaultPrevented (_readonly boolean_): `true` if any previously called leave handlers called `preventDefault`.
- retry (_function_, _force?: boolean_ ): call to retry the same navigation, perhaps after confirming with the user. Pass `true` to skip running the leave handlers again (i.e. force navigate without confirming).

Example usage:

Expand Down
3 changes: 3 additions & 0 deletions src/data/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ function getCache() {
return (req.router || (req.router = {})).cache || (req.router.cache = new Map());
}

/**
* Revalidates the given cache entry/entries.
*/
export function revalidate(key?: string | string[] | void, force = true) {
return startTransition(() => {
const now = Date.now();
Expand Down
118 changes: 118 additions & 0 deletions src/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,84 @@ export const useHref = (to: () => string | undefined) => {
});
};

/**
* Retrieves method to do navigation. The method accepts a path to navigate to and an optional object with the following options:
*
* - resolve (*boolean*, default `true`): resolve the path against the current route
* - replace (*boolean*, default `false`): replace the history entry
* - scroll (*boolean*, default `true`): scroll to top after navigation
* - state (*any*, default `undefined`): pass custom state to `location.state`
*
* **Note**: The state is serialized using the structured clone algorithm which does not support all object types.
*
* @example
* ```js
* const navigate = useNavigate();
*
* if (unauthorized) {
* navigate("/login", { replace: true });
* }
* ```
*/
export const useNavigate = () => useRouter().navigatorFactory();

/**
* Retrieves reactive `location` object useful for getting things like `pathname`.
*
* @example
* ```js
* const location = useLocation();
*
* const pathname = createMemo(() => parsePath(location.pathname));
* ```
*/
export const useLocation = <S = unknown>() => useRouter().location as Location<S>;

/**
* Retrieves signal that indicates whether the route is currently in a *Transition*.
* Useful for showing stale/pending state when the route resolution is *Suspended* during concurrent rendering.
*
* @example
* ```js
* const isRouting = useIsRouting();
*
* return (
* <div classList={{ "grey-out": isRouting() }}>
* <MyAwesomeContent />
* </div>
* );
* ```
*/
export const useIsRouting = () => useRouter().isRouting;

/**
* usePreloadRoute returns a function that can be used to preload a route manual.
* This is what happens automatically with link hovering and similar focus based behavior, but it is available here as an API.
*
* @example
* ```js
* const preload = usePreloadRoute();
*
* preload(`/users/settings`, { preloadData: true });
* ```
*/
export const usePreloadRoute = () => {
const pre = useRouter().preloadRoute
return (url: string | URL, options: { preloadData?: boolean } = {} ) =>
pre(url instanceof URL ? url : new URL(url, mockBase), options.preloadData)
}

/**
* `useMatch` takes an accessor that returns the path and creates a `Memo` that returns match information if the current path matches the provided path.
* Useful for determining if a given path matches the current route.
*
* @example
* ```js
* const match = useMatch(() => props.href);
*
* return <div classList={{ active: Boolean(match()) }} />;
* ```
*/
export const useMatch = <S extends string>(path: () => S, matchFilters?: MatchFilters<S>) => {
const location = useLocation();
const matchers = createMemo(() =>
Expand All @@ -98,8 +167,30 @@ export const useMatch = <S extends string>(path: () => S, matchFilters?: MatchFi
});
};

/**
* `useCurrentMatches` returns all the matches for the current matched route.
* Useful for getting all the route information.
*
* @example
* ```js
* const matches = useCurrentMatches();
*
* const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb))
* ```
*/
export const useCurrentMatches = () => useRouter().matches;

/**
* Retrieves a reactive, store-like object containing the current route path parameters as defined in the Route.
*
* @example
* ```js
* const params = useParams();
*
* // fetch user based on the id path parameter
* const [user] = createResource(() => params.id, fetchUser);
* ```
*/
export const useParams = <T extends Params>() => useRouter().params as T;

export const useSearchParams = <T extends SearchParams>(): [
Expand All @@ -119,6 +210,33 @@ export const useSearchParams = <T extends SearchParams>(): [
return [location.query as Partial<T>, setSearchParams];
};

/**
* useBeforeLeave takes a function that will be called prior to leaving a route.
* The function will be called with:
*
* - from (*Location*): current location (before change).
* - to (*string | number*): path passed to `navigate`.
* - options (*NavigateOptions*): options passed to navigate.
* - preventDefault (*function*): call to block the route change.
* - defaultPrevented (*readonly boolean*): `true` if any previously called leave handlers called `preventDefault`.
* - retry (*function*, force?: boolean ): call to retry the same navigation, perhaps after confirming with the user. Pass `true` to skip running the leave handlers again (i.e. force navigate without confirming).
*
* @example
* ```js
* useBeforeLeave((e: BeforeLeaveEventArgs) => {
* if (form.isDirty && !e.defaultPrevented) {
* // preventDefault to block immediately and prompt user async
* e.preventDefault();
* setTimeout(() => {
* if (window.confirm("Discard unsaved changes - are you sure?")) {
* // user wants to proceed anyway so retry with force=true
* e.retry(true);
* }
* }, 100);
* }
* });
* ```
*/
export const useBeforeLeave = (listener: (e: BeforeLeaveEventArgs) => void) => {
const s = useRouter().beforeLeave.subscribe({
listener,
Expand Down

0 comments on commit af7e46b

Please sign in to comment.