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