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

link.tsx

635 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 = (e.currentTarget as HTMLAnchorElement).target
247 const effectiveTarget = target !== undefined ? target : elementTarget
248​
249 if (
250 !disabled &&
251 !isCtrlEvent(e) &&
252 !e.defaultPrevented &&
253 (!effectiveTarget || effectiveTarget === '_self') &&
254 e.button === 0
255 ) {
256 e.preventDefault()
257​
258 flushSync(() => {
259 setIsTransitioning(true)
260 })
261​
262 const unsub = router.subscribe('onResolved', () => {
263 unsub()
264 setIsTransitioning(false)
265 })
266​
267 // All is well? Navigate!
268 // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing
269 router.navigate({
270 ..._options,
271 replace,
272 resetScroll,
273 hashScrollIntoView,
274 startTransition,
275 viewTransition,
276 ignoreBlocker,
277 })
278 }
279 }
280​
281 if (externalLink) {
282 return {
283 ...propsSafeToSpread,
284 ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],
285 href: externalLink,
286 ...(children && { children }),
287 ...(target && { target }),
288 ...(disabled && { disabled }),
289 ...(style && { style }),
290 ...(className && { className }),
291 ...(onClick && { onClick }),
292 ...(onFocus && { onFocus }),
293 ...(onMouseEnter && { onMouseEnter }),
294 ...(onMouseLeave && { onMouseLeave }),
295 ...(onTouchStart && { onTouchStart }),
296 }
297 }
298​
299 // The click handler
300 const handleFocus = (_: React.MouseEvent) => {
301 if (disabled) return
302 if (preload) {
303 doPreload()
304 }
305 }
306​
307 const handleTouchStart = handleFocus
308​
309 const handleEnter = (e: React.MouseEvent) => {
310 if (disabled || !preload) return
311​
312 if (!preloadDelay) {
313 doPreload()
314 } else {
315 const eventTarget = e.target
316 if (timeoutMap.has(eventTarget)) {
317 return
318 }
319 const id = setTimeout(() => {
320 timeoutMap.delete(eventTarget)
321 doPreload()
322 }, preloadDelay)
323 timeoutMap.set(eventTarget, id)
324 }
325 }
326​
327 const handleLeave = (e: React.MouseEvent) => {
328 if (disabled || !preload || !preloadDelay) return
329 const eventTarget = e.target
330 const id = timeoutMap.get(eventTarget)
331 if (id) {
332 clearTimeout(id)
333 timeoutMap.delete(eventTarget)
334 }
335 }
336​
337 // Get the active props
338 const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = isActive
339 ? (functionalUpdate(activeProps as any, {}) ?? STATIC_ACTIVE_OBJECT)
340 : STATIC_EMPTY_OBJECT
341​
342 // Get the inactive props
343 const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> =
344 isActive
345 ? STATIC_EMPTY_OBJECT
346 : (functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT)
347​
348 const resolvedClassName = [
349 className,
350 resolvedActiveProps.className,
351 resolvedInactiveProps.className,
352 ]
353 .filter(Boolean)
354 .join(' ')
355​
356 const resolvedStyle = (style ||
357 resolvedActiveProps.style ||
358 resolvedInactiveProps.style) && {
359 ...style,
360 ...resolvedActiveProps.style,
361 ...resolvedInactiveProps.style,
362 }
363​
364 return {
365 ...propsSafeToSpread,
366 ...resolvedActiveProps,
367 ...resolvedInactiveProps,
368 href: hrefOption?.href,
369 ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'],
370 onClick: composeHandlers([onClick, handleClick]),
371 onFocus: composeHandlers([onFocus, handleFocus]),
372 onMouseEnter: composeHandlers([onMouseEnter, handleEnter]),
373 onMouseLeave: composeHandlers([onMouseLeave, handleLeave]),
374 onTouchStart: composeHandlers([onTouchStart, handleTouchStart]),
375 disabled: !!disabled,
376 target,
377 ...(resolvedStyle && { style: resolvedStyle }),
378 ...(resolvedClassName && { className: resolvedClassName }),
379 ...(disabled && STATIC_DISABLED_PROPS),
380 ...(isActive && STATIC_ACTIVE_PROPS),
381 ...(isTransitioning && STATIC_TRANSITIONING_PROPS),
382 }
384​
385const STATIC_EMPTY_OBJECT = {}
386const STATIC_ACTIVE_OBJECT = { className: 'active' }
387const STATIC_DISABLED_PROPS = { role: 'link', 'aria-disabled': true }
388const STATIC_ACTIVE_PROPS = { 'data-status': 'active', 'aria-current': 'page' }
389const STATIC_TRANSITIONING_PROPS = { 'data-transitioning': 'transitioning' }
390​
391const timeoutMap = new WeakMap<EventTarget, ReturnType<typeof setTimeout>>()
392​
393const intersectionObserverOptions: IntersectionObserverInit = {
394 rootMargin: '100px',
396​
397const composeHandlers =
398 (handlers: Array<undefined | React.EventHandler<any>>) =>
399 (e: React.SyntheticEvent) => {
400 for (const handler of handlers) {
401 if (!handler) continue
402 if (e.defaultPrevented) return
403 handler(e)
404 }
405 }
406​
407type UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements
408 ? React.JSX.IntrinsicElements[TComp]
409 : TComp extends React.ComponentType<any>
410 ? React.ComponentPropsWithoutRef<TComp> &
411 React.RefAttributes<React.ComponentRef<TComp>>
412 : never
413​
414export type UseLinkPropsOptions<
415 TRouter extends AnyRouter = RegisteredRouter,
416 TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
417 TTo extends string | undefined = '.',
418 TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
419 TMaskTo extends string = '.',
420> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
421 UseLinkReactProps<'a'>
422​
423export type ActiveLinkOptions<
424 TComp = 'a',
425 TRouter extends AnyRouter = RegisteredRouter,
426 TFrom extends string = string,
427 TTo extends string | undefined = '.',
428 TMaskFrom extends string = TFrom,
429 TMaskTo extends string = '.',
430> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
431 ActiveLinkOptionProps<TComp>
432​
433type ActiveLinkProps<TComp> = Partial<
434 LinkComponentReactProps<TComp> & {
435 [key: `data-${string}`]: unknown
436 }
438​
439export interface ActiveLinkOptionProps<TComp = 'a'> {
440 /**
441 * A function that returns additional props for the `active` state of this link.
442 * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)
443 */
444 activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
445 /**
446 * A function that returns additional props for the `inactive` state of this link.
447 * These props override other props passed to the link (`style`'s are merged, `className`'s are concatenated)
448 */
449 inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
451​
452export type LinkProps<
453 TComp = 'a',
454 TRouter extends AnyRouter = RegisteredRouter,
455 TFrom extends string = string,
456 TTo extends string | undefined = '.',
457 TMaskFrom extends string = TFrom,
458 TMaskTo extends string = '.',
459> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
460 LinkPropsChildren
461​
462export interface LinkPropsChildren {
463 // 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
464 children?:
465 | React.ReactNode
466 | ((state: {
467 isActive: boolean
468 isTransitioning: boolean
469 }) => React.ReactNode)
471​
472type LinkComponentReactProps<TComp> = Omit<
473 UseLinkReactProps<TComp>,
474 keyof CreateLinkProps
476​
477export type LinkComponentProps<
478 TComp = 'a',
479 TRouter extends AnyRouter = RegisteredRouter,
480 TFrom extends string = string,
481 TTo extends string | undefined = '.',
482 TMaskFrom extends string = TFrom,
483 TMaskTo extends string = '.',
484> = LinkComponentReactProps<TComp> &
485 LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
486​
487export type CreateLinkProps = LinkProps<
488 any,
489 any,
490 string,
491 string,
492 string,
493 string
495​
496export type LinkComponent<
497 in out TComp,
498 in out TDefaultFrom extends string = string,
499> = <
500 TRouter extends AnyRouter = RegisteredRouter,
501 const TFrom extends string = TDefaultFrom,
502 const TTo extends string | undefined = undefined,
503 const TMaskFrom extends string = TFrom,
504 const TMaskTo extends string = '',
505>(
506 props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
507) => React.ReactElement
508​
509export interface LinkComponentRoute<
510 in out TDefaultFrom extends string = string,
511> {
512 defaultFrom: TDefaultFrom
513 <
514 TRouter extends AnyRouter = RegisteredRouter,
515 const TTo extends string | undefined = undefined,
516 const TMaskTo extends string = '',
517 >(
518 props: LinkComponentProps<
519 'a',
520 TRouter,
521 this['defaultFrom'],
522 TTo,
523 this['defaultFrom'],
524 TMaskTo
525 >,
526 ): React.ReactElement
528​
529/**
530 * Creates a typed Link-like component that preserves TanStack Router's
531 * navigation semantics and type-safety while delegating rendering to the
532 * provided host component.
533 *
534 * Useful for integrating design system anchors/buttons while keeping
535 * router-aware props (eg. `to`, `params`, `search`, `preload`).
536 *
537 * @param Comp The host component to render (eg. a design-system Link/Button)
538 * @returns A router-aware component with the same API as `Link`.
539 * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-link
540 */
541export function createLink<const TComp>(
542 Comp: Constrain<TComp, any, (props: CreateLinkProps) => ReactNode>,
543): LinkComponent<TComp> {
544 return React.forwardRef(function CreatedLink(props, ref) {
545 return <Link {...(props as any)} _asChild={Comp} ref={ref} />
546 }) as any
548​
549/**
550 * A strongly-typed anchor component for declarative navigation.
551 * Handles path, search, hash and state updates with optional route preloading
552 * and active-state styling.
553 *
554 * Props:
555 * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false)
556 * - `preloadDelay`: Delay in ms before preloading on hover
557 * - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive
558 * - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation
559 * - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation
560 * - `ignoreBlocker`: Bypass registered blockers
561 *
562 * @returns An anchor-like element that navigates without full page reloads.
563 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent
564 */
565export const Link: LinkComponent<'a'> = React.forwardRef<Element, any>(
566 (props, ref) => {
567 const { _asChild, ...rest } = props
568 const {
569 type: _type,
570 ref: innerRef,
571 ...linkProps
572 } = useLinkProps(rest as any, ref)
573​
574 const children =
575 typeof rest.children === 'function'
576 ? rest.children({
577 isActive: (linkProps as any)['data-status'] === 'active',
578 })
579 : rest.children
580​
581 if (_asChild === undefined) {
582 // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop
583 // @ts-expect-error
584 delete linkProps.disabled
585 }
586​
587 return React.createElement(
588 _asChild ? _asChild : 'a',
589 {
590 ...linkProps,
591 ref: innerRef,
592 },
593 children,
594 )
595 },
596) as any
597​
598function isCtrlEvent(e: React.MouseEvent) {
599 return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
601​
602export type LinkOptionsFnOptions<
603 TOptions,
604 TComp,
605 TRouter extends AnyRouter = RegisteredRouter,
606> =
607 TOptions extends ReadonlyArray<any>
608 ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>
609 : ValidateLinkOptions<TRouter, TOptions, string, TComp>
610​
611export type LinkOptionsFn<TComp> = <
612 const TOptions,
613 TRouter extends AnyRouter = RegisteredRouter,
614>(
615 options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,
616) => TOptions
617​
618/**
619 * Validate and reuse navigation options for `Link`, `navigate` or `redirect`.
620 * Accepts a literal options object and returns it typed for later spreading.
621 * @example
622 * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
623 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
624 */
625export const linkOptions: LinkOptionsFn<'a'> = (options) => {
626 return options as any
628​
629/**
630 * Type-check a literal object for use with `Link`, `navigate` or `redirect`.
631 * Use to validate and reuse navigation options across your app.
632 * @example
633 * const opts = linkOptions({ to: '/dashboard', search: { tab: 'home' } })
634 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkOptions
635 */