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()} ) : ( - {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())} { await router.refresh(); setRefreshes(count => count + 1); @@ -116,6 +125,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 +136,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 +148,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 +158,11 @@ 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([]); } finally { await server.close(); await browser.close(); diff --git a/packages/svelte/src/runtime/Link.svelte b/packages/svelte/src/runtime/Link.svelte index 79b48a408..fdabba86e 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 b184b7be4..449ff58e9 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -95,11 +95,9 @@ 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`, and + `data-void-pending`. Use `useLinkStatus()` for surrounding UI or read status from + `Link` children. 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 42dc7284f..19eed79e0 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, + resolvedLinkStatus, 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 a24c2086b..6b9d44158 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,131 @@ export function linkPrefetchStrategies( return prefetch; } -/** - * Marks a GET link to 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. - */ -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 {}; - } +type ActiveMatch = 'current' | 'ancestor' | undefined; +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 - * 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. - */ -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 resolvedLinkStatus(router, navigation, resolveLink({ href, method, data }), activeMatch); +} + +export function resolvedLinkStatus( + 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); + const active = current && target && link.isGet ? matchActive(current, target, match) : undefined; + return { + current: active === 'current', + active: active !== undefined, + pending: !!target && 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. */ +export function isLinkPending( + router: VoidRouter | null | undefined, + navigation: NavigationState | null | undefined, + href: Href, + { method, data }: LinkStatusOptions = {}, +): boolean { + return pendingForLink(router, navigation, resolveLink({ href, method, data })); +} + +function pendingForLink( + router: VoidRouter | null | undefined, + navigation: NavigationState | null | undefined, + link: ResolvedLink, +): boolean { + const target = router && navigation?.location && resolveSameOrigin(link.href, router.url); + return !!target && matchPending(navigation, link.method, target); +} + +/** 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; +} - return {}; +export function linkActiveAttributes( + router: VoidRouter | null | undefined, + link: ResolvedLink, + match?: LinkActiveMatch, +): LinkActiveAttributes { + return linkStatusAttributes(resolvedLinkStatus(router, null, link, match)); +} + +export function linkPendingAttributes( + router: VoidRouter | null | undefined, + navigation: NavigationState | null | undefined, + link: ResolvedLink, +): LinkPendingAttributes { + return pendingForLink(router, navigation, link) ? { '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 b69860fb7..0f45c933d 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 36298c9cd..1c310e2a5 100644 --- a/packages/vue/src/runtime/index.ts +++ b/packages/vue/src/runtime/index.ts @@ -4,6 +4,8 @@ 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'; diff --git a/packages/vue/src/runtime/link.ts b/packages/vue/src/runtime/link.ts index c1a82f1b4..0fb0a2214 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, + resolvedLinkStatus, 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 = resolvedLinkStatus(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 000000000..b4d08c2ab --- /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/use-link-status.test.ts b/packages/vue/test/unit/use-link-status.test.ts new file mode 100644 index 000000000..e96339aea --- /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 09888b43b..5ca085e35 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 d56c67f73..64be23906 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 8c2eb40ca..f765d58b2 100644 --- a/playground/svelte-pages/pages/link-behavior.svelte +++ b/playground/svelte-pages/pages/link-behavior.svelte @@ -1,5 +1,5 @@
{params.slug}
{status.current}/{status.active}/{status.pending}
+
- Post to this page + {({ pending }) => (pending ? 'Submitting…' : 'Post to this page')}