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 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,
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 = (e.currentTarget as HTMLAnchorElement).target
285 const effectiveTarget =
286 local.target !== undefined ? local.target : elementTarget
287β
288 if (
289 !local.disabled &&
290 !isCtrlEvent(e) &&
291 !e.defaultPrevented &&
292 (!effectiveTarget || effectiveTarget === '_self') &&
293 e.button === 0
294 ) {
295 e.preventDefault()
296β
297 setIsTransitioning(true)
298β
299 const unsub = router.subscribe('onResolved', () => {
300 unsub()
301 setIsTransitioning(false)
302 })
303β
304 // All is well? Navigate!
305 // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing
306 router.navigate({
307 ..._options(),
308 replace: local.replace,
309 resetScroll: local.resetScroll,
310 hashScrollIntoView: local.hashScrollIntoView,
311 startTransition: local.startTransition,
312 viewTransition: local.viewTransition,
313 ignoreBlocker: local.ignoreBlocker,
314 })
315 }
316 }
317β
318 // The click handler
319 const handleFocus = (_: MouseEvent) => {
320 if (local.disabled) return
321 if (preload()) {
322 doPreload()
323 }
324 }
325β
326 const handleTouchStart = handleFocus
327β
328 const handleEnter = (e: MouseEvent) => {
329 if (local.disabled) return
330 const eventTarget = (e.target || {}) as LinkCurrentTargetElement
331β
332 if (preload()) {
333 if (eventTarget.preloadTimeout) {
334 return
335 }
336β
337 eventTarget.preloadTimeout = setTimeout(() => {
338 eventTarget.preloadTimeout = null
339 doPreload()
340 }, preloadDelay())
341 }
342 }
343β
344 const handleLeave = (e: MouseEvent) => {
345 if (local.disabled) return
346 const eventTarget = (e.target || {}) as LinkCurrentTargetElement
347β
348 if (eventTarget.preloadTimeout) {
349 clearTimeout(eventTarget.preloadTimeout)
350 eventTarget.preloadTimeout = null
351 }
352 }
353β
354 /** Call a JSX.EventHandlerUnion with the event. */
355 function callHandler<T, TEvent extends Event>(
356 event: TEvent & { currentTarget: T; target: Element },
357 handler: Solid.JSX.EventHandlerUnion<T, TEvent> | undefined,
358 ) {
359 if (handler) {
360 if (typeof handler === 'function') {
361 handler(event)
362 } else {
363 handler[0](handler[1], event)
364 }
365 }
366β
367 return event.defaultPrevented
368 }
369β
370 function composeEventHandlers<T>(
371 handlers: Array<Solid.JSX.EventHandlerUnion<T, any> | undefined>,
372 ) {
373 return (event: any) => {
374 for (const handler of handlers) {
375 callHandler(event, handler)
376 }
377 }
378 }
379β
380 // Get the active props
381 const resolvedActiveProps: () => Omit<Solid.ComponentProps<'a'>, 'style'> & {
382 style?: Solid.JSX.CSSProperties
383 } = () =>
384 isActive() ? (functionalUpdate(local.activeProps as any, {}) ?? {}) : {}
385β
386 // Get the inactive props
387 const resolvedInactiveProps: () => Omit<
388 Solid.ComponentProps<'a'>,
389 'style'
390 > & { style?: Solid.JSX.CSSProperties } = () =>
391 isActive() ? {} : functionalUpdate(local.inactiveProps, {})
392β
393 const resolvedClassName = () =>
394 [local.class, resolvedActiveProps().class, resolvedInactiveProps().class]
395 .filter(Boolean)
396 .join(' ')
397β
398 const resolvedStyle = () => ({
399 ...local.style,
400 ...resolvedActiveProps().style,
401 ...resolvedInactiveProps().style,
402 })
403β
404 return Solid.mergeProps(
405 propsSafeToSpread,
406 resolvedActiveProps,
407 resolvedInactiveProps,
408 () => {
409 return {
410 href: hrefOption()?.href,
411 ref: mergeRefs(setRef, _options().ref),
412 onClick: composeEventHandlers([local.onClick, handleClick]),
413 onFocus: composeEventHandlers([local.onFocus, handleFocus]),
414 onMouseEnter: composeEventHandlers([local.onMouseEnter, handleEnter]),
415 onMouseOver: composeEventHandlers([local.onMouseOver, handleEnter]),
416 onMouseLeave: composeEventHandlers([local.onMouseLeave, handleLeave]),
417 onMouseOut: composeEventHandlers([local.onMouseOut, handleLeave]),
418 onTouchStart: composeEventHandlers([
419 local.onTouchStart,
420 handleTouchStart,
421 ]),
422 disabled: !!local.disabled,
423 target: local.target,
424 ...(Object.keys(resolvedStyle).length && { style: resolvedStyle }),
425 ...(resolvedClassName() && { class: resolvedClassName() }),
426 ...(local.disabled && {
427 role: 'link',
428 'aria-disabled': true,
429 }),
430 ...(isActive() && { 'data-status': 'active', 'aria-current': 'page' }),
431 ...(isTransitioning() && { 'data-transitioning': 'transitioning' }),
432 }
433 },
434 ) as any
435}
436β
437export type UseLinkPropsOptions<
438 TRouter extends AnyRouter = RegisteredRouter,
439 TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
440 TTo extends string | undefined = '.',
441 TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
442 TMaskTo extends string = '.',
443> = ActiveLinkOptions<'a', TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
444 Omit<Solid.ComponentProps<'a'>, 'style'> & { style?: Solid.JSX.CSSProperties }
445β
446export type ActiveLinkOptions<
447 TComp = 'a',
448 TRouter extends AnyRouter = RegisteredRouter,
449 TFrom extends string = string,
450 TTo extends string | undefined = '.',
451 TMaskFrom extends string = TFrom,
452 TMaskTo extends string = '.',
453> = LinkOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
454 ActiveLinkOptionProps<TComp>
455β
456type ActiveLinkProps<TComp> = Partial<
457 LinkComponentSolidProps<TComp> & {
458 [key: `data-${string}`]: unknown
459 }
460>
461β
462export interface ActiveLinkOptionProps<TComp = 'a'> {
463 /**
464 * A function that returns additional props for the `active` state of this link.
465 * These props override other props passed to the link (`style`'s are merged, `class`'s are concatenated)
466 */
467 activeProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
468 /**
469 * A function that returns additional props for the `inactive` state of this link.
470 * These props override other props passed to the link (`style`'s are merged, `class`'s are concatenated)
471 */
472 inactiveProps?: ActiveLinkProps<TComp> | (() => ActiveLinkProps<TComp>)
473}
474β
475export type LinkProps<
476 TComp = 'a',
477 TRouter extends AnyRouter = RegisteredRouter,
478 TFrom extends string = string,
479 TTo extends string | undefined = '.',
480 TMaskFrom extends string = TFrom,
481 TMaskTo extends string = '.',
482> = ActiveLinkOptions<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo> &
483 LinkPropsChildren
484β
485export interface LinkPropsChildren {
486 // 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
487 children?:
488 | Solid.JSX.Element
489 | ((state: {
490 isActive: boolean
491 isTransitioning: boolean
492 }) => Solid.JSX.Element)
493}
494β
495type LinkComponentSolidProps<TComp> = TComp extends Solid.ValidComponent
496 ? Omit<Solid.ComponentProps<TComp>, keyof CreateLinkProps>
497 : never
498β
499export type LinkComponentProps<
500 TComp = 'a',
501 TRouter extends AnyRouter = RegisteredRouter,
502 TFrom extends string = string,
503 TTo extends string | undefined = '.',
504 TMaskFrom extends string = TFrom,
505 TMaskTo extends string = '.',
506> = LinkComponentSolidProps<TComp> &
507 LinkProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
508β
509export type CreateLinkProps = LinkProps<
510 any,
511 any,
512 string,
513 string,
514 string,
515 string
516>
517β
518export type LinkComponent<
519 in out TComp,
520 in out TDefaultFrom extends string = string,
521> = <
522 TRouter extends AnyRouter = RegisteredRouter,
523 const TFrom extends string = TDefaultFrom,
524 const TTo extends string | undefined = undefined,
525 const TMaskFrom extends string = TFrom,
526 const TMaskTo extends string = '',
527>(
528 props: LinkComponentProps<TComp, TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
529) => Solid.JSX.Element
530β
531export interface LinkComponentRoute<
532 in out TDefaultFrom extends string = string,
533> {
534 defaultFrom: TDefaultFrom
535 <
536 TRouter extends AnyRouter = RegisteredRouter,
537 const TTo extends string | undefined = undefined,
538 const TMaskTo extends string = '',
539 >(
540 props: LinkComponentProps<
541 'a',
542 TRouter,
543 this['defaultFrom'],
544 TTo,
545 this['defaultFrom'],
546 TMaskTo
547 >,
548 ): Solid.JSX.Element
549}
550β
551export function createLink<const TComp>(
552 Comp: Constrain<TComp, any, (props: CreateLinkProps) => Solid.JSX.Element>,
553): LinkComponent<TComp> {
554 return (props) => <Link {...props} _asChild={Comp} />
555}
556β
557export const Link: LinkComponent<'a'> = (props) => {
558 const [local, rest] = Solid.splitProps(
559 props as typeof props & { _asChild: any },
560 ['_asChild', 'children'],
561 )
562β
563 const [_, linkProps] = Solid.splitProps(
564 useLinkProps(rest as unknown as any),
565 ['type'],
566 )
567β
568 const children = Solid.createMemo(() => {
569 const ch = local.children
570 if (typeof ch === 'function') {
571 return ch({
572 get isActive() {
573 return (linkProps as any)['data-status'] === 'active'
574 },
575 isTransitioning: false,
576 })
577 }
578β
579 return ch satisfies Solid.JSX.Element
580 })
581β
582 return (
583 <Dynamic component={local._asChild ? local._asChild : 'a'} {...linkProps}>
584 {children()}
585 </Dynamic>
586 )
587}
588β
589function isCtrlEvent(e: MouseEvent) {
590 return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
591}
592β
593export type LinkOptionsFnOptions<
594 TOptions,
595 TComp,
596 TRouter extends AnyRouter = RegisteredRouter,
597> =
598 TOptions extends ReadonlyArray<any>
599 ? ValidateLinkOptionsArray<TRouter, TOptions, string, TComp>
600 : ValidateLinkOptions<TRouter, TOptions, string, TComp>
601β
602export type LinkOptionsFn<TComp> = <
603 const TOptions,
604 TRouter extends AnyRouter = RegisteredRouter,
605>(
606 options: LinkOptionsFnOptions<TOptions, TComp, TRouter>,
607) => TOptions
608β
609export const linkOptions: LinkOptionsFn<'a'> = (options) => {
610 return options as any
611}