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
30 changes: 30 additions & 0 deletions docs/guide/pages-routing/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,36 @@ 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 button that accepts an `isActive` prop. 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
29 changes: 29 additions & 0 deletions docs/reference/api/pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,35 @@ 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` | Pass getters for changing inputs. |
| Solid | `status().active` | Pass accessors for changing inputs. |

For a list of destinations, import `isLinkActive(router, href, options?)` or `isLinkPending(router, navigation, href, options?)` from `void/pages-client`. Obtain `router` and `navigation` from your adapter's `useRouter()` and `useNavigation()`. For example, a sidebar can find the label for its active section with a plain function.

```ts
import { isLinkActive } from 'void/pages-client';
import type { VoidRouter } from 'void/pages-client';
import type { Href } from 'void/routes';

function sectionLabel(router: VoidRouter, sections: { href: Href; label: string }[]) {
return sections.find(({ href }) => isLinkActive(router, href, { activeMatch: 'prefix' }))?.label;
}
```

## Prefetching {#prefetching}

`Link`'s `prefetch` prop takes `true`, `false`, a strategy, or an array of strategies:
Expand Down
4 changes: 2 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 { useLinkStatus, Link } from './link.tsx';
export { useRouter } from './use-router.ts';
export { useParams } from './use-params.ts';
export { useShared } from './use-shared.ts';
Expand All @@ -25,4 +25,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,
resolvedLinkStatus,
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(
() => resolvedLinkStatus(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>
);
}
60 changes: 60 additions & 0 deletions packages/react/test/unit/link-status.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// @vitest-environment happy-dom

import { act, createElement } from 'react';
import { createRoot } from 'react-dom/client';
import { expect, it } from 'vite-plus/test';
import { createSsrRouter } from 'void/pages-client';
import type { LinkStatus, NavigationState } from 'void/pages-client';
import { NavigationContext, RouterContext } from '../../src/runtime/context.ts';
import { Link, useLinkStatus } from '../../src/runtime/link.tsx';
import type { LinkProps } from '../../src/runtime/link.tsx';

(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

it('keeps the status object until current, active or pending changes', () => {
const router = createSsrRouter('/posts');
const hookStatuses: Array<LinkStatus> = [];
const linkStatuses: Array<LinkStatus> = [];
function Item() {
hookStatuses.push(useLinkStatus('/about', { data: { page: 1 } }));
const props: LinkProps = {
href: '/about',
data: { page: 1 },
children: (status) => {
linkStatuses.push(status);
return 'About';
},
};
return createElement(Link, props);
}
const visiting = (path: string): NavigationState => ({
state: 'loading',
location: new URL(path, router.url),
method: 'GET',
});
const container = document.createElement('div');
const root = createRoot(container);
const render = (navigation: NavigationState) =>
act(() => {
root.render(
createElement(
RouterContext.Provider,
{ value: router },
createElement(NavigationContext.Provider, { value: navigation }, createElement(Item)),
),
);
});
try {
render(visiting('/posts/1'));
render(visiting('/posts/2'));
render(visiting('/about?page=1'));

for (const statuses of [hookStatuses, linkStatuses]) {
expect(statuses).toHaveLength(3);
expect(statuses[1]).toBe(statuses[0]);
expect(statuses[2]).toEqual({ current: false, active: false, pending: true });
}
} finally {
act(() => root.unmount());
}
});
40 changes: 39 additions & 1 deletion packages/react/test/unit/link.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vite-plus/test';
import { createSsrRouter } from 'void/pages-client';
import type { NavigationMethod, NavigationState } from 'void/pages-client';
import { NavigationContext, RouterContext } from '../../src/runtime/context.ts';
import { Link } from '../../src/runtime/link.tsx';
import { Link, useLinkStatus } from '../../src/runtime/link.tsx';
import type { LinkProps } from '../../src/runtime/link.tsx';

function renderAt(url: string | null, props: LinkProps): string {
Expand Down Expand Up @@ -42,6 +42,44 @@ function renderVisiting(
}

describe('Link', () => {
it('gives the wrapper and link children the same status during a visit', () => {
const props = { href: '/users', activeMatch: 'prefix', data: { page: 2 } } as const;
function Item() {
const status = useLinkStatus(props.href, props);
expect(status).toEqual({ current: false, active: true, pending: true });
const linkProps: LinkProps = {
...props,
children: (childStatus) => {
expect(childStatus).toEqual(status);
return childStatus.pending ? 'Loading' : 'Users';
},
};
return createElement(Link, linkProps);
}
const router = createSsrRouter('/users/1');
const markup = renderToStaticMarkup(
createElement(
RouterContext.Provider,
{ value: router },
createElement(
NavigationContext.Provider,
{
value: {
state: 'loading',
method: 'GET',
location: new URL('/users?page=2', router.url),
},
},
createElement(Item),
),
),
);
expect(markup).toContain('data-void-active=""');
expect(markup).toContain('data-void-pending=""');
expect(markup).not.toContain('aria-current');
expect(markup).toContain('>Loading</a>');
});

it('marks the link to the current page', () => {
const current = renderAt('/users', { href: '/users' });
expect(current).toContain('aria-current="page"');
Expand Down
4 changes: 2 additions & 2 deletions packages/solid/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, type LinkProps } from './link.tsx';
export { useLinkStatus, Link, 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 @@ -24,4 +24,4 @@ export {
} from './context.ts';
export type { DeferredState as Deferred, InferProps } from 'void';

export type { PageError, ErrorPageProps } from 'void/pages-client';
export type { PageError, ErrorPageProps, LinkStatus, LinkStatusOptions } from 'void/pages-client';
Loading