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

link.tsx

630 lines16.3 KB

1import * as Solid from 'solid-js'
2​
3import { mergeRefs } from '@solid-primitives/refs'
4​
5import {
6 deepEqual,
7 exactPathTest,
8 functionalUpdate,
9 preloadWarning,
10 removeTrailingSlash,
11} from '@tanstack/router-core'
12import { Dynamic } from 'solid-js/web'
13import { useRouterState } from './useRouterState'
14import { useRouter } from './useRouter'
15​
16import { useIntersectionObserver } from './utils'
17​
18import type {
19 AnyRouter,
20 Constrain,
21 LinkCurrentTargetElement,
22 LinkOptions,
23 RegisteredRouter,
24 RoutePaths,
25} from '@tanstack/router-core'
26import type {
27 ValidateLinkOptions,
28 ValidateLinkOptionsArray,
29} from './typePrimitives'
30​
31export function useLinkProps<
32 TRouter extends AnyRouter = RegisteredRouter,
33 TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
34 TTo extends string = '',
35 TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
36 TMaskTo extends string = '',
37>(
38 options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
39): Solid.ComponentProps<'a'> {
40 const router = useRouter()
41 const [isTransitioning, setIsTransitioning] = Solid.createSignal(false)
42 let hasRenderFetched = false
43​
44 const [local, rest] = Solid.splitProps(
45 Solid.mergeProps(
46 {
47 activeProps: () => ({ class: 'active' }),
48 inactiveProps: () => ({}),
49 },
50 options,
51 ),
52 [
53 'activeProps',
54 'inactiveProps',
55 'activeOptions',
56 'to',
57 'preload',
58 'preloadDelay',
59 'hashScrollIntoView',
60 'replace',
61 'startTransition',
62 'resetScroll',
63 'viewTransition',
64 'target',
65 'disabled',
66 'style',
67 'class',
68 'onClick',
69 'onFocus',
70 'onMouseEnter',
71 'onMouseLeave',
72 'onMouseOver',
73 'onMouseOut',
74 'onTouchStart',
75 'ignoreBlocker',
76 ],
77 )
78​
79 // const {
80 // // custom props
81 // activeProps = () => ({ class: 'active' }),
82 // inactiveProps = () => ({}),
83 // activeOptions,
84 // to,
85 // preload: userPreload,
86 // preloadDelay: userPreloadDelay,
87 // hashScrollIntoView,
88 // replace,
89 // startTransition,
90 // resetScroll,
91 // viewTransition,
92 // // element props
93 // children,
94 // target,
95 // disabled,
96 // style,
97 // class,
98 // onClick,
99 // onFocus,
100 // onMouseEnter,
101 // onMouseLeave,
102 // onTouchStart,
103 // ignoreBlocker,
104 // ...rest
105 // } = options
106​
107 const [_, propsSafeToSpread] = Solid.splitProps(rest, [
108 'params',
109 'search',
110 'hash',
111 'state',
112 'mask',
113 'reloadDocument',
114 'unsafeRelative',
115 ])
116​
117 const currentSearch = useRouterState({
118 select: (s) => s.location.searchStr,
119 })
120​
121 const from = options.from
122​
123 const _options = () => {
124 return {
125 ...options,
126 from,
127 }
128 }
129​
130 const next = Solid.createMemo(() => {
131 currentSearch()
132 return router.buildLocation(_options() as any)
133 })
134​
135 const hrefOption = Solid.createMemo(() => {
136 if (_options().disabled) {
137 return undefined
138 }
139 let href
140 const maskedLocation = next().maskedLocation
141 if (maskedLocation) {
142 href = maskedLocation.url
143 } else {
144 href = next().url
145 }
146 let external = false
147 if (router.origin) {
148 if (href.startsWith(router.origin)) {
149 href = router.history.createHref(href.replace(router.origin, ''))
150 } else {
151 external = true
152 }
153 }
154 return { href, external }
155 })
156​
157 const externalLink = Solid.createMemo(() => {
158 const _href = hrefOption()
159 if (_href?.external) {
160 return _href.href
161 }
162 try {
163 new URL(_options().to as any)
164 return _options().to
165 } catch {}
166 return undefined
167 })
168​
169 const preload = Solid.createMemo(() => {
170 if (_options().reloadDocument || externalLink()) {
171 return false
172 }
173 return local.preload ?? router.options.defaultPreload
174 })
175 const preloadDelay = () =>
176 local.preloadDelay ?? router.options.defaultPreloadDelay ?? 0
177​
178 const isActive = useRouterState({
179 select: (s) => {
180 if (externalLink()) return false
181 if (local.activeOptions?.exact) {
182 const testExact = exactPathTest(
183 s.location.pathname,
184 next().pathname,
185 router.basepath,
186 )
187 if (!testExact) {
188 return false
189 }
190 } else {
191 const currentPathSplit = removeTrailingSlash(
192 s.location.pathname,
193 router.basepath,
194 ).split('/')
195 const nextPathSplit = removeTrailingSlash(
196 next()?.pathname,
197 router.basepath,
198 )?.split('/')
199​
200 const pathIsFuzzyEqual = nextPathSplit?.every(
201 (d, i) => d === currentPathSplit[i],
202 )
203 if (!pathIsFuzzyEqual) {
204 return false
205 }
206 }
207​
208 if (local.activeOptions?.includeSearch ?? true) {
209 const searchTest = deepEqual(s.location.search, next().search, {
210 partial: !local.activeOptions?.exact,
211 ignoreUndefined: !local.activeOptions?.explicitUndefined,
212 })
213 if (!searchTest) {
214 return false
215 }
216 }
217​
218 if (local.activeOptions?.includeHash) {
219 return s.location.hash === next().hash
220 }
221 return true
222 },
223 })
224​
225 const doPreload = () =>
226 router.preloadRoute(_options() as any).catch((err: any) => {
227 console.warn(err)
228 console.warn(preloadWarning)
229 })
230​
231 const preloadViewportIoCallback = (
232 entry: IntersectionObserverEntry | undefined,
233 ) => {
234 if (entry?.isIntersecting) {
235 doPreload()
236 }
237 }
238​
239 const [ref, setRef] = Solid.createSignal<Element | null>(null)
240​
241 useIntersectionObserver(
242 ref,
243 preloadViewportIoCallback,
244 { rootMargin: '100px' },
245 { disabled: !!local.disabled || !(preload() === 'viewport') },
246 )
247​
248 Solid.createEffect(() => {
249 if (hasRenderFetched) {
250 return
251 }
252 if (!local.disabled && preload() === 'render') {
253 doPreload()
254 hasRenderFetched = true
255 }
256 })
257​
258 if (externalLink()) {
259 return Solid.mergeProps(
260 propsSafeToSpread,
261 {
262 ref: mergeRefs(setRef, _options().ref),
263 href: externalLink(),
264 },
265 Solid.splitProps(local, [
266 'target',
267 'disabled',
268 'style',
269 'class',
270 'onClick',
271 'onFocus',
272 'onMouseEnter',
273 'onMouseLeave',
274 'onMouseOut',
275 'onMouseOver',
276 'onTouchStart',
277 ])[0],
278 ) as any
279 }
280​
281 // The click handler
282 const handleClick = (e: MouseEvent) => {
283 // Check actual element's target attribute as fallback
284 const elementTarget = (
285 e.currentTarget as HTMLAnchorElement | SVGAElement
286 ).getAttribute('target')
287 const effectiveTarget =
288 local.target !== undefined ? local.target : elementTarget
289​
290 if (
291 !local.disabled &&
292 !isCtrlEvent(e) &&
293 !e.defaultPrevented &&
294 (!effectiveTarget || effectiveTarget === '_self') &&
295 e.button === 0
296 ) {
297 e.preventDefault()
298​
299 setIsTransitioning(true)
300​
301 const unsub = router.subscribe('onResolved', () => {
302 unsub()
303 setIsTransitioning(false)
304 })
305​
306 // All is well? Navigate!
307 // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing
308 router.navigate({
309 ..._options(),
310 replace: local.replace,
311 resetScroll: local.resetScroll,
312 hashScrollIntoView: local.hashScrollIntoView,
313 startTransition: local.startTransition,
314 viewTransition: local.viewTransition,
315 ignoreBlocker: local.ignoreBlocker,
316 })
317 }
318 }
319​
320 // The click handler
321 const handleFocus = (_: MouseEvent) => {
322 if (local.disabled) return
323 if (preload()) {
324 doPreload()
325 }
326 }
327​
328 const handleTouchStart = handleFocus
329​
330 const handleEnter = (e: MouseEvent) => {
331 if (local.disabled) return
332 const eventTarget = (e.currentTarget || {}) as LinkCurrentTargetElement
333​
334 if (preload()) {
335 if (eventTarget.preloadTimeout) {
336 return
337 }
338​
339 eventTarget.preloadTimeout = setTimeout(() => {
340 eventTarget.preloadTimeout = null
341 doPreload()
342 }, preloadDelay())
343 }
344 }
345​
346 const handleLeave = (e: MouseEvent) => {
347 if (local.disabled) return
348 const eventTarget = (e.currentTarget || {}) as LinkCurrentTargetElement
349​
350 if (eventTarget.preloadTimeout) {
351 clearTimeout(eventTarget.preloadTimeout)
352 eventTarget.preloadTimeout = null
353 }
354 }
355​
356 /** Call a JSX.EventHandlerUnion with the event. */
357 function callHandler<T, TEvent extends Event>(
358 event: TEvent & { currentTarget: T; target: Element },
359 handler: Solid.JSX.EventHandlerUnion<T, TEvent> | undefined,
360 ) {
361 if (handler) {
362 if (typeof handler === 'function') {
363 handler(event)
364 } else {
365 handler[0](handler[1], event)
366 }
367 }
368​
369 return event.defaultPrevented
370 }
371​
372 function composeEventHandlers<T>(
373 handlers: Array<Solid.JSX.EventHandlerUnion<T, any> | undefined>,
374 ) {
375 return (event: any) => {
376 for (const handler of handlers) {
377 callHandler(event, handler)
378 }
379 }
380 }
381​
382 // Get the active props
383 const resolvedActiveProps: () => Omit<Solid.ComponentProps<'a'>, 'style'> & {
384 style?: Solid.JSX.CSSProperties
385 } = () =>
386 isActive() ? (functionalUpdate(local.activeProps as any, {}) ?? {}) : {}
387​
388 // Get the inactive props
389 const resolvedInactiveProps: () => Omit<
390 Solid.ComponentProps<'a'>,
391 'style'
392 > & { style?: Solid.JSX.CSSProperties } = () =>
393 isActive() ? {} : functionalUpdate(local.inactiveProps, {})
394​
395 const resolvedClassName = () =>
396 [local.class, resolvedActiveProps().class, resolvedInactiveProps().class]
397 .filter(Boolean)
398 .join(' ')
399​
400 const resolvedStyle = () => ({
401 ...local.style,
402 ...resolvedActiveProps().style,
403 ...resolvedInactiveProps().style,
404 })
405​
406 return Solid.mergeProps(
407 propsSafeToSpread,
408 resolvedActiveProps,
409 resolvedInactiveProps,
410 () => {
411 return {
412 href: hrefOption()?.href,
413 ref: mergeRefs(setRef, _options().ref),
414 onClick: composeEventHandlers([local.onClick, handleClick]),
415 onFocus: composeEventHandlers([local.onFocus, handleFocus]),
416 onMouseEnter: composeEventHandlers([local.onMouseEnter, handleEnter]),
417 onMouseOver: composeEventHandlers([local.onMouseOver, handleEnter]),
418 onMouseLeave: composeEventHandlers([local.onMouseLeave, handleLeave]),
419 onMouseOut: composeEventHandlers([local.onMouseOut, handleLeave]),
420 onTouchStart: composeEventHandlers([
421 local.onTouchStart,
422 handleTouchStart,
423 ]),
424 disabled: !!local.disabled,
425 target: local.target,
426 ...(() => {
427 const s = resolvedStyle()
428 return Object.keys(s).length ? { style: s } : {}
429 })(),
430 ...(() => {
431 const c = resolvedClassName()
432 return c ? { class: c } : {}
433 })(),
434 ...(local.disabled && {
435 role: 'link',
436 'aria-disabled': true,
437 }),
438 ...(isActive() && { 'data-status': 'active', 'aria-current': 'page' }),
439 ...(isTransitioning() && { 'data-transitioning': 'transitioning' }),
440 }
441 },
442 ) as any
444​
445export type UseLinkPropsOptions<
446 TRouter extends AnyRouter = RegisteredRouter,
447 TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
448 TTo extends string | undefined = '.',
449 TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
450 TMaskTo extends string = '.',
451> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
452 Omit<Solid.ComponentProps<'a'>, 'style'> & { style?: Solid.JSX.CSSProperties }
453​
454export type ActiveLinkOptions<
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> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
462 ActiveLinkOptionProps<TComp>
463​
464type ActiveLinkProps<TComp> = Partial<
465 LinkComponentSolidProps<TComp> & {
466 [key: `data-${string}`]: unknown
467 }
469​
470export interface ActiveLinkOptionProps<TComp = 'a'> {
471 /**
472 * A function that returns additional props for the `active` state of this link.
473 * These props override other props passed to the link (`style`'s are merged, `class`'s are concatenated)
474 */
475 activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
476 /**
477 * A function that returns additional props for the `inactive` state of this link.
478 * These props override other props passed to the link (`style`'s are merged, `class`'s are concatenated)
479 */
480 inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
482​
483export type LinkProps<
484 TComp = 'a',
485 TRouter extends AnyRouter = RegisteredRouter,
486 TFrom extends string = string,
487 TTo extends string | undefined = '.',
488 TMaskFrom extends string = TFrom,
489 TMaskTo extends string = '.',
490> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
491 LinkPropsChildren
492​
493export interface LinkPropsChildren {
494 // 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
495 children?:
496 | Solid.JSX.Element
497 | ((state: {
498 isActive: boolean
499 isTransitioning: boolean
500 }) => Solid.JSX.Element)
502​
503type LinkComponentSolidProps<TComp> = TComp extends Solid.ValidComponent
504 ? Omit<Solid.ComponentProps<TComp>, keyof CreateLinkProps>
505 : never
506​
507export type LinkComponentProps<
508 TComp = 'a',
509 TRouter extends AnyRouter = RegisteredRouter,
510 TFrom extends string = string,
511 TTo extends string | undefined = '.',
512 TMaskFrom extends string = TFrom,
513 TMaskTo extends string = '.',
514> = LinkComponentSolidProps<TComp> &
515 LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
516​
517export type CreateLinkProps = LinkProps<
518 any,
519 any,
520 string,
521 string,
522 string,
523 string
525​
526export type LinkComponent<
527 in out TComp,
528 in out TDefaultFrom extends string = string,
529> = <
530 TRouter extends AnyRouter = RegisteredRouter,
531 const TFrom extends string = TDefaultFrom,
532 const TTo extends string | undefined = undefined,
533 const TMaskFrom extends string = TFrom,
534 const TMaskTo extends string = '',
535>(
536 props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
537) => Solid.JSX.Element
538​
539export interface LinkComponentRoute<
540 in out TDefaultFrom extends string = string,
541> {
542 defaultFrom: TDefaultFrom
543 <
544 TRouter extends AnyRouter = RegisteredRouter,
545 const TTo extends string | undefined = undefined,
546 const TMaskTo extends string = '',
547 >(
548 props: LinkComponentProps<
549 'a',
550 TRouter,
551 this['defaultFrom'],
552 TTo,
553 this['defaultFrom'],
554 TMaskTo
555 >,
556 ): Solid.JSX.Element
558​
559export function createLink<const TComp>(
560 Comp: Constrain<TComp, any, (props: CreateLinkProps) => Solid.JSX.Element>,
561): LinkComponent<TComp> {
562 return (props) => <Link {...props} _asChild={Comp} />
564​
565export const Link: LinkComponent<'a'> = (props) => {
566 const [local, rest] = Solid.splitProps(
567 props as typeof props & { _asChild: any },
568 ['_asChild', 'children'],
569 )
570​
571 const [_, linkProps] = Solid.splitProps(
572 useLinkProps(rest as unknown as any),
573 ['type'],
574 )
575​
576 const children = Solid.createMemo(() => {
577 const ch = local.children
578 if (typeof ch === 'function') {
579 return ch({
580 get isActive() {
581 return (linkProps as any)['data-status'] === 'active'
582 },
583 get isTransitioning() {
584 return (linkProps as any)['data-transitioning'] === 'transitioning'
585 },
586 })
587 }
588​
589 return ch satisfies Solid.JSX.Element
590 })
591​
592 if (local._asChild === 'svg') {
593 const [_, svgLinkProps] = Solid.splitProps(linkProps, ['class'])
594 return (
595 <svg>
596 <a {...svgLinkProps}>{children()}</a>
597 </svg>
598 )
599 }
600​
601 return (
602 <Dynamic component={local._asChild ? local._asChild : 'a'} {...linkProps}>
603 {children()}
604 </Dynamic>
605 )
607​
608function isCtrlEvent(e: MouseEvent) {
609 return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
611​
612export type LinkOptionsFnOptions<
613 TOptions,
614 TComp,
615 TRouter extends AnyRouter = RegisteredRouter,
616> =
617 TOptions extends ReadonlyArray<any>
618 ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>
619 : ValidateLinkOptions<TRouter, TOptions, string, TComp>
620​
621export type LinkOptionsFn<TComp> = <
622 const TOptions,
623 TRouter extends AnyRouter = RegisteredRouter,
624>(
625 options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,
626) => TOptions
627​
628export const linkOptions: LinkOptionsFn<'a'> = (options) => {
629 return options as any