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] + + + +``` + +```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()} ) : ( )} 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())}