Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

link.tsx

637 lines18.1 KB

1import * as React from 'react'
2import { flushSync } from 'react-dom'
3import {
4 deepEqual,
5 exactPathTest,
6 functionalUpdate,
7 preloadWarning,
8 removeTrailingSlash,
9} from '@tanstack/router-core'
10import { useRouterState } from './useRouterState'
11import { useRouter } from './useRouter'
12​
13import { useForwardedRef, useIntersectionObserver } from './utils'
14​
15import type {
16 AnyRouter,
17 Constrain,
18 LinkOptions,
19 RegisteredRouter,
20 RoutePaths,
21} from '@tanstack/router-core'
22import type { ReactNode } from 'react'
23import type {
24 ValidateLinkOptions,
25 ValidateLinkOptionsArray,
26} from './typePrimitives'
27​
28/**
29 * Build anchor-like props for declarative navigation and preloading.
30 *
31 * Returns stable `href`, event handlers and accessibility props derived from
32 * router options and active state. Used internally by `Link` and custom links.
33 *
34 * Options cover `to`, `params`, `search`, `hash`, `state`, `preload`,
35 * `activeProps`, `inactiveProps`, and more.
36 *
37 * @returns React anchor props suitable for `<a>` or custom components.
38 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLinkPropsHook
39 */
40export function useLinkProps<
41 TRouter extends AnyRouter = RegisteredRouter,
42 const TFrom extends string = string,
43 const TTo extends string | undefined = undefined,
44 const TMaskFrom extends string = TFrom,
45 const TMaskTo extends string = '',
46>(
47 options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
48 forwardedRef?: React.ForwardedRef<Element>,
49): React.ComponentPropsWithRef<'a'> {
50 const router = useRouter()
51 const [isTransitioning, setIsTransitioning] = React.useState(false)
52 const hasRenderFetched = React.useRef(false)
53 const innerRef = useForwardedRef(forwardedRef)
54​
55 const {
56 // custom props
57 activeProps,
58 inactiveProps,
59 activeOptions,
60 to,
61 preload: userPreload,
62 preloadDelay: userPreloadDelay,
63 hashScrollIntoView,
64 replace,
65 startTransition,
66 resetScroll,
67 viewTransition,
68 // element props
69 children,
70 target,
71 disabled,
72 style,
73 className,
74 onClick,
75 onFocus,
76 onMouseEnter,
77 onMouseLeave,
78 onTouchStart,
79 ignoreBlocker,
80 // prevent these from being returned
81 params: _params,
82 search: _search,
83 hash: _hash,
84 state: _state,
85 mask: _mask,
86 reloadDocument: _reloadDocument,
87 unsafeRelative: _unsafeRelative,
88 from: _from,
89 _fromLocation,
90 ...propsSafeToSpread
91 } = options
92​
93 // subscribe to search params to re-build location if it changes
94 const currentSearch = useRouterState({
95 select: (s) => s.location.search,
96 structuralSharing: true as any,
97 })
98​
99 const from = options.from
100​
101 const _options = React.useMemo(
102 () => {
103 return { ...options, from }
104 },
105 // eslint-disable-next-line react-hooks/exhaustive-deps
106 [
107 router,
108 currentSearch,
109 from,
110 options._fromLocation,
111 options.hash,
112 options.to,
113 options.search,
114 options.params,
115 options.state,
116 options.mask,
117 options.unsafeRelative,
118 ],
119 )
120​
121 const next = React.useMemo(
122 () => router.buildLocation({ ..._options } as any),
123 [router, _options],
124 )
125​
126 const hrefOption = React.useMemo(() => {
127 if (disabled) {
128 return undefined
129 }
130 let href = next.maskedLocation ? next.maskedLocation.url : next.url
131​
132 let external = false
133 if (router.origin) {
134 if (href.startsWith(router.origin)) {
135 href = router.history.createHref(href.replace(router.origin, '')) || '/'
136 } else {
137 external = true
138 }
139 }
140 return { href, external }
141 }, [disabled, next.maskedLocation, next.url, router.origin, router.history])
142​
143 const externalLink = React.useMemo(() => {
144 if (hrefOption?.external) {
145 return hrefOption.href
146 }
147 try {
148 new URL(to as any)
149 return to
150 } catch {}
151 return undefined
152 }, [to, hrefOption])
153​
154 const preload =
155 options.reloadDocument || externalLink
156 ? false
157 : (userPreload ?? router.options.defaultPreload)
158 const preloadDelay =
159 userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0
160​
161 const isActive = useRouterState({
162 select: (s) => {
163 if (externalLink) return false
164 if (activeOptions?.exact) {
165 const testExact = exactPathTest(
166 s.location.pathname,
167 next.pathname,
168 router.basepath,
169 )
170 if (!testExact) {
171 return false
172 }
173 } else {
174 const currentPathSplit = removeTrailingSlash(
175 s.location.pathname,
176 router.basepath,
177 )
178 const nextPathSplit = removeTrailingSlash(
179 next.pathname,
180 router.basepath,
181 )
182​
183 const pathIsFuzzyEqual =
184 currentPathSplit.startsWith(nextPathSplit) &&
185 (currentPathSplit.length === nextPathSplit.length ||
186 currentPathSplit[nextPathSplit.length] === '/')
187​
188 if (!pathIsFuzzyEqual) {
189 return false
190 }
191 }
192​
193 if (activeOptions?.includeSearch ?? true) {
194 const searchTest = deepEqual(s.location.search, next.search, {
195 partial: !activeOptions?.exact,
196 ignoreUndefined: !activeOptions?.explicitUndefined,
197 })
198 if (!searchTest) {
199 return false
200 }
201 }
202​
203 if (activeOptions?.includeHash) {
204 return s.location.hash === next.hash
205 }
206 return true
207 },
208 })
209​
210 const doPreload = React.useCallback(() => {
211 router.preloadRoute({ ..._options } as any).catch((err) => {
212 console.warn(err)
213 console.warn(preloadWarning)
214 })
215 }, [router, _options])
216​
217 const preloadViewportIoCallback = React.useCallback(
218 (entry: IntersectionObserverEntry | undefined) => {
219 if (entry?.isIntersecting) {
220 doPreload()
221 }
222 },
223 [doPreload],
224 )
225​
226 useIntersectionObserver(
227 innerRef,
228 preloadViewportIoCallback,
229 intersectionObserverOptions,
230 { disabled: !!disabled || !(preload === 'viewport') },
231 )
232​
233 React.useEffect(() => {
234 if (hasRenderFetched.current) {
235 return
236 }
237 if (!disabled && preload === 'render') {
238 doPreload()
239 hasRenderFetched.current = true
240 }
241 }, [disabled, doPreload, preload])
242​
243 // The click handler
244 const handleClick = (e: React.MouseEvent) => {
245 // Check actual element's target attribute as fallback
246 const elementTarget = (
247 e.currentTarget as HTMLAnchorElement | SVGAElement
248 ).getAttribute('target')
249 const effectiveTarget = target !== undefined ? target : elementTarget
250​
251 if (
252 !disabled &&
253 !isCtrlEvent(e) &&
254 !e.defaultPrevented &&
255 (!effectiveTarget || effectiveTarget === '_self') &&
256 e.button === 0
257 ) {
258 e.preventDefault()
259​
260 flushSync(() => {
261 setIsTransitioning(true)
262 })
263​
264 const unsub = router.subscribe('onResolved', () => {
265 unsub()
266 setIsTransitioning(false)
267 })
268​
269 // All is well? Navigate!
270 // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing
271 router.navigate({
272 ..._options,
273 replace,
274 resetScroll,
275 hashScrollIntoView,
276 startTransition,
277 viewTransition,
278 ignoreBlocker,
279 })
280 }
281 }
282​
283 if (externalLink) {
284 return {
285 ...propsSafeToSpread,
286 ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],
287 href: externalLink,
288 ...(children && { children }),
289 ...(target && { target }),
290 ...(disabled && { disabled }),
291 ...(style && { style }),
292 ...(className && { className }),
293 ...(onClick && { onClick }),
294 ...(onFocus && { onFocus }),
295 ...(onMouseEnter && { onMouseEnter }),
296 ...(onMouseLeave && { onMouseLeave }),
297 ...(onTouchStart && { onTouchStart }),
298 }
299 }
300​
301 // The click handler
302 const handleFocus = (_: React.MouseEvent) => {
303 if (disabled) return
304 if (preload) {
305 doPreload()
306 }
307 }
308​
309 const handleTouchStart = handleFocus
310​
311 const handleEnter = (e: React.MouseEvent) => {
312 if (disabled || !preload) return
313​
314 if (!preloadDelay) {
315 doPreload()
316 } else {
317 const eventTarget = e.target
318 if (timeoutMap.has(eventTarget)) {
319 return
320 }
321 const id = setTimeout(() => {
322 timeoutMap.delete(eventTarget)
323 doPreload()
324 }, preloadDelay)
325 timeoutMap.set(eventTarget, id)
326 }
327 }
328​
329 const handleLeave = (e: React.MouseEvent) => {
330 if (disabled || !preload || !preloadDelay) return
331 const eventTarget = e.target
332 const id = timeoutMap.get(eventTarget)
333 if (id) {
334 clearTimeout(id)
335 timeoutMap.delete(eventTarget)
336 }
337 }
338​
339 // Get the active props
340 const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = isActive
341 ? (functionalUpdate(activeProps as any, {}) ?? STATIC_ACTIVE_OBJECT)
342 : STATIC_EMPTY_OBJECT
343​
344 // Get the inactive props
345 const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> =
346 isActive
347 ? STATIC_EMPTY_OBJECT
348 : (functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT)
349​
350 const resolvedClassName = [
351 className,
352 resolvedActiveProps.className,
353 resolvedInactiveProps.className,
354 ]
355 .filter(Boolean)
356 .join(' ')
357​
358 const resolvedStyle = (style ||
359 resolvedActiveProps.style ||
360 resolvedInactiveProps.style) && {
361 ...style,
362 ...resolvedActiveProps.style,
363 ...resolvedInactiveProps.style,
364 }
365​
366 return {
367 ...propsSafeToSpread,
368 ...resolvedActiveProps,
369 ...resolvedInactiveProps,
370 href: hrefOption?.href,
371 ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],
372 onClick: composeHandlers([onClick, handleClick]),
373 onFocus: composeHandlers([onFocus, handleFocus]),
374 onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),
375 onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),
376 onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),
377 disabled: !!disabled,
378 target,
379 ...(resolvedStyle && { style: resolvedStyle }),
380 ...(resolvedClassName && { className: resolvedClassName }),
381 ...(disabled && STATIC_DISABLED_PROPS),
382 ...(isActive && STATIC_ACTIVE_PROPS),
383 ...(isTransitioning && STATIC_TRANSITIONING_PROPS),
384 }
386​
387const STATIC_EMPTY_OBJECT = {}
388const STATIC_ACTIVE_OBJECT = { className: 'active' }
389const STATIC_DISABLED_PROPS = { role: 'link', 'aria-disabled': true }
390const STATIC_ACTIVE_PROPS = { 'data-status': 'active', 'aria-current': 'page' }
391const STATIC_TRANSITIONING_PROPS = { 'data-transitioning': 'transitioning' }
392​
393const timeoutMap = new WeakMap<EventTarget, ReturnType<typeof setTimeout>>()
394​
395const intersectionObserverOptions: IntersectionObserverInit = {
396 rootMargin: '100px',
398​
399const composeHandlers =
400 (handlers: Array<undefined | React.EventHandler<any>>) =>
401 (e: React.SyntheticEvent) => {
402 for (const handler of handlers) {
403 if (!handler) continue
404 if (e.defaultPrevented) return
405 handler(e)
406 }
407 }
408​
409type UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements
410 ? React.JSX.IntrinsicElements[TComp]
411 : TComp extends React.ComponentType<any>
412 ? React.ComponentPropsWithoutRef<TComp> &
413 React.RefAttributes<React.ComponentRef<TComp>>
414 : never
415​
416export type UseLinkPropsOptions<
417 TRouter extends AnyRouter = RegisteredRouter,
418 TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
419 TTo extends string | undefined = '.',
420 TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
421 TMaskTo extends string = '.',
422> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
423 UseLinkReactProps<'a'>
424​
425export type ActiveLinkOptions<
426 TComp = 'a',
427 TRouter extends AnyRouter = RegisteredRouter,
428 TFrom extends string = string,
429 TTo extends string | undefined = '.',
430 TMaskFrom extends string = TFrom,
431 TMaskTo extends string = '.',
432> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
433 ActiveLinkOptionProps<TComp>
434​
435type ActiveLinkProps<TComp> = Partial<
436 LinkComponentReactProps<TComp> & {
437 [key: `data-${string}`]: unknown
438 }
440​
441export interface ActiveLinkOptionProps<TComp = 'a'> {
442 /**
443 * A function that returns additional props for the `active` state of this link.
444 * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)
445 */
446 activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
447 /**
448 * A function that returns additional props for the `inactive` state of this link.
449 * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)
450 */
451 inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
453​
454export type LinkProps<
455 TComp = 'a',
456 TRouter extends AnyRouter = RegisteredRouter,
457 TFrom extends string = string,
458 TTo extends string | undefined = '.',
459 TMaskFrom extends string = TFrom,
460 TMaskTo extends string = '.',
461> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
462 LinkPropsChildren
463​
464export interface LinkPropsChildren {
465 // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns
466 children?:
467 | React.ReactNode
468 | ((state: {
469 isActive: boolean
470 isTransitioning: boolean
471 }) => React.ReactNode)
473​
474type LinkComponentReactProps<TComp> = Omit<
475 UseLinkReactProps<TComp>,
476 keyof CreateLinkProps
478​
479export type LinkComponentProps<
480 TComp = 'a',
481 TRouter extends AnyRouter = RegisteredRouter,
482 TFrom extends string = string,
483 TTo extends string | undefined = '.',
484 TMaskFrom extends string = TFrom,
485 TMaskTo extends string = '.',
486> = LinkComponentReactProps<TComp> &
487 LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
488​
489export type CreateLinkProps = LinkProps<
490 any,
491 any,
492 string,
493 string,
494 string,
495 string
497​
498export type LinkComponent<
499 in out TComp,
500 in out TDefaultFrom extends string = string,
501> = <
502 TRouter extends AnyRouter = RegisteredRouter,
503 const TFrom extends string = TDefaultFrom,
504 const TTo extends string | undefined = undefined,
505 const TMaskFrom extends string = TFrom,
506 const TMaskTo extends string = '',
507>(
508 props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
509) => React.ReactElement
510​
511export interface LinkComponentRoute<
512 in out TDefaultFrom extends string = string,
513> {
514 defaultFrom: TDefaultFrom
515 <
516 TRouter extends AnyRouter = RegisteredRouter,
517 const TTo extends string | undefined = undefined,
518 const TMaskTo extends string = '',
519 >(
520 props: LinkComponentProps<
521 'a',
522 TRouter,
523 this['defaultFrom'],
524 TTo,
525 this['defaultFrom'],
526 TMaskTo
527 >,
528 ): React.ReactElement
530​
531/**
532 * Creates a typed Link-like component that preserves TanStack Router's
533 * navigation semantics and type-safety while delegating rendering to the
534 * provided host component.
535 *
536 * Useful for integrating design system anchors/buttons while keeping
537 * router-aware props (eg. `to`, `params`, `search`, `preload`).
538 *
539 * @param Comp The host component to render (eg. a design-system Link/Button)
540 * @returns A router-aware component with the same API as `Link`.
541 * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-link
542 */
543export function createLink<const TComp>(
544 Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>,
545): LinkComponent<TComp> {
546 return React.forwardRef(function CreatedLink(props, ref) {
547 return <Link {...(props as any)} _asChild={Comp} ref={ref} />
548 }) as any
550​
551/**
552 * A strongly-typed anchor component for declarative navigation.
553 * Handles path, search, hash and state updates with optional route preloading
554 * and active-state styling.
555 *
556 * Props:
557 * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)
558 * - `preloadDelay`: Delay in ms before preloading on hover
559 * - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive
560 * - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation
561 * - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation
562 * - `ignoreBlocker`: Bypass registered blockers
563 *
564 * @returns An anchor-like element that navigates without full page reloads.
565 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent
566 */
567export const Link: LinkComponent<'a'> = React.forwardRef<Element, any>(
568 (props, ref) => {
569 const { _asChild, ...rest } = props
570 const {
571 type: _type,
572 ref: innerRef,
573 ...linkProps
574 } = useLinkProps(rest as any, ref)
575​
576 const children =
577 typeof rest.children === 'function'
578 ? rest.children({
579 isActive: (linkProps as any)['data-status'] === 'active',
580 })
581 : rest.children
582​
583 if (_asChild === undefined) {
584 // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop
585 // @ts-expect-error
586 delete linkProps.disabled
587 }
588​
589 return React.createElement(
590 _asChild ? _asChild : 'a',
591 {
592 ...linkProps,
593 ref: innerRef,
594 },
595 children,
596 )
597 },
598) as any
599​
600function isCtrlEvent(e: React.MouseEvent) {
601 return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
603​
604export type LinkOptionsFnOptions<
605 TOptions,
606 TComp,
607 TRouter extends AnyRouter = RegisteredRouter,
608> =
609 TOptions extends ReadonlyArray<any>
610 ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>
611 : ValidateLinkOptions<TRouter, TOptions, string, TComp>
612​
613export type LinkOptionsFn<TComp> = <
614 const TOptions,
615 TRouter extends AnyRouter = RegisteredRouter,
616>(
617 options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,
618) => TOptions
619​
620/**
621 * Validate and reuse navigation options for `Link`, `navigate` or `redirect`.
622 * Accepts a literal options object and returns it typed for later spreading.
623 * @example
624 * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
625 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
626 */
627export const linkOptions: LinkOptionsFn<'a'> = (options) => {
628 return options as any
630​
631/**
632 * Type-check a literal object for use with `Link`, `navigate` or `redirect`.
633 * Use to validate and reuse navigation options across your app.
634 * @example
635 * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
636 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
637 */