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..b964c0448 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, + 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 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( + () => resolvedLinkStatus(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 000000000..6d0913132 --- /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 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..4e28edcc1 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, + 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 +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,16 @@ 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), + 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() { + const children = local.children; + return typeof children === 'function' ? children(status()) : children; + } function doPrefetch() { prefetchLink(router, link().href, local.cacheFor); @@ -181,13 +206,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..e8c3c3531 100644 --- a/packages/solid/test/integration/use-params-navigation.test.ts +++ b/packages/solid/test/integration/use-params-navigation.test.ts @@ -18,20 +18,29 @@ 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); + 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())}