diff --git a/docs/guide/pages-routing/overview.md b/docs/guide/pages-routing/overview.md
index 850b987a86..054b92b627 100644
--- a/docs/guide/pages-routing/overview.md
+++ b/docs/guide/pages-routing/overview.md
@@ -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 (
+
+
+ {label}
+
+
+ );
+}
+```
+
+```vue [Vue]
+
+
+
+
+ {{ label }}
+
+
+```
+
+```svelte [Svelte]
+
+
+
+ {label}
+
+```
+
+```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 (
+
+
+ {props.label}
+
+
+ );
+}
+```
+
+:::
+
+For content inside a `Link`, read the same state from its children:
+
+::: code-group
+
+```tsx [React]
+ {({ pending }) => (pending ? 'Loading users…' : 'Users')}
+```
+
+```vue [Vue]
+ {{ pending ? 'Loading users…' : 'Users' }}
+```
+
+```svelte [Svelte]
+
+ {#snippet children({ pending })}
+ {pending ? 'Loading users…' : 'Users'}
+ {/snippet}
+
+```
+
+```tsx [Solid]
+ {({ pending }) => (pending ? 'Loading users…' : 'Users')}
+```
+
+:::
+
+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:
diff --git a/docs/reference/api/pages.md b/docs/reference/api/pages.md
index fdb6733bca..d796c06c12 100644
--- a/docs/reference/api/pages.md
+++ b/docs/reference/api/pages.md
@@ -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:
@@ -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).
diff --git a/packages/react/src/runtime/index.ts b/packages/react/src/runtime/index.ts
index 2b973455d0..e809a7332f 100644
--- a/packages/react/src/runtime/index.ts
+++ b/packages/react/src/runtime/index.ts
@@ -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';
@@ -10,6 +10,8 @@ export { action, setActionRouter } from './action.ts';
export {
getValidationErrors,
isCallSiteActionError,
+ isLinkActive,
+ isLinkPending,
isVoidActionError,
type ActionResult,
type VoidActionError,
@@ -25,4 +27,4 @@ export {
export type { InferProps } from 'void';
export type Deferred = Promise;
-export type { PageError, ErrorPageProps } from 'void/pages-client';
+export type { PageError, ErrorPageProps, LinkStatus, LinkStatusOptions } from 'void/pages-client';
diff --git a/packages/react/src/runtime/link.tsx b/packages/react/src/runtime/link.tsx
index 5294d8d0dc..0dcada0dae 100644
--- a/packages/react/src/runtime/link.tsx
+++ b/packages/react/src/runtime/link.tsx
@@ -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,
@@ -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, keyof BaseLinkProps> &
- Omit, keyof BaseLinkProps>;
+type CommonProps = BaseLinkProps & {
+ children?: ReactNode | ((status: LinkStatus) => ReactNode);
+};
+
+export type LinkProps = CommonProps &
+ Omit, keyof CommonProps> &
+ Omit, keyof CommonProps>;
type LinkEventHandlers = Pick<
HTMLAttributes,
'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',
@@ -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(
@@ -245,18 +267,18 @@ export function Link({
[style],
);
+ const content = typeof children === 'function' ? children(status) : children;
if (link.isGet) {
return (
- {children}
+ {content}
);
}
@@ -266,11 +288,11 @@ export function Link({
ref={setElementRef}
type="button"
style={resolvedStyle}
- {...pendingAttributes}
+ {...attributes}
{...rest}
{...eventHandlers}
>
- {children}
+ {content}
);
}
diff --git a/packages/react/test/unit/link-status.test.ts b/packages/react/test/unit/link-status.test.ts
new file mode 100644
index 0000000000..6d0913132f
--- /dev/null
+++ b/packages/react/test/unit/link-status.test.ts
@@ -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 = [];
+ const linkStatuses: Array = [];
+ 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());
+ }
+});
diff --git a/packages/react/test/unit/link.test.ts b/packages/react/test/unit/link.test.ts
index 55b1a77fa9..96cffa3805 100644
--- a/packages/react/test/unit/link.test.ts
+++ b/packages/react/test/unit/link.test.ts
@@ -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 {
@@ -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');
+ });
+
it('marks the link to the current page', () => {
const current = renderAt('/users', { href: '/users' });
expect(current).toContain('aria-current="page"');
diff --git a/packages/solid/src/runtime/index.ts b/packages/solid/src/runtime/index.ts
index 6bdc27bf9d..52639da0b1 100644
--- a/packages/solid/src/runtime/index.ts
+++ b/packages/solid/src/runtime/index.ts
@@ -1,5 +1,5 @@
export { Form } from './form.tsx';
-export { Link, type LinkProps } 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';
@@ -10,6 +10,8 @@ export { action, setActionRouter } from './action.ts';
export {
getValidationErrors,
isCallSiteActionError,
+ isLinkActive,
+ isLinkPending,
isVoidActionError,
type ActionResult,
type VoidActionError,
@@ -24,4 +26,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';
diff --git a/packages/solid/src/runtime/link.tsx b/packages/solid/src/runtime/link.tsx
index 67ad1e8d4b..3ac02da06c 100644
--- a/packages/solid/src/runtime/link.tsx
+++ b/packages/solid/src/runtime/link.tsx
@@ -1,19 +1,21 @@
import { createMemo, onCleanup, onMount, splitProps, useContext } from 'solid-js';
-import type { JSX } from 'solid-js';
+import type { Accessor, JSX } from 'solid-js';
import {
handleLinkClick,
- linkActiveAttributes,
- linkPendingAttributes,
+ getLinkStatus,
+ linkStatusAttributes,
+ linkStatusEquals,
+ 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';
type CommonProps = BaseLinkProps & {
- children?: JSX.Element;
+ children?: JSX.Element | ((status: LinkStatus) => JSX.Element);
};
export type LinkProps = CommonProps &
@@ -41,6 +43,25 @@ function callHandler(handler: unknown, event: Event): void {
}
}
+export function useLinkStatus(
+ href: BaseLinkProps['href'] | Accessor,
+ options: LinkStatusOptions | Accessor = {},
+): Accessor {
+ const router = useContext(RouterContext);
+ const navigation = useContext(NavigationContext);
+ return createMemo(
+ () =>
+ getLinkStatus(
+ router,
+ navigation?.(),
+ typeof href === 'function' ? href() : href,
+ typeof options === 'function' ? options() : options,
+ ),
+ undefined,
+ { equals: linkStatusEquals },
+ );
+}
+
export function Link(props: LinkProps): JSX.Element {
const [local, rest] = splitProps(props, [
'href',
@@ -72,12 +93,22 @@ export function Link(props: LinkProps): JSX.Element {
linkPrefetchStrategies(local, link(), router?._prefetchDefaultStrategy),
);
const resolvedStyle = createMemo(() => mergeStyle(local.style));
- // Reading router.url tracks the route URL, so this follows navigations.
- const activeAttributes = createMemo(() =>
- linkActiveAttributes(router, link(), local.activeMatch),
+ const status = createMemo(
+ () => getResolvedLinkStatus(router, navigation?.(), link(), local.activeMatch),
+ undefined,
+ { equals: linkStatusEquals },
);
- // Calling navigation() tracks visits as they start and end.
- const pendingAttributes = createMemo(() => linkPendingAttributes(router, navigation?.(), link()));
+ const attributes = createMemo(() => linkStatusAttributes(status()));
+ function content(): JSX.Element {
+ const children = local.children;
+ // Solid passes , , and lazy components as zero-argument accessors,
+ // which JSX.Element already allows. Like , only call a function that
+ // takes an argument, so those children are not rebuilt on status changes.
+ if (typeof children === 'function' && children.length > 0) {
+ return children(status());
+ }
+ return children as JSX.Element;
+ }
function doPrefetch() {
prefetchLink(router, link().href, local.cacheFor);
@@ -181,13 +212,12 @@ export function Link(props: LinkProps): JSX.Element {
el = r;
}}
href={link().href}
- {...activeAttributes()}
- {...pendingAttributes()}
+ {...attributes()}
{...rest}
style={resolvedStyle()}
{...eventHandlers()}
>
- {local.children}
+ {content()}
) : (
- {local.children}
+ {content()}
)}
>
diff --git a/packages/solid/test/integration/use-params-navigation.test.ts b/packages/solid/test/integration/use-params-navigation.test.ts
index 8fc337b002..914a9759d5 100644
--- a/packages/solid/test/integration/use-params-navigation.test.ts
+++ b/packages/solid/test/integration/use-params-navigation.test.ts
@@ -18,20 +18,34 @@ export default function Post(props) {
;
}`;
-const LAYOUT = `import { useParams, useRouter } from "@void/solid";
-import { createEffect, createSignal } from "solid-js";
+const LAYOUT = `import { Link, useLinkStatus, useParams, useRouter } from "@void/solid";
+import { Show, createEffect, createSignal } from "solid-js";
+function Mounted() {
+ window.linkChildMounts = (window.linkChildMounts ?? 0) + 1;
+ return Post a ;
+}
export default function Layout(props) {
const params = useParams();
const router = useRouter();
+ const status = useLinkStatus(() => params.slug ? "/posts/b" : "/about");
const [observed, setObserved] = createSignal([]);
const [refreshes, setRefreshes] = createSignal(0);
+ const [statusRuns, setStatusRuns] = createSignal([]);
createEffect(() => {
const slug = params.slug;
setObserved(values => [...values, slug ?? null]);
});
+ createEffect(() => {
+ const { current, active, pending } = status();
+ setStatusRuns(runs => [...runs, [current, active, pending].map(Number).join("")]);
+ });
return
+
{String(status().current)}
+
{({ active }) => active ? "Posts section" : "Other section"}
+
{params.slug}
{JSON.stringify(observed())}
+
{JSON.stringify(statusRuns())}
{
await router.refresh();
setRefreshes(count => count + 1);
@@ -116,6 +130,8 @@ it('keeps useParams reactive without notifying unchanged values', async () => {
await page.waitForSelector('#app[data-hydrated="true"]');
expect(await page.textContent('#slug')).toBe('a');
expect(await page.textContent('#layout-slug')).toBe('a');
+ expect(await page.textContent('#link-current')).toBe('false');
+ expect(await page.textContent('a[href="/posts"]')).toBe('Posts section');
// A full reload would also render "b", so check that the document survives.
await page.evaluate(() => {
@@ -125,6 +141,7 @@ it('keeps useParams reactive without notifying unchanged values', async () => {
await page.waitForFunction(() => document.getElementById('title')?.textContent === 'Post b');
expect(await page.textContent('#slug')).toBe('b');
expect(await page.textContent('#layout-slug')).toBe('b');
+ expect(await page.textContent('#link-current')).toBe('true');
expect(await page.textContent('#observed-slugs')).toBe('["a","b"]');
// A refresh commits a new page response, but unchanged params must not
@@ -136,6 +153,8 @@ it('keeps useParams reactive without notifying unchanged values', async () => {
await page.click('a[href="/about"]');
await page.waitForFunction(() => document.getElementById('title')?.textContent === 'About');
expect(await page.textContent('#layout-slug')).toBe('');
+ expect(await page.textContent('#link-current')).toBe('true');
+ expect(await page.textContent('a[href="/posts"]')).toBe('Other section');
expect(await page.textContent('#observed-slugs')).toBe('["a","b",null]');
await page.goBack();
@@ -144,6 +163,15 @@ it('keeps useParams reactive without notifying unchanged values', async () => {
expect(await page.textContent('#layout-slug')).toBe('b');
expect(await page.textContent('#observed-slugs')).toBe('["a","b",null,"b"]');
expect(await page.getAttribute('html', 'data-same-document')).toBe('true');
+
+ // Status memos compare by value, so effects never rerun for an unchanged status.
+ const statusRuns: Array = JSON.parse((await page.textContent('#status-runs')) ?? '[]');
+ expect(statusRuns.length).toBeGreaterThan(1);
+ expect(statusRuns.filter((run, index) => run === statusRuns[index - 1])).toEqual([]);
+ // A child that is not a render function, such as , survives status changes.
+ expect(
+ await page.evaluate(() => (window as unknown as { linkChildMounts: number }).linkChildMounts),
+ ).toBe(1);
} finally {
await server.close();
await browser.close();
diff --git a/packages/svelte/src/runtime/Link.svelte b/packages/svelte/src/runtime/Link.svelte
index 79b48a4087..2cc0993bc9 100644
--- a/packages/svelte/src/runtime/Link.svelte
+++ b/packages/svelte/src/runtime/Link.svelte
@@ -1,7 +1,7 @@
{title}
{params.slug}
+{status.current}/{status.active}/{status.pending}
`;
-it('useParams() follows navigation between two params of the same page', async () => {
+it('useParams and link status getters follow navigation between two params of the same page', async () => {
const root = createPackageFixtureDir(join(import.meta.dirname, '../..'), '.tmp-use-params-');
writeFileSync(join(root, 'Page.svelte'), PAGE);
writeFileSync(join(root, 'entry.js'), ENTRY);
@@ -78,10 +91,23 @@ it('useParams() follows navigation between two params of the same page', async (
await page.goto(server.resolvedUrls!.local[0]);
await page.waitForSelector('#slug');
expect(await page.textContent('#slug')).toBe('a');
+ expect(await page.textContent('#status')).toBe('true/true/false');
+
+ await page.evaluate(() =>
+ (window as unknown as { visit: (path: string) => void }).visit('/posts/a'),
+ );
+ await page.waitForFunction(
+ () => document.getElementById('status')?.textContent === 'true/true/true',
+ );
await page.evaluate(() => (window as unknown as { navigateToB: () => void }).navigateToB());
await page.waitForFunction(() => document.getElementById('title')?.textContent === 'Post b');
expect(await page.textContent('#slug')).toBe('b');
+ expect(await page.textContent('#status')).toBe('false/true/false');
+ // Each field is derived separately, so readers of an unchanged field never rerun.
+ expect(
+ await page.evaluate(() => (window as unknown as { activeRuns: Array }).activeRuns),
+ ).toEqual([true]);
} finally {
await server.close();
await browser.close();
diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md
index b85804dbbc..ca327a4c1a 100644
--- a/packages/void/skills/void/SKILL.md
+++ b/packages/void/skills/void/SKILL.md
@@ -96,11 +96,11 @@ Use `void deploy --skip-migrations` when database migrations run separately; it
guides and use `void info` to preserve resource names and instance keys.
- Declare application environment keys in `env.ts` and access them through
`void/env`; follow `docs/guide/env-vars.md` for local and production values.
-- In Pages navigation, style the current link with `Link`'s `aria-current` and `data-void-active`
- attributes (`activeMatch="prefix"` for sections) instead of comparing `useRouter().path`; see
- `docs/guide/pages-routing/overview.md#active-links`. Show a loading state on
- the clicked link with `data-void-pending` instead of matching `useNavigation().location`
- yourself; see `docs/guide/pages-routing/overview.md#pending-links`.
+- For Pages navigation, style links with `aria-current`, `data-void-active`
+ (`activeMatch="prefix"` for sections), and `data-void-pending`. For other UI, read
+ `useLinkStatus()`, `Link` children, or `isLinkActive()`/`isLinkPending()` for lists
+ instead of comparing `useRouter().path` or `useNavigation().location` yourself. See
+ `docs/guide/pages-routing/overview.md#reading-link-status`.
- For platform setup, follow the pages linked from
`docs/guide/self-hosted-platform.md`. Use `void platform list` to find the
installation slug for maintenance. For recovery, use its documented resume
diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts
index 42dc7284fc..ec0b93ad21 100644
--- a/packages/void/src/pages/client.ts
+++ b/packages/void/src/pages/client.ts
@@ -26,13 +26,19 @@ import { isSameOrigin } from './url.ts';
export { getValidationErrors, isModifiedEvent, mergeDataIntoHref } from './adapter-helpers.ts';
export {
+ getLinkStatus,
handleLinkClick,
+ isLinkActive,
+ isLinkPending,
linkActiveAttributes,
linkPendingAttributes,
linkPrefetchStrategies,
+ linkStatusAttributes,
+ linkStatusEquals,
observeLinkVisible,
prefetchLink,
resolveLink,
+ getResolvedLinkStatus,
type BaseLinkProps,
type LinkActiveAttributes,
type LinkActiveMatch,
@@ -40,6 +46,8 @@ export {
type LinkPendingAttributes,
type LinkPrefetchValue,
type LinkPrefetchStrategy,
+ type LinkStatus,
+ type LinkStatusOptions,
type ResolvedLink,
} from './link.ts';
export {
diff --git a/packages/void/src/pages/link.ts b/packages/void/src/pages/link.ts
index a24c2086bc..881ad69727 100644
--- a/packages/void/src/pages/link.ts
+++ b/packages/void/src/pages/link.ts
@@ -38,6 +38,14 @@ export type BaseLinkProps = {
onNavigate?: (event: LinkNavigateEvent) => void;
};
+export type LinkStatusOptions = Pick;
+
+export type LinkStatus = {
+ current: boolean;
+ active: boolean;
+ pending: boolean;
+};
+
export type ResolvedLink = {
method: NavigationMethod;
isGet: boolean;
@@ -120,84 +128,150 @@ export function linkPrefetchStrategies(
return prefetch;
}
+type ActiveMatch = 'current' | 'ancestor' | undefined;
+
/**
- * Marks a GET link to the current page. Pathnames compare the way the server
+ * Matches a GET link against the current page. Pathnames compare the way the server
* matches pages: case-sensitive, trailing slash significant, decoded like Hono's
* getPath. A link with a query also needs each of its params, with the same value,
* in the current URL, which may have more params in any order. GET data counts as
* query, and the hash is ignored. `prefix` also matches nested pages by whole
* segment, except for `/`, comparing only the path, but only an exact match is
- * `aria-current`. Spread the result before the user's attributes so theirs win.
+ * current (`aria-current`).
*/
-export function linkActiveAttributes(
- router: VoidRouter | null | undefined,
- link: ResolvedLink,
- match: LinkActiveMatch = 'exact',
-): LinkActiveAttributes {
- if (!router || !link.isGet) {
- return {};
- }
-
- const current = router.url;
- const target = resolveSameOrigin(link.href, current);
- if (!target) {
- return {};
- }
-
+function matchActive(current: URL, target: URL, match: LinkActiveMatch): ActiveMatch {
const currentPath = decodePagePath(current.pathname);
const linkPath = decodePagePath(target.pathname);
if (linkPath === currentPath) {
// A link that only changes the query, such as pagination, leads to another page.
- return hasQueryParams(current.searchParams, target.searchParams)
- ? { 'aria-current': 'page', 'data-void-active': '' }
- : {};
+ return hasQueryParams(current.searchParams, target.searchParams) ? 'current' : undefined;
}
if (match === 'prefix' && linkPath !== '/') {
const parent = linkPath.endsWith('/') ? linkPath : `${linkPath}/`;
if (currentPath.startsWith(parent)) {
- return { 'data-void-active': '' };
+ return 'ancestor';
}
}
-
- return {};
}
/**
- * Marks a link while a visit to its destination is loading: the visit uses the link's
+ * Matches a visit that is loading the link's destination: the visit uses the link's
* method and goes to its path, query and hash. Unlike active links, the whole query and
* the hash count, so `?tab=open` isn't pending during a visit to `?tab=open&page=2`.
- * Every link to the destination is marked, not only the one that was clicked.
- * Spread the result before the user's attributes so theirs win.
+ * Every link to the destination is pending, not only the one that was clicked.
*/
-export function linkPendingAttributes(
- router: VoidRouter | null | undefined,
+function matchPending(
navigation: NavigationState | null | undefined,
- link: ResolvedLink,
-): LinkPendingAttributes {
- if (
- !router ||
- !navigation?.location ||
- navigation.state === 'idle' ||
- navigation.method !== link.method
- ) {
- return {};
- }
-
- const destination = navigation.location;
- const target = resolveSameOrigin(link.href, router.url);
- if (
- target &&
+ method: NavigationMethod,
+ target: URL,
+): boolean {
+ const destination = navigation?.location;
+ return Boolean(
+ destination &&
+ navigation.state !== 'idle' &&
+ navigation.method === method &&
target.host === destination.host &&
target.protocol === destination.protocol &&
decodePagePath(target.pathname) === decodePagePath(destination.pathname) &&
target.search === destination.search &&
- target.hash === destination.hash
- ) {
- return { 'data-void-pending': '' };
+ target.hash === destination.hash,
+ );
+}
+
+/** Reads the same current, active and pending state used by a Link with these props. */
+export function getLinkStatus(
+ router: VoidRouter | null | undefined,
+ navigation: NavigationState | null | undefined,
+ href: Href,
+ { method, data, activeMatch }: LinkStatusOptions = {},
+): LinkStatus {
+ return getResolvedLinkStatus(
+ router,
+ navigation,
+ resolveLink({ href, method, data }),
+ activeMatch,
+ );
+}
+
+/** Like getLinkStatus(), for a link an adapter has already resolved. */
+export function getResolvedLinkStatus(
+ router: VoidRouter | null | undefined,
+ navigation: NavigationState | null | undefined,
+ link: ResolvedLink,
+ match: LinkActiveMatch = 'exact',
+): LinkStatus {
+ const current = router?.url;
+ const target = current && resolveSameOrigin(link.href, current);
+ if (!current || !target) {
+ return { current: false, active: false, pending: false };
}
+ const active = link.isGet ? matchActive(current, target, match) : undefined;
+ return {
+ current: active === 'current',
+ active: active !== undefined,
+ pending: matchPending(navigation, link.method, target),
+ };
+}
+
+/** Compares statuses by value so fine-grained adapters skip unchanged notifications. */
+export function linkStatusEquals(a: LinkStatus, b: LinkStatus): boolean {
+ return a.current === b.current && a.active === b.active && a.pending === b.pending;
+}
+
+/** Returns true for the current page and, with prefix matching, its parent paths. */
+export function isLinkActive(
+ router: VoidRouter | null | undefined,
+ href: Href,
+ options?: LinkStatusOptions,
+): boolean {
+ return getLinkStatus(router, null, href, options).active;
+}
+
+/**
+ * Returns true during a visit with the link's method, path, full query and hash.
+ * Takes the same options as isLinkActive(); `activeMatch` doesn't change pending.
+ */
+export function isLinkPending(
+ router: VoidRouter | null | undefined,
+ navigation: NavigationState | null | undefined,
+ href: Href,
+ options?: LinkStatusOptions,
+): boolean {
+ return getLinkStatus(router, navigation, href, options).pending;
+}
- return {};
+/** Spread before authored attributes so the user's values win. */
+export function linkStatusAttributes(
+ status: LinkStatus,
+): LinkActiveAttributes & LinkPendingAttributes {
+ const attributes: LinkActiveAttributes & LinkPendingAttributes = {};
+ if (status.current) {
+ attributes['aria-current'] = 'page';
+ }
+ if (status.active) {
+ attributes['data-void-active'] = '';
+ }
+ if (status.pending) {
+ attributes['data-void-pending'] = '';
+ }
+ return attributes;
+}
+
+export function linkActiveAttributes(
+ router: VoidRouter | null | undefined,
+ link: ResolvedLink,
+ match?: LinkActiveMatch,
+): LinkActiveAttributes {
+ return linkStatusAttributes(getResolvedLinkStatus(router, null, link, match));
+}
+
+export function linkPendingAttributes(
+ router: VoidRouter | null | undefined,
+ navigation: NavigationState | null | undefined,
+ link: ResolvedLink,
+): LinkPendingAttributes {
+ return getResolvedLinkStatus(router, navigation, link).pending ? { 'data-void-pending': '' } : {};
}
/** Each of `params` has the same value in `current`. Extra params in `current` are allowed. */
diff --git a/packages/void/test/unit/pages-link.test.ts b/packages/void/test/unit/pages-link.test.ts
index b69860fb74..0f45c933d0 100644
--- a/packages/void/test/unit/pages-link.test.ts
+++ b/packages/void/test/unit/pages-link.test.ts
@@ -2,7 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import {
createRouterFacade,
createSsrRouter,
+ getLinkStatus,
idleNavigationState,
+ isLinkActive,
+ isLinkPending,
+ linkStatusAttributes,
} from '../../src/pages/client.ts';
import type { NavigationMethod, VoidRouter } from '../../src/pages/client.ts';
import {
@@ -347,6 +351,69 @@ describe('linkPendingAttributes', () => {
});
});
+describe('public link status', () => {
+ const router = createSsrRouter('/café/posts?page=2&sort=new', {}, 'https://app.test');
+ const navigation = {
+ state: 'loading',
+ location: new URL('https://app.test/caf%C3%A9/posts?page=2#top'),
+ method: 'GET',
+ } as const;
+
+ it.each([
+ ['/café/posts#top', { data: { page: 2 } }, { current: true, active: true, pending: true }],
+ ['?page=2', {}, { current: true, active: true, pending: false }],
+ ['?page=1', {}, { current: false, active: false, pending: false }],
+ ['/caf%C3%A9', { activeMatch: 'prefix' }, { current: false, active: true, pending: false }],
+ ['/', { activeMatch: 'prefix' }, { current: false, active: false, pending: false }],
+ [
+ '/café/posts?page=2#top',
+ { method: 'post' },
+ { current: false, active: false, pending: false },
+ ],
+ [
+ 'https://other.test/café/posts?page=2#top',
+ {},
+ { current: false, active: false, pending: false },
+ ],
+ ] as const)('matches %s with %j', (href, options, expected) => {
+ expect(getLinkStatus(router, navigation, href, options)).toEqual(expected);
+ expect(isLinkActive(router, href, options)).toBe(expected.active);
+ expect(isLinkPending(router, navigation, href, options)).toBe(expected.pending);
+ const link = resolveLink({ ...options, href });
+ expect(linkStatusAttributes(expected)).toEqual({
+ ...linkActiveAttributes(
+ router,
+ link,
+ 'activeMatch' in options ? options.activeMatch : undefined,
+ ),
+ ...linkPendingAttributes(router, navigation, link),
+ });
+ });
+
+ it('reports nothing without a router', () => {
+ expect(getLinkStatus(null, navigation, '/café/posts?page=2#top')).toEqual({
+ current: false,
+ active: false,
+ pending: false,
+ });
+ expect(isLinkActive(null, '/', { activeMatch: 'prefix' })).toBe(false);
+ expect(isLinkActive(undefined, '/café/posts')).toBe(false);
+ expect(isLinkPending(null, navigation, '/café/posts?page=2#top')).toBe(false);
+ expect(isLinkPending(router, null, '/café/posts?page=2#top')).toBe(false);
+ });
+
+ it('reports a pending submission for a matching non-GET link', () => {
+ const submission = { ...navigation, state: 'submitting', method: 'POST' } as const;
+ expect(getLinkStatus(router, submission, '/café/posts?page=2#top', { method: 'post' })).toEqual(
+ {
+ current: false,
+ active: false,
+ pending: true,
+ },
+ );
+ });
+});
+
describe('prefetchLink', () => {
it('prefetches other destinations with cacheFor only when given', () => {
const router = createRouter();
diff --git a/packages/vue/src/runtime/index.ts b/packages/vue/src/runtime/index.ts
index 36298c9cd2..cdb08f9a89 100644
--- a/packages/vue/src/runtime/index.ts
+++ b/packages/vue/src/runtime/index.ts
@@ -4,12 +4,16 @@ export { useRouter } from './use-router.ts';
export { useParams } from './use-params.ts';
export { useShared } from './use-shared.ts';
export { useForm } from './use-form.ts';
+export { useLinkStatus } from './use-link-status.ts';
+export type { LinkStatus, LinkStatusOptions } from 'void/pages-client';
export { useNavigation } from './use-navigation.ts';
export { useIslandForm } from './use-island-form.ts';
export { action, setActionRouter } from './action.ts';
export {
getValidationErrors,
isCallSiteActionError,
+ isLinkActive,
+ isLinkPending,
isVoidActionError,
type ActionResult,
type VoidActionError,
diff --git a/packages/vue/src/runtime/link.ts b/packages/vue/src/runtime/link.ts
index c1a82f1b4b..034dc2d696 100644
--- a/packages/vue/src/runtime/link.ts
+++ b/packages/vue/src/runtime/link.ts
@@ -1,7 +1,8 @@
import {
handleLinkClick,
- linkActiveAttributes,
- linkPendingAttributes,
+ linkStatusAttributes,
+ linkStatusEquals,
+ getResolvedLinkStatus,
linkPrefetchStrategies,
observeLinkVisible,
prefetchLink,
@@ -12,6 +13,7 @@ import type {
LinkActiveMatch,
LinkNavigateEvent,
LinkPrefetchValue,
+ LinkStatus,
NavigationState,
VoidRouter,
} from 'void/pages-client';
@@ -23,6 +25,7 @@ import type {
DefineSetupFnComponent,
ExtractPublicPropTypes,
PropType,
+ SlotsType,
} from 'vue';
type LinkMethod = NonNullable;
@@ -86,6 +89,7 @@ function callHandler(handler: unknown, event: Event): void {
const LinkComponent = defineComponent({
name: 'Link',
props: linkPropOptions,
+ slots: Object as SlotsType<{ default: LinkStatus }>,
setup(props, { slots, attrs }) {
const router = inject('__void_router', null);
const navigation = inject('__void_navigation', null);
@@ -94,12 +98,11 @@ const LinkComponent = defineComponent({
const strategies = computed(() =>
linkPrefetchStrategies(props, link.value, router?._prefetchDefaultStrategy),
);
- // Reading router.url tracks the route URL, so this follows navigations.
- const activeAttributes = computed(() =>
- linkActiveAttributes(router, link.value, props.activeMatch),
- );
- // The injected navigation state is reactive, so this follows visits as they start and end.
- const pendingAttributes = computed(() => linkPendingAttributes(router, navigation, link.value));
+ // Keep the previous object for an equal status so the render skips unchanged updates.
+ const status = computed((previous) => {
+ const next = getResolvedLinkStatus(router, navigation, link.value, props.activeMatch);
+ return previous && linkStatusEquals(previous, next) ? previous : next;
+ });
function doPrefetch() {
prefetchLink(router, link.value.href, props.cacheFor);
@@ -190,15 +193,14 @@ const LinkComponent = defineComponent({
return h(
tag,
{
- ...activeAttributes.value,
- ...pendingAttributes.value,
+ ...linkStatusAttributes(status.value),
...attrs,
ref: elRef,
...(isGet ? { href } : { type: 'button' }),
style: [{ touchAction: 'manipulation' }, (attrs as { style?: unknown }).style],
...eventHandlers,
},
- slots.default?.(),
+ slots.default?.(status.value),
);
};
},
@@ -208,5 +210,9 @@ const LinkComponent = defineComponent({
// treat LinkProps as runtime prop options and widen `href` to an optional `any`.
// The options component is not assignable to it, so cast; the check above keeps
// the runtime props in step with BaseLinkProps.
-export const Link: DefineSetupFnComponent =
- LinkComponent as DefineSetupFnComponent;
+type PublicLink = DefineSetupFnComponent<
+ LinkProps,
+ Record,
+ SlotsType<{ default: LinkStatus }>
+>;
+export const Link: PublicLink = LinkComponent as PublicLink;
diff --git a/packages/vue/src/runtime/use-link-status.ts b/packages/vue/src/runtime/use-link-status.ts
new file mode 100644
index 0000000000..b4d08c2ab5
--- /dev/null
+++ b/packages/vue/src/runtime/use-link-status.ts
@@ -0,0 +1,18 @@
+import { getLinkStatus, linkStatusEquals } from 'void/pages-client';
+import type { LinkStatus, LinkStatusOptions, NavigationState, VoidRouter } from 'void/pages-client';
+import type { Href } from 'void/routes';
+import { computed, inject, toValue } from 'vue';
+import type { ComputedRef, MaybeRefOrGetter } from 'vue';
+
+export function useLinkStatus(
+ href: MaybeRefOrGetter,
+ options?: MaybeRefOrGetter,
+): ComputedRef {
+ const router = inject('__void_router', null);
+ const navigation = inject('__void_navigation', null);
+ // Keep the previous object for an equal status so watchers skip unchanged updates.
+ return computed((previous) => {
+ const next = getLinkStatus(router, navigation, toValue(href), toValue(options));
+ return previous && linkStatusEquals(previous, next) ? previous : next;
+ });
+}
diff --git a/packages/vue/test/unit/link.typecheck.ts b/packages/vue/test/unit/link.typecheck.ts
index 1690efd270..4dd38cd5aa 100644
--- a/packages/vue/test/unit/link.typecheck.ts
+++ b/packages/vue/test/unit/link.typecheck.ts
@@ -1,3 +1,4 @@
+import type { LinkStatus } from 'void/pages-client';
import { h } from 'vue';
import { Link } from '../../src/runtime/link.ts';
@@ -23,3 +24,16 @@ export function checkLinkPassThroughAttributes(): void {
const badActiveMatch: LinkProps = { href: '/users', activeMatch: 'nested' };
void [missingHref, badPrefetch, badActiveMatch];
}
+
+export function checkLinkStatusSlot(): void {
+ type LinkSlots = InstanceType['$slots'];
+ const slots = {} as LinkSlots;
+ void slots.default?.({ current: true, active: true, pending: false });
+ // @ts-expect-error the default slot receives the link status
+ void slots.default?.();
+ void h(
+ Link,
+ { href: '/users' },
+ { default: ({ pending }: LinkStatus) => (pending ? 'Loading' : 'Users') },
+ );
+}
diff --git a/packages/vue/test/unit/use-link-status.test.ts b/packages/vue/test/unit/use-link-status.test.ts
new file mode 100644
index 0000000000..e96339aeab
--- /dev/null
+++ b/packages/vue/test/unit/use-link-status.test.ts
@@ -0,0 +1,45 @@
+import { expect, it } from 'vite-plus/test';
+import { createSsrRouter } from 'void/pages-client';
+import type { LinkActiveMatch, LinkStatus, NavigationState } from 'void/pages-client';
+import { createSSRApp, reactive, ref, watch } from 'vue';
+import { useLinkStatus } from '../../src/runtime/use-link-status.ts';
+
+it('tracks a destination ref and options supplied by a getter', () => {
+ const app = createSSRApp({});
+ app.provide('__void_router', createSsrRouter('/posts/first'));
+ const href = ref('/posts/first');
+ const activeMatch = ref('exact');
+ const status = app.runWithContext(() =>
+ useLinkStatus(href, () => ({ activeMatch: activeMatch.value })),
+ );
+ expect(status.value).toEqual({ active: true, current: true, pending: false });
+ href.value = '/posts';
+ expect(status.value.active).toBe(false);
+ activeMatch.value = 'prefix';
+ expect(status.value).toEqual({ active: true, current: false, pending: false });
+});
+
+it('notifies watchers only when the status changes', () => {
+ const app = createSSRApp({});
+ const router = createSsrRouter('/posts/first');
+ const navigation = reactive({ state: 'idle', location: null, method: null });
+ app.provide('__void_router', router);
+ app.provide('__void_navigation', navigation);
+ const href = ref('/about');
+ const status = app.runWithContext(() => useLinkStatus(href));
+ const seen: Array = [];
+ watch(status, (value) => seen.push(value), { flush: 'sync' });
+
+ const initial = status.value;
+ href.value = '/contact';
+ Object.assign(navigation, {
+ state: 'loading',
+ location: new URL('/posts', router.url),
+ method: 'GET',
+ });
+ expect(status.value).toBe(initial);
+ expect(seen).toEqual([]);
+
+ navigation.location = new URL('/contact', router.url);
+ expect(seen).toEqual([{ current: false, active: false, pending: true }]);
+});
diff --git a/playground/react-pages/pages/link-behavior.tsx b/playground/react-pages/pages/link-behavior.tsx
index 09888b43b1..5ca085e355 100644
--- a/playground/react-pages/pages/link-behavior.tsx
+++ b/playground/react-pages/pages/link-behavior.tsx
@@ -1,4 +1,4 @@
-import { Link, useNavigation, useRouter } from '@void/react';
+import { Link, useLinkStatus, useNavigation, useRouter } from '@void/react';
import { useEffect, useRef, useState } from 'react';
import type { Props } from './link-behavior.server.ts';
@@ -22,6 +22,7 @@ export default function LinkBehaviorPage({ title, absoluteUrl, protocolRelativeU
}, []);
const router = useRouter();
+ const postStatus = useLinkStatus('/link-behavior', { method: 'post' });
const navigation = useNavigation();
const previousNavigationState = useRef(navigation.state);
const abortTestCleanupRef = useRef<() => void>(() => {});
@@ -154,9 +155,9 @@ export default function LinkBehaviorPage({ title, absoluteUrl, protocolRelativeU
-
+
- Post to this page
+ {({ pending }) => (pending ? 'Submitting…' : 'Post to this page')}
diff --git a/playground/solid-pages/pages/link-behavior.tsx b/playground/solid-pages/pages/link-behavior.tsx
index d56c67f73c..64be239068 100644
--- a/playground/solid-pages/pages/link-behavior.tsx
+++ b/playground/solid-pages/pages/link-behavior.tsx
@@ -1,4 +1,4 @@
-import { Link, useRouter } from '@void/solid';
+import { Link, useLinkStatus, useRouter } from '@void/solid';
import { ErrorBoundary, createSignal } from 'solid-js';
import type { Props } from './link-behavior.server.ts';
@@ -19,6 +19,7 @@ function setBoundClicked(label: string, event: MouseEvent) {
export default function LinkBehaviorPage(props: Props) {
const router = useRouter();
+ const postStatus = useLinkStatus('/link-behavior', { method: 'post' });
const [prefetchMethod, setPrefetchMethod] = createSignal<'GET' | 'POST'>('GET');
const [reloadMethod, setReloadMethod] = createSignal<'GET' | 'POST'>('GET');
@@ -108,9 +109,9 @@ export default function LinkBehaviorPage(props: Props) {
-
+
- Post to this page
+ {({ pending }) => (pending ? 'Submitting…' : 'Post to this page')}
diff --git a/playground/svelte-pages/pages/link-behavior.svelte b/playground/svelte-pages/pages/link-behavior.svelte
index 8c2eb40cad..15ff913bac 100644
--- a/playground/svelte-pages/pages/link-behavior.svelte
+++ b/playground/svelte-pages/pages/link-behavior.svelte
@@ -1,5 +1,5 @@