From f2ea1feefff720e23a3738fee4f4dd70905118cb Mon Sep 17 00:00:00 2001 From: karthic Date: Thu, 26 Nov 2026 11:09:26 +0530 Subject: [PATCH 1/3] feat(pages): expose current, active, and pending link status --- docs/guide/pages-routing/overview.md | 30 ++++ docs/reference/api/pages.md | 29 +++ packages/react/src/runtime/index.ts | 4 +- packages/react/src/runtime/link.tsx | 53 +++--- packages/react/test/unit/link.test.ts | 40 ++++- packages/solid/src/runtime/index.ts | 4 +- packages/solid/src/runtime/link.tsx | 48 +++-- .../integration/use-params-navigation.test.ts | 10 +- packages/svelte/src/runtime/Link.svelte | 19 +- packages/svelte/src/runtime/index.ts | 2 + packages/svelte/src/runtime/link-props.ts | 4 +- .../src/runtime/use-link-status.svelte.ts | 31 ++++ .../integration/use-params-navigation.test.ts | 14 +- packages/void/skills/void/SKILL.md | 8 +- packages/void/src/pages/client.ts | 7 + packages/void/src/pages/link.ts | 166 ++++++++++++------ packages/void/test/unit/pages-link.test.ts | 55 ++++++ packages/vue/src/runtime/index.ts | 2 + packages/vue/src/runtime/link.ts | 27 +-- packages/vue/src/runtime/use-link-status.ts | 14 ++ .../vue/test/unit/use-link-status.test.ts | 20 +++ .../react-pages/pages/link-behavior.tsx | 7 +- .../solid-pages/pages/link-behavior.tsx | 7 +- .../svelte-pages/pages/link-behavior.svelte | 11 +- playground/vue-pages/pages/link-behavior.vue | 9 +- test/pages-client-contract.ts | 5 + 26 files changed, 482 insertions(+), 144 deletions(-) create mode 100644 packages/svelte/src/runtime/use-link-status.svelte.ts create mode 100644 packages/vue/src/runtime/use-link-status.ts create mode 100644 packages/vue/test/unit/use-link-status.test.ts diff --git a/docs/guide/pages-routing/overview.md b/docs/guide/pages-routing/overview.md index 5667d48c1..b767a6496 100644 --- a/docs/guide/pages-routing/overview.md +++ b/docs/guide/pages-routing/overview.md @@ -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] +{({ 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 390670498..75927c605 100644 --- a/docs/reference/api/pages.md +++ b/docs/reference/api/pages.md @@ -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: diff --git a/packages/react/src/runtime/index.ts b/packages/react/src/runtime/index.ts index 2b973455d..3092c75ef 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 { useLinkStatus, Link } from './link.tsx'; export { useRouter } from './use-router.ts'; export { useParams } from './use-params.ts'; export { useShared } from './use-shared.ts'; @@ -25,4 +25,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 5294d8d0d..29a8e920b 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,42 @@ 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, 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 useMemo( + () => getLinkStatus(router, navigation, href, { method, data, activeMatch }), + [activeMatch, data, href, method, navigation, router], + ); +} + export function Link({ href, method = 'GET', @@ -72,15 +89,11 @@ 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 = useMemo( + () => resolvedLinkStatus(router, navigation, link, activeMatch), + [activeMatch, link, navigation, router], ); + const attributes = linkStatusAttributes(status); const hoverDelay = router?._hoverDelay ?? 75; const doPrefetch = useCallback( @@ -245,18 +258,18 @@ export function Link({ [style], ); + const content = typeof children === 'function' ? children(status) : children; if (link.isGet) { return ( - {children} + {content} ); } @@ -266,11 +279,11 @@ export function Link({ ref={setElementRef} type="button" style={resolvedStyle} - {...pendingAttributes} + {...attributes} {...rest} {...eventHandlers} > - {children} + {content} ); } diff --git a/packages/react/test/unit/link.test.ts b/packages/react/test/unit/link.test.ts index 55b1a77fa..96cffa380 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 6bdc27bf9..a30f2cba3 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 { 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'; @@ -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'; diff --git a/packages/solid/src/runtime/link.tsx b/packages/solid/src/runtime/link.tsx index 67ad1e8d4..ab16a44fc 100644 --- a/packages/solid/src/runtime/link.tsx +++ b/packages/solid/src/runtime/link.tsx @@ -1,19 +1,20 @@ 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, + 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'; type CommonProps = BaseLinkProps & { - children?: JSX.Element; + children?: JSX.Element | ((status: LinkStatus) => JSX.Element); }; export type LinkProps = CommonProps & @@ -41,6 +42,22 @@ 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, + ), + ); +} + export function Link(props: LinkProps): JSX.Element { const [local, rest] = splitProps(props, [ 'href', @@ -72,12 +89,14 @@ 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(() => + resolvedLinkStatus(router, navigation?.(), link(), local.activeMatch), ); - // Calling navigation() tracks visits as they start and end. - const pendingAttributes = createMemo(() => linkPendingAttributes(router, navigation?.(), link())); + const attributes = createMemo(() => linkStatusAttributes(status())); + function content() { + const children = local.children; + return typeof children === 'function' ? children(status()) : children; + } function doPrefetch() { prefetchLink(router, link().href, local.cacheFor); @@ -181,13 +200,12 @@ export function Link(props: LinkProps): JSX.Element { el = r; }} href={link().href} - {...activeAttributes()} - {...pendingAttributes()} + {...attributes()} {...rest} style={resolvedStyle()} {...eventHandlers()} > - {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 8fc337b00..eabd5dd07 100644 --- a/packages/solid/test/integration/use-params-navigation.test.ts +++ b/packages/solid/test/integration/use-params-navigation.test.ts @@ -18,11 +18,12 @@ export default function Post(props) { ; }`; -const LAYOUT = `import { useParams, useRouter } from "@void/solid"; +const LAYOUT = `import { Link, useLinkStatus, useParams, useRouter } from "@void/solid"; import { createEffect, createSignal } from "solid-js"; 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); createEffect(() => { @@ -30,6 +31,8 @@ export default function Layout(props) { setObserved(values => [...values, slug ?? null]); }); return
+ {String(status().current)} + {({ active }) => active ? "Posts section" : "Other section"}

{params.slug}

{JSON.stringify(observed())}