Skip to content
Open
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
98 changes: 98 additions & 0 deletions docs/guide/pages-routing/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,104 @@ A pending link matches the destination's path, query, and hash. A link to `/user

A `data-void-pending` you pass to `Link` replaces the computed value. For a loading indicator that covers the whole page, use [`useNavigation()`](../../reference/api/pages.md).

### Reading link status

Use `useLinkStatus(href, options?)` when a surrounding component needs a link’s state, such as a sidebar item that highlights its whole row. Pass the same `href`, `method`, `data`, and `activeMatch` as the `Link`:

::: code-group

```tsx [React]
import { Link, useLinkStatus } from '@void/react';
import type { Href } from 'void/routes';

function SidebarItem({ href, label }: { href: Href; label: string }) {
const { active } = useLinkStatus(href, { activeMatch: 'prefix' });
return (
<li className={active ? 'item item-active' : 'item'}>
<Link href={href} activeMatch="prefix">
{label}
</Link>
</li>
);
}
```

```vue [Vue]
<script setup lang="ts">
import { Link, useLinkStatus } from '@void/vue';
import type { Href } from 'void/routes';

const props = defineProps<{ href: Href; label: string }>();
const status = useLinkStatus(() => props.href, { activeMatch: 'prefix' });
</script>

<template>
<li :class="['item', { 'item-active': status.active }]">
<Link :href="href" active-match="prefix">{{ label }}</Link>
</li>
</template>
```

```svelte [Svelte]
<script lang="ts">
import { Link, useLinkStatus } from '@void/svelte';
import type { Href } from 'void/routes';

let { href, label }: { href: Href; label: string } = $props();
const status = useLinkStatus(() => href, { activeMatch: 'prefix' });
</script>

<li class="item" class:item-active={status.active}>
<Link {href} activeMatch="prefix">{label}</Link>
</li>
```

```tsx [Solid]
import { Link, useLinkStatus } from '@void/solid';
import type { Href } from 'void/routes';

function SidebarItem(props: { href: Href; label: string }) {
const status = useLinkStatus(() => props.href, { activeMatch: 'prefix' });
return (
<li class="item" classList={{ 'item-active': status().active }}>
<Link href={props.href} activeMatch="prefix">
{props.label}
</Link>
</li>
);
}
```

:::

For content inside a `Link`, read the same state from its children:

::: code-group

```tsx [React]
<Link href="/users">{({ pending }) => (pending ? 'Loading users…' : 'Users')}</Link>
```

```vue [Vue]
<Link href="/users" v-slot="{ pending }">{{ pending ? 'Loading users…' : 'Users' }}</Link>
```

```svelte [Svelte]
<Link href="/users">
{#snippet children({ pending })}
{pending ? 'Loading users…' : 'Users'}
{/snippet}
</Link>
```

```tsx [Solid]
<Link href="/users">{({ pending }) => (pending ? 'Loading users…' : 'Users')}</Link>
```

:::

See [Link status](../../reference/api/pages.md#link-status) for reactive inputs and how to match a list of destinations.

### Prefetching

Add `prefetch` to a `Link` to load its page before the user clicks. This markup works in all four adapters:
Expand Down
64 changes: 51 additions & 13 deletions docs/reference/api/pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,42 @@ With [`routing.typedRoutes`](../config.md#routing-typedroutes), `href` and route

See [Typed navigation](../../guide/pages-routing/overview.md#typed-navigation) for framework examples.

## Link status

All four adapters export `useLinkStatus(href, options?)`. Pass the same `href`, `method`, `data`, and `activeMatch` you would give a `Link`. The `LinkStatus` result contains three booleans.

| Field | When it is true |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `current` | The link matches the current page under the [active link rules](../../guide/pages-routing/overview.md#active-links). Void sets `aria-current="page"`. |
| `active` | The link is current, or matches a parent section with `activeMatch="prefix"`. Void sets `data-void-active`. |
| `pending` | A visit to this destination is in progress under the [pending link rules](../../guide/pages-routing/overview.md#pending-links). Void sets `data-void-pending`. |

| Adapter | Reading the result | Reactive inputs |
| ------- | ------------------------------------------------------------- | ----------------------------------------- |
| React | `status.active` | Pass the current props on each render. |
| Vue | `status.value.active` in script, `status.active` in templates | Pass refs or getters for changing inputs. |
| Svelte | `status.active` (destructuring reads the values only once) | Pass getters for changing inputs. |
| Solid | `status().active` | Pass accessors for changing inputs. |

For a list of destinations, use `isLinkActive(router, href, options?)` and `isLinkPending(router, navigation, href, options?)`, which take the same options. Get `router` and `navigation` from `useRouter()` and `useNavigation()`:

```ts
import { isLinkActive, useRouter } from '@void/react'; // or @void/vue, @void/svelte, @void/solid
import type { Href } from 'void/routes';

const sections: { href: Href; label: string }[] = [
{ href: '/admin/users', label: 'Users' },
{ href: '/admin/billing', label: 'Billing' },
];

// In a component:
const router = useRouter();
const activeLabel = () =>
sections.find(({ href }) => isLinkActive(router, href, { activeMatch: 'prefix' }))?.label;
```

Call `activeLabel()` where your framework tracks changes: during render in React, in the template or a `computed()` in Vue, in markup or `$derived()` in Svelte, and in JSX or a `createMemo()` in Solid.

## Prefetching {#prefetching}

`Link`'s `prefetch` prop takes `true`, `false`, a strategy, or an array of strategies:
Expand Down Expand Up @@ -64,19 +100,21 @@ Each adapter plugin's `prefetch` option sets app-wide values:

Import these helpers from your framework's adapter (`@void/react`, `@void/vue`, `@void/svelte`, or `@void/solid`).

| Export | Usage |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Link` | Renders an anchor for GET and a button for mutations. Accepts `href`, `method`, `data`, `prefetch`, `cacheFor`, `preserveScroll`, `preserveState`, `replace`, `reloadDocument`, `viewTransition`, `activeMatch`, and `onNavigate`. |
| `useRouter()` | Read `url`, `path`, `query`, and `params`. Navigate with `visit` or `refresh`, and manage prefetched pages with `prefetch`, `flush`, and `flushAll`. |
| `useParams()` | Read the current page's route parameters. Pass its pattern to type them, e.g. `useParams<'/users/[id]'>()`. |
| `useNavigation()` | Read `{ state, location, method }`. The state is `idle`, `loading`, or `submitting`. The location is the pending destination. |
| `useShared()` | Read [shared data](../../guide/pages-routing/layouts.md#shared-data) set by middleware, loaders, or actions. |
| `useForm(url, defaults, options?)` | Manage a [form](#form) bound to a page action. Submit with `post`, `put`, `patch`, or `delete`. |
| `useIslandForm(defaults)` | Manage a form in an [island](../../guide/pages-routing/islands.md#forms). Pass the action URL to each submit method. With [typed routes](../config.md#routing-typedroutes), the URL must be a [`RouteUrl`](./types.md#route-types). |
| `action(url, options?)` | Run a page action and await its [`ActionResult`](../../guide/pages-routing/actions-and-forms.md#action-helper). Accepts `data`, `params`, `preserveScroll`, and `method` (`POST` by default, or `PUT`, `PATCH`, or `DELETE`). |
| `isVoidActionError(error)` | Narrows a thrown action error to `VoidActionError`. |
| `isCallSiteActionError(error)` | Recognizes expected action errors such as `409` or `422`. |
| `getValidationErrors(body)` | Reads field errors from `error.body`. Returns `null` when there are none. |
| Export | Usage |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Link` | Renders an anchor for GET and a button for mutations. Accepts `href`, `method`, `data`, `prefetch`, `cacheFor`, `preserveScroll`, `preserveState`, `replace`, `reloadDocument`, `viewTransition`, `activeMatch`, and `onNavigate`. Children can read the [link status](#link-status). |
| `useRouter()` | Read `url`, `path`, `query`, and `params`. Navigate with `visit` or `refresh`, and manage prefetched pages with `prefetch`, `flush`, and `flushAll`. |
| `useParams()` | Read the current page's route parameters. Pass its pattern to type them, e.g. `useParams<'/users/[id]'>()`. |
| `useLinkStatus(href, options?)` | Read a destination's [link status](#link-status): `current`, `active`, and `pending`. Takes `method`, `data`, and `activeMatch`. |
| `isLinkActive`, `isLinkPending` | Plain functions that match a [list of destinations](#link-status) with the same rules. |
| `useNavigation()` | Read `{ state, location, method }`. The state is `idle`, `loading`, or `submitting`. The location is the pending destination. |
| `useShared()` | Read [shared data](../../guide/pages-routing/layouts.md#shared-data) set by middleware, loaders, or actions. |
| `useForm(url, defaults, options?)` | Manage a [form](#form) bound to a page action. Submit with `post`, `put`, `patch`, or `delete`. |
| `useIslandForm(defaults)` | Manage a form in an [island](../../guide/pages-routing/islands.md#forms). Pass the action URL to each submit method. With [typed routes](../config.md#routing-typedroutes), the URL must be a [`RouteUrl`](./types.md#route-types). |
| `action(url, options?)` | Run a page action and await its [`ActionResult`](../../guide/pages-routing/actions-and-forms.md#action-helper). Accepts `data`, `params`, `preserveScroll`, and `method` (`POST` by default, or `PUT`, `PATCH`, or `DELETE`). |
| `isVoidActionError(error)` | Narrows a thrown action error to `VoidActionError`. |
| `isCallSiteActionError(error)` | Recognizes expected action errors such as `409` or `422`. |
| `getValidationErrors(body)` | Reads field errors from `error.body`. Returns `null` when there are none. |

On GET links, `data` adds query parameters to the rendered `href`. Primitive values become strings and arrays become repeated keys. Void skips `null` and `undefined` and rejects nested objects. Only GET links accept `prefetch` and `reloadDocument`. Style the current link with [`data-void-active`](../../guide/pages-routing/overview.md#active-links) or `aria-current="page"`, and the pending destination with [`data-void-pending`](../../guide/pages-routing/overview.md#pending-links).

Expand Down
6 changes: 4 additions & 2 deletions packages/react/src/runtime/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { Form } from './form.tsx';
export { Link } from './link.tsx';
export { Link, useLinkStatus, type LinkProps } from './link.tsx';
export { useRouter } from './use-router.ts';
export { useParams } from './use-params.ts';
export { useShared } from './use-shared.ts';
Expand All @@ -10,6 +10,8 @@ export { action, setActionRouter } from './action.ts';
export {
getValidationErrors,
isCallSiteActionError,
isLinkActive,
isLinkPending,
isVoidActionError,
type ActionResult,
type VoidActionError,
Expand All @@ -25,4 +27,4 @@ export {
export type { InferProps } from 'void';
export type Deferred<T> = Promise<T>;

export type { PageError, ErrorPageProps } from 'void/pages-client';
export type { PageError, ErrorPageProps, LinkStatus, LinkStatusOptions } from 'void/pages-client';
62 changes: 42 additions & 20 deletions packages/react/src/runtime/link.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useContext, useEffect, useMemo, useRef } from 'react';
import type { JSX } from 'react';
import type { JSX, ReactNode } from 'react';
import type {
MouseEvent,
MouseEventHandler,
Expand All @@ -13,25 +13,49 @@ import type {
} from 'react';
import {
handleLinkClick,
linkActiveAttributes,
linkPendingAttributes,
getLinkStatus,
linkStatusAttributes,
getResolvedLinkStatus,
linkPrefetchStrategies,
observeLinkVisible,
prefetchLink,
resolveLink,
} from 'void/pages-client';
import type { BaseLinkProps } from 'void/pages-client';
import type { BaseLinkProps, LinkStatus, LinkStatusOptions } from 'void/pages-client';
import { NavigationContext, RouterContext } from './context.ts';

export type LinkProps = BaseLinkProps &
Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof BaseLinkProps> &
Omit<ButtonHTMLAttributes<HTMLButtonElement>, keyof BaseLinkProps>;
type CommonProps = BaseLinkProps & {
children?: ReactNode | ((status: LinkStatus) => ReactNode);
};

export type LinkProps = CommonProps &
Omit<AnchorHTMLAttributes<HTMLAnchorElement>, keyof CommonProps> &
Omit<ButtonHTMLAttributes<HTMLButtonElement>, keyof CommonProps>;

type LinkEventHandlers = Pick<
HTMLAttributes<HTMLElement>,
'onClick' | 'onFocus' | 'onMouseDown' | 'onMouseEnter' | 'onMouseLeave' | 'onTouchStart'
>;

export function useLinkStatus(
href: BaseLinkProps['href'],
{ method, data, activeMatch }: LinkStatusOptions = {},
): LinkStatus {
const router = useContext(RouterContext);
const navigation = useContext(NavigationContext);
return useStableLinkStatus(
useMemo(
() => getLinkStatus(router, navigation, href, { method, data, activeMatch }),
[activeMatch, data, href, method, navigation, router],
),
);
}

/** Keeps one object per status value so memoized children and effects skip unchanged updates. */
function useStableLinkStatus({ current, active, pending }: LinkStatus): LinkStatus {
return useMemo(() => ({ current, active, pending }), [active, current, pending]);
}

export function Link({
href,
method = 'GET',
Expand Down Expand Up @@ -72,15 +96,13 @@ export function Link({
() => linkPrefetchStrategies({ prefetch, reloadDocument }, { isGet }, defaultStrategy),
[defaultStrategy, isGet, prefetch, reloadDocument],
);
// The router context changes with the route URL, so this follows navigations.
const activeAttributes = useMemo(
() => linkActiveAttributes(router, link, activeMatch),
[activeMatch, link, router],
);
const pendingAttributes = useMemo(
() => linkPendingAttributes(router, navigation, link),
[link, navigation, router],
const status = useStableLinkStatus(
useMemo(
() => getResolvedLinkStatus(router, navigation, link, activeMatch),
[activeMatch, link, navigation, router],
),
);
const attributes = linkStatusAttributes(status);
const hoverDelay = router?._hoverDelay ?? 75;

const doPrefetch = useCallback(
Expand Down Expand Up @@ -245,18 +267,18 @@ export function Link({
[style],
);

const content = typeof children === 'function' ? children(status) : children;
if (link.isGet) {
return (
<a
ref={setElementRef}
href={link.href}
style={resolvedStyle}
{...activeAttributes}
{...pendingAttributes}
{...attributes}
{...rest}
{...eventHandlers}
>
{children}
{content}
</a>
);
}
Expand All @@ -266,11 +288,11 @@ export function Link({
ref={setElementRef}
type="button"
style={resolvedStyle}
{...pendingAttributes}
{...attributes}
{...rest}
{...eventHandlers}
>
{children}
{content}
</button>
);
}
Loading