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

link.tsx

714 lines21.0 KB

1import * as Solid from 'solid-js'
2​
3import {
4 _isRouteDeparting,
5 deepEqual,
6 functionalUpdate,
7 getUrlScheme,
8 hasKeys,
9 isDangerousProtocol,
10 preloadWarning,
11 removeTrailingSlash,
12} from '@tanstack/router-core'
13​
14import { isServer } from '@tanstack/router-core/isServer'
15import { Dynamic } from 'solid-js/web'
16import { useRouter } from './useRouter'
17import { nearestMatchContext } from './matchContext'
18​
19import { useIntersectionObserver } from './utils'
20​
21import { useHydrated } from './ClientOnly'
22import type {
23 AnyRouter,
24 Constrain,
25 LinkOptions,
26 ParsedLocation,
27 RegisteredRouter,
28 RoutePaths,
29} from '@tanstack/router-core'
30import type {
31 ValidateLinkOptions,
32 ValidateLinkOptionsArray,
33} from './typePrimitives'
34​
35export function useLinkProps<
36 TRouter extends AnyRouter = RegisteredRouter,
37 TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
38 TTo extends string = '',
39 TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
40 TMaskTo extends string = '',
41>(
42 options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
43): Solid.ComponentProps<'a'> {
44 return createLinkProps(options as any, LINK_OPTION_KEYS)
46​
47// `ownKeys` are the options that never reach the element.
48function createLinkProps(
49 options: UseLinkPropsOptions,
50 ownKeys: ReadonlyArray<string>,
51): Solid.ComponentProps<'a'> {
52 const router = useRouter()
53 // Options are read directly: one props proxy, no merged-default getters.
54 const [, propsSafeToSpread] = Solid.splitProps(
55 options,
56 ownKeys as Array<keyof typeof options>,
57 )
58​
59 // A live match never changes route, so read it once without tracking.
60 const routeId = Solid.useContext(nearestMatchContext)[0 /* routeId */]()
61​
62 // While a publishing navigation leaves the Link's route, keep the location
63 // the route still presents so the Link does no work. The route unmounts
64 // when that navigation commits, and any other outcome publishes a newer
65 // location. Compare by identity: a same-href navigation can change state.
66 // The server renders one location: no reactivity there.
67 const currentLocation =
68 (isServer ?? router.isServer)
69 ? () => router.stores.location.get()
70 : Solid.createMemo((prev?: ParsedLocation) => {
71 const location = router.stores.location.get()
72 return prev && _isRouteDeparting(router, routeId, location)
73 ? prev
74 : location
75 })
76​
77 // The Link's own destination options, replaced only when a destination prop
78 // changes: the router reuses a location built from the same object without
79 // reading the current location. A Solid store changes in place, so a store
80 // prop value (checked one level deep, not nested) gets a fresh object per
81 // location instead, re-reading the store at each navigation as before. A
82 // mask holds destination options of its own, so its values are checked too.
83 const getDest = () => {
84 const dest: any = {}
85 for (const key of NAVIGATION_KEYS) {
86 const value = (dest[key] = (options as any)[key])
87 if (
88 isStore(value) ||
89 (key === 'mask' && value && Object.values(value).some(isStore))
90 ) {
91 currentLocation()
92 }
93 }
94 return dest
95 }
96 const dest =
97 (isServer ?? router.isServer) ? getDest : Solid.createMemo(getDest)
98​
99 // Only a hydrating client renders the server's hash-less active state first.
100 const hasHydrated =
101 !(isServer ?? router.isServer) && router.options.ssr
102 ? useHydrated()
103 : undefined
104​
105 // Everything the Link derives from its destination and the location, in
106 // one computation: [element href, external href (null when blocked),
107 // active]. An unchanged result keeps its identity, so a navigation that
108 // leaves the Link as it was notifies nothing downstream.
109 const getLinkState = (prev?: LinkState): LinkState => {
110 const location = currentLocation()
111 const to = options.to
112 const disabled = options.disabled
113 const scheme = typeof to === 'string' && getUrlScheme(to)
114 let href: string | undefined
115 let external: string | null | undefined
116 let active = false
117 if (scheme) {
118 if (router.protocolAllowlist.has(scheme)) {
119 external = to
120 } else {
121 if (process.env.NODE_ENV !== 'production') {
122 console.warn(`Blocked Link with dangerous protocol: ${to}`)
123 }
124 external = null
125 }
126 } else {
127 const options_ = dest()
128 // Clicks and preloads go where the href points.
129 options_._fromLocation = location
130 // untrack because router-core will also access stores, which are signals in solid
131 const next = Solid.untrack(() => router.buildLocation(options_))
132 if (!disabled) {
133 // Use publicHref - it contains the correct href for display
134 // When a rewrite changes the origin, publicHref is the full URL
135 // Otherwise it's the origin-stripped path
136 // This avoids constructing URL objects in the hot path
137 const shown = next.maskedLocation ?? next
138 const publicHref = shown.publicHref
139 const shownHref = shown.external
140 ? publicHref
141 : router.history.createHref(publicHref) || '/'
142 if (
143 (shown.external || shownHref !== publicHref) &&
144 isDangerousProtocol(shownHref, router.protocolAllowlist)
145 ) {
146 if (process.env.NODE_ENV !== 'production') {
147 console.warn(`Blocked Link with dangerous protocol: ${shownHref}`)
148 }
149 } else {
150 href = shownHref
151 }
152 }
153 external =
154 !href && !disabled
155 ? null
156 : href && getUrlScheme(href)
157 ? href
158 : undefined
159 if (external === undefined) {
160 const activeOptions = options.activeOptions
161 const currentPath = removeTrailingSlash(
162 location.pathname,
163 router.basepath,
164 )
165 const nextPath = removeTrailingSlash(next.pathname, router.basepath)
166 // Both modes compare normalized paths; fuzzy matches need a segment boundary.
167 active =
168 (activeOptions?.exact
169 ? currentPath === nextPath
170 : currentPath.startsWith(nextPath) &&
171 (currentPath.length === nextPath.length ||
172 currentPath[nextPath.length] === '/')) &&
173 (!(activeOptions?.includeSearch ?? true) ||
174 deepEqual(
175 location.search,
176 next.search,
177 !activeOptions?.exact,
178 activeOptions?.explicitUndefined,
179 )) &&
180 (!activeOptions?.includeHash ||
181 (hasHydrated && !hasHydrated() ? '' : location.hash) === next.hash)
182 }
183 }
184 href = external === null ? undefined : external || href
185 return prev &&
186 prev[0 /* href */] === href &&
187 prev[1 /* external */] === external &&
188 prev[2 /* active */] === active
189 ? prev
190 : [href, external, active]
191 }
192 const linkState =
193 (isServer ?? router.isServer)
194 ? getLinkState
195 : Solid.createMemo(getLinkState)
196​
197 type ResolvedLinkStateProps = Omit<Solid.ComponentProps<'a'>, 'style'> & {
198 style?: Solid.JSX.CSSProperties
199 }
200​
201 const resolveLinkStateProps = (
202 [href, external, active]: LinkState,
203 base: Solid.ComponentProps<'a'> & { disabled?: boolean },
204 ) => {
205 const disabled = options.disabled || external === null
206 base.href = href
207 base.disabled = disabled
208 base.target = options.target
209 if (disabled) {
210 Object.assign(base, STATIC_DISABLED_PROPS)
211 }
212​
213 if (
214 options.activeProps === undefined &&
215 options.inactiveProps === undefined &&
216 options.class === undefined &&
217 options.style === undefined
218 ) {
219 return active
220 ? Object.assign(base, STATIC_DEFAULT_ACTIVE_ATTRIBUTES)
221 : base
222 }
223​
224 const stateProps: ResolvedLinkStateProps =
225 functionalUpdate(
226 (active ? options.activeProps : options.inactiveProps) ??
227 (active ? STATIC_ACTIVE_PROPS : EMPTY_OBJECT),
228 {},
229 ) ?? EMPTY_OBJECT
230 const baseStyle = options.style
231 const stateStyle = stateProps.style
232 // Snapshot reactive style properties so in-place updates remain observable.
233 const style =
234 baseStyle || stateStyle ? { ...baseStyle, ...stateStyle } : undefined
235 const baseClass = options.class
236 const stateClass = stateProps.class
237 const className = baseClass
238 ? stateClass
239 ? `${baseClass} ${stateClass}`
240 : baseClass
241 : stateClass
242​
243 return {
244 ...base,
245 ...stateProps,
246 // State props can override element props, but not routing options.
247 href,
248 disabled,
249 target: base.target,
250 ...(style && hasKeys(style) && { style }),
251 ...(className && { class: className }),
252 ...(active && STATIC_ACTIVE_ATTRIBUTES),
253 } as ResolvedLinkStateProps
254 }
255​
256 // Keep the guard inline so browser builds can drop the server return.
257 if (isServer ?? router.isServer) {
258 const props = resolveLinkStateProps(linkState(), {
259 onClick: options.onClick,
260 onBlur: options.onBlur,
261 onFocus: options.onFocus,
262 onMouseEnter: options.onMouseEnter,
263 onMouseLeave: options.onMouseLeave,
264 onMouseOut: options.onMouseOut,
265 onMouseOver: options.onMouseOver,
266 onTouchStart: options.onTouchStart,
267 ref: options.ref,
268 })
269 // Avoid creating merged-prop getters for absent server event handlers.
270 for (const key of STATIC_EVENT_PROPS) {
271 if (props[key] === undefined) {
272 delete props[key]
273 }
274 }
275 return Solid.mergeProps(propsSafeToSpread, props) as any
276 }
277​
278 let hasRenderFetched = false
279​
280 const preload = () =>
281 !options.reloadDocument &&
282 linkState()[1 /* external */] === undefined &&
283 !options.disabled &&
284 (options.preload ?? router.options.defaultPreload)
285 const preloadDelay = () =>
286 options.preloadDelay ?? router.options.defaultPreloadDelay ?? 0
287​
288 const doPreload = () =>
289 router.preloadRoute(dest()).catch((err: any) => {
290 console.warn(err)
291 console.warn(preloadWarning)
292 })
293​
294 const [ref, setRef] = Solid.createSignal<Element | null>(null)
295​
296 let preloadTimeout: ReturnType<typeof setTimeout> | undefined
297 const cancelPreload = () => {
298 clearTimeout(preloadTimeout)
299 preloadTimeout = undefined
300 }
301​
302 const enqueuePreload = (
303 e?: MouseEvent | FocusEvent | IntersectionObserverEntry,
304 ) => {
305 if (!e) {
306 cancelPreload()
307 return
308 }
309​
310 if (
311 !(
312 (e as IntersectionObserverEntry).isIntersecting ??
313 preload() === 'intent'
314 )
315 ) {
316 if ((e as IntersectionObserverEntry).isIntersecting === false) {
317 cancelPreload()
318 }
319 return
320 }
321​
322 if (!preloadDelay()) {
323 doPreload()
324 return
325 }
326​
327 preloadTimeout ??= setTimeout(() => {
328 preloadTimeout = undefined
329 doPreload()
330 }, preloadDelay())
331 }
332​
333 useIntersectionObserver(ref, enqueuePreload, preload)
334​
335 Solid.createEffect(() => {
336 if (hasRenderFetched) {
337 return
338 }
339 if (preload() === 'render') {
340 doPreload()
341 hasRenderFetched = true
342 }
343 })
344​
345 // The click handler
346 const handleClick = (e: MouseEvent) => {
347 // Check actual element's target attribute as fallback
348 const elementTarget = (
349 e.currentTarget as HTMLAnchorElement | SVGAElement
350 ).getAttribute('target')
351 const effectiveTarget =
352 options.target !== undefined ? options.target : elementTarget
353​
354 if (
355 !options.disabled &&
356 linkState()[1 /* external */] === undefined &&
357 !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) &&
358 !e.defaultPrevented &&
359 (!effectiveTarget || effectiveTarget === '_self') &&
360 e.button === 0
361 ) {
362 e.preventDefault()
363 cancelPreload()
364​
365 // All is well? Navigate!
366 // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing
367 router.navigate(dest())
368 }
369 }
370​
371 const handleTouchStart = () => {
372 if (preload() !== 'intent') return
373 doPreload()
374 }
375​
376 const handleLeave = () => {
377 if (preload() === 'intent') {
378 cancelPreload()
379 }
380 }
381​
382 const onClick = createComposedHandler(() => options.onClick, handleClick)
383 const onBlur = createComposedHandler(() => options.onBlur, handleLeave)
384 const onFocus = createComposedHandler(() => options.onFocus, enqueuePreload)
385 const onMouseEnter = createComposedHandler(
386 () => options.onMouseEnter,
387 enqueuePreload,
388 )
389 const onMouseOver = createComposedHandler(
390 () => options.onMouseOver,
391 enqueuePreload,
392 )
393 const onMouseLeave = createComposedHandler(
394 () => options.onMouseLeave,
395 handleLeave,
396 )
397 const onMouseOut = createComposedHandler(
398 () => options.onMouseOut,
399 handleLeave,
400 )
401 const onTouchStart = createComposedHandler(
402 () => options.onTouchStart,
403 handleTouchStart,
404 )
405​
406 // One ref callback per element. The selected state props' ref, else the
407 // Link's own, receives the element once; a state change does not re-call it.
408 const linkRef = (el: Element) => {
409 setRef(el)
410 const ref = resolved.ref ?? options.ref
411 if (typeof ref === 'function') {
412 ref(el as HTMLAnchorElement)
413 }
414 }
415​
416 // `mergeProps` memoizes this itself; the ref reads its latest result.
417 let resolved: Solid.ComponentProps<'a'>
418 const resolvedProps = () =>
419 (resolved = resolveLinkStateProps(linkState(), {
420 onClick,
421 onBlur,
422 onFocus,
423 onMouseEnter,
424 onMouseOver,
425 onMouseLeave,
426 onMouseOut,
427 onTouchStart,
428 }))
429​
430 // The ref sits after the memo so reading it does not track the memo: the
431 // element's ref effect then runs once.
432 return Solid.mergeProps(propsSafeToSpread, resolvedProps, {
433 ref: linkRef,
434 }) as any
436​
437// [element href, external href (null when blocked), active]
438type LinkState = [
439 href: string | undefined,
440 external: string | null | undefined,
441 active: boolean,
443​
444const isStore = (value: any): boolean => !!value?.[Solid.$PROXY]
445​
446// Props that decide where and how a Link navigates.
447const NAVIGATION_KEYS = [
448 'to',
449 'reloadDocument',
450 'replace',
451 'resetScroll',
452 'hashScrollIntoView',
453 'startTransition',
454 'viewTransition',
455 'ignoreBlocker',
456 'params',
457 'search',
458 'hash',
459 'state',
460 'mask',
461 'unsafeRelative',
462 'from',
463 'href',
464] as const
465// Options the Link consumes; every other option is an element prop.
466const LINK_OPTION_KEYS = [
467 ...NAVIGATION_KEYS,
468 'activeProps',
469 'inactiveProps',
470 'activeOptions',
471 'preload',
472 'preloadDelay',
473 'preloadIntentProximity',
474 'target',
475 'disabled',
476 'style',
477 'class',
478 'onClick',
479 'onBlur',
480 'onFocus',
481 'onMouseEnter',
482 'onMouseLeave',
483 'onMouseOver',
484 'onMouseOut',
485 'onTouchStart',
487// A Link also consumes its children and component, and drops `type`.
488const LINK_ELEMENT_KEYS = [...LINK_OPTION_KEYS, '_asChild', 'children', 'type']
489const STATIC_EVENT_PROPS = [
490 'onClick',
491 'onBlur',
492 'onFocus',
493 'onMouseEnter',
494 'onMouseLeave',
495 'onMouseOut',
496 'onMouseOver',
497 'onTouchStart',
498] as const
499const STATIC_ACTIVE_PROPS = { class: 'active' }
500const EMPTY_OBJECT = {}
501const STATIC_DEFAULT_ACTIVE_ATTRIBUTES = {
502 class: 'active',
503 'data-status': 'active',
504 'aria-current': 'page',
506const STATIC_DISABLED_PROPS = {
507 role: 'link' as const,
508 'aria-disabled': true,
510const STATIC_ACTIVE_ATTRIBUTES = {
511 'data-status': 'active',
512 'aria-current': 'page',
514​
515/** Call a JSX.EventHandlerUnion with the event. */
516function callHandler<T, TEvent extends Event>(
517 event: TEvent & { currentTarget: T; target: Element },
518 handler: Solid.JSX.EventHandlerUnion<T, TEvent>,
519) {
520 if (typeof handler === 'function') {
521 handler(event)
522 } else {
523 handler[0](handler[1], event)
524 }
525 return event.defaultPrevented
527​
528function createComposedHandler<T, TEvent extends Event>(
529 getHandler: () => Solid.JSX.EventHandlerUnion<T, TEvent> | undefined,
530 fallback: (event: TEvent) => void,
531) {
532 return (event: TEvent & { currentTarget: T; target: Element }) => {
533 const handler = getHandler()
534 if (!handler || !callHandler(event, handler)) fallback(event)
535 }
537​
538export type UseLinkPropsOptions<
539 TRouter extends AnyRouter = RegisteredRouter,
540 TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
541 TTo extends string | undefined = '.',
542 TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
543 TMaskTo extends string = '.',
544> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
545 Omit<Solid.ComponentProps<'a'>, 'style'> & { style?: Solid.JSX.CSSProperties }
546​
547export type ActiveLinkOptions<
548 TComp = 'a',
549 TRouter extends AnyRouter = RegisteredRouter,
550 TFrom extends string = string,
551 TTo extends string | undefined = '.',
552 TMaskFrom extends string = TFrom,
553 TMaskTo extends string = '.',
554> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
555 ActiveLinkOptionProps<TComp>
556​
557type ActiveLinkProps<TComp> = Partial<
558 LinkComponentSolidProps<TComp> & {
559 [key: `data-${string}`]: unknown
560 }
562​
563export interface ActiveLinkOptionProps<TComp = 'a'> {
564 /**
565 * A function that returns additional props for the `active` state of this link.
566 * These props override other props passed to the link (`style`'s are merged, `class`'s are concatenated)
567 */
568 activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
569 /**
570 * A function that returns additional props for the `inactive` state of this link.
571 * These props override other props passed to the link (`style`'s are merged, `class`'s are concatenated)
572 */
573 inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
575​
576export type LinkProps<
577 TComp = 'a',
578 TRouter extends AnyRouter = RegisteredRouter,
579 TFrom extends string = string,
580 TTo extends string | undefined = '.',
581 TMaskFrom extends string = TFrom,
582 TMaskTo extends string = '.',
583> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
584 LinkPropsChildren
585​
586export interface LinkPropsChildren {
587 // 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
588 children?:
589 | Solid.JSX.Element
590 | ((state: { isActive: boolean }) => Solid.JSX.Element)
592​
593type LinkComponentSolidProps<TComp> = TComp extends Solid.ValidComponent
594 ? Omit<Solid.ComponentProps<TComp>, keyof CreateLinkProps>
595 : never
596​
597export type LinkComponentProps<
598 TComp = 'a',
599 TRouter extends AnyRouter = RegisteredRouter,
600 TFrom extends string = string,
601 TTo extends string | undefined = '.',
602 TMaskFrom extends string = TFrom,
603 TMaskTo extends string = '.',
604> = LinkComponentSolidProps<TComp> &
605 LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
606​
607export type CreateLinkProps = LinkProps<
608 any,
609 any,
610 string,
611 string,
612 string,
613 string
615​
616export type LinkComponent<
617 in out TComp,
618 in out TDefaultFrom extends string = string,
619> = <
620 TRouter extends AnyRouter = RegisteredRouter,
621 const TFrom extends string = TDefaultFrom,
622 const TTo extends string | undefined = undefined,
623 const TMaskFrom extends string = TFrom,
624 const TMaskTo extends string = '',
625>(
626 props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
627) => Solid.JSX.Element
628​
629export interface LinkComponentRoute<
630 in out TDefaultFrom extends string = string,
631> {
632 defaultFrom: TDefaultFrom;
633 <
634 TRouter extends AnyRouter = RegisteredRouter,
635 const TTo extends string | undefined = undefined,
636 const TMaskTo extends string = '',
637 >(
638 props: LinkComponentProps<
639 'a',
640 TRouter,
641 this['defaultFrom'],
642 TTo,
643 this['defaultFrom'],
644 TMaskTo
645 >,
646 ): Solid.JSX.Element
648​
649export function createLink<const TComp>(
650 Comp: Constrain<TComp, any, (props: CreateLinkProps) => Solid.JSX.Element>,
651): LinkComponent<TComp> {
652 return (props) => <Link {...props} _asChild={Comp} />
654​
655export const Link: LinkComponent<'a'> = (props) => {
656 const local = props as typeof props & { _asChild: any }
657 // One props proxy between the element and the Link's props.
658 const linkProps = createLinkProps(props as any, LINK_ELEMENT_KEYS)
659​
660 // Element insertion tracks this itself; only a custom component, which may
661 // read its children more than once, gets a memo.
662 const children = () => {
663 const ch = local.children
664 if (typeof ch === 'function') {
665 return ch({
666 get isActive() {
667 return (linkProps as any)['data-status'] === 'active'
668 },
669 })
670 }
671​
672 return ch satisfies Solid.JSX.Element
673 }
674​
675 if (local._asChild === 'svg') {
676 const [_, svgLinkProps] = Solid.splitProps(linkProps, ['class'])
677 return (
678 <svg>
679 <a {...svgLinkProps}>{children()}</a>
680 </svg>
681 )
682 }
683​
684 if (!local._asChild) {
685 return <a {...linkProps}>{children()}</a>
686 }
687​
688 const memo = Solid.createMemo(children)
689 return (
690 <Dynamic component={local._asChild as Solid.ValidComponent} {...linkProps}>
691 {memo()}
692 </Dynamic>
693 )
695​
696export type LinkOptionsFnOptions<
697 TOptions,
698 TComp,
699 TRouter extends AnyRouter = RegisteredRouter,
700> =
701 TOptions extends ReadonlyArray<any>
702 ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>
703 : ValidateLinkOptions<TRouter, TOptions, string, TComp>
704​
705export type LinkOptionsFn<TComp> = <
706 const TOptions,
707 TRouter extends AnyRouter = RegisteredRouter,
708>(
709 options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,
710) => TOptions
711​
712export const linkOptions: LinkOptionsFn<'a'> = (options) => {
713 return options as any