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

BaseTanStackRouterDevtoolsPanel.tsx

835 lines25.6 KB

1import { clsx as cx } from 'clsx'
2import {
3 getRouteSegments,
4 hasKeys,
5 hasMissingPathParams,
6 interpolatePath,
7 rootRouteId,
8 trimPath,
9} from '@tanstack/router-core'
10import {
11 For,
12 Match,
13 Show,
14 Switch,
15 createEffect,
16 createMemo,
17 createSignal,
18 onCleanup,
19 splitProps,
20 untrack,
21} from 'solid-js'
22import { useDevtoolsOnClose } from './context'
23import { useStyles } from './useStyles'
24import useLocalStorage from './useLocalStorage'
25import { Explorer } from './Explorer'
26import { getRouteStatusColor, getStatusColor, multiSortBy } from './utils'
27import { AgeTicker } from './AgeTicker'
28// import type { DevtoolsPanelOptions } from './TanStackRouterDevtoolsPanel'
29​
30import { NavigateButton } from './NavigateButton'
31import type {
32 AnyContext,
33 AnyRoute,
34 AnyRouteMatch,
35 AnyRouter,
36 FileRouteTypes,
37 MakeRouteMatchUnion,
38 Route,
39 RouterState,
40} from '@tanstack/router-core'
41import type { Accessor, JSX } from 'solid-js'
42​
43export interface BaseDevtoolsPanelOptions {
44 /**
45 * The standard React style object used to style a component with inline styles
46 */
47 style?: Accessor<JSX.CSSProperties>
48 /**
49 * The standard React class property used to style a component with classes
50 */
51 className?: Accessor<string>
52 /**
53 * A boolean variable indicating whether the panel is open or closed
54 */
55 isOpen?: boolean
56 /**
57 * A function that toggles the open and close state of the panel
58 */
59 setIsOpen?: (isOpen: boolean) => void
60 /**
61 * Handles the opening and closing the devtools panel
62 */
63 handleDragStart?: (e: any) => void
64 /**
65 * A boolean variable indicating if the "lite" version of the library is being used
66 */
67 router: Accessor<AnyRouter>
68 routerState: Accessor<any>
69 /**
70 * Use this to attach the devtool's styles to specific element in the DOM.
71 */
72 shadowDOMTarget?: ShadowRoot
74​
75const HISTORY_LIMIT = 15
76​
77function Logo(props: any) {
78 const { className, ...rest } = props
79 const styles = useStyles()
80 return (
81 <button {...rest} class={cx(styles().logo, className ? className() : '')}>
82 <div class={styles().tanstackLogo}>TANSTACK</div>
83 <div class={styles().routerLogo}>TanStack Router v1</div>
84 </button>
85 )
87​
88function NavigateLink(props: {
89 class?: string
90 left?: JSX.Element
91 children?: JSX.Element
92 right?: JSX.Element
93}) {
94 return (
95 <div
96 class={props.class}
97 style={{
98 display: 'flex',
99 'align-items': 'center',
100 width: '100%',
101 }}
102 >
103 {props.left}
104 <div style={{ 'flex-grow': 1, 'min-width': 0 }}>{props.children}</div>
105 {props.right}
106 </div>
107 )
109​
110function RouteComp({
111 routerState,
112 pendingMatches,
113 router,
114 route,
115 isRoot,
116 activeId,
117 setActiveId,
118}: {
119 routerState: Accessor<
120 RouterState<
121 Route<
122 any,
123 any,
124 any,
125 '/',
126 '/',
127 string,
128 '__root__',
129 undefined,
130 {},
131 {},
132 AnyContext,
133 AnyContext,
134 {},
135 undefined,
136 any,
137 FileRouteTypes,
138 unknown,
139 undefined
140 >,
141 MakeRouteMatchUnion
142 >
143 >
144 pendingMatches: Accessor<Array<AnyRouteMatch>>
145 router: Accessor<AnyRouter>
146 route: AnyRoute
147 isRoot?: boolean
148 activeId: Accessor<string | undefined>
149 setActiveId: (id: string) => void
150}) {
151 const styles = useStyles()
152 const matches = createMemo(() =>
153 pendingMatches().length ? pendingMatches() : routerState().matches,
154 )
155 const match = createMemo(() =>
156 routerState().matches.find((d) => d.routeId === route.id),
157 )
158​
159 const param = createMemo(() => {
160 try {
161 if (match()?.params) {
162 const p = match()?.params
163 const r: string = route.path || trimPath(route.id)
164 if (r.startsWith('$')) {
165 const trimmed = r.slice(1)
166​
167 if (p[trimmed]) {
168 return `(${p[trimmed]})`
169 }
170 }
171 }
172 return ''
173 } catch (error) {
174 return ''
175 }
176 })
177​
178 const navigationTarget = createMemo<string | undefined>(() => {
179 if (isRoot) return undefined // rootRouteId has no path
180 if (!route.path) return undefined // no path to navigate to
181​
182 // flatten all params in the router state, into a single object
183 const allParams = Object.assign({}, ...matches().map((m) => m.params))
184​
185 const segments = getRouteSegments(route)
186 const pathname = segments
187 ? interpolatePath(
188 route.fullPath,
189 segments,
190 allParams,
191 router().pathParamsDecoder,
192 )
193 : route.fullPath
194​
195 return segments && hasMissingPathParams(segments, allParams)
196 ? undefined
197 : pathname
198 })
199​
200 return (
201 <div>
202 <div
203 role="button"
204 aria-label={`Open match details for ${route.id}`}
205 onClick={() => {
206 if (match()) {
207 setActiveId(activeId() === route.id ? '' : route.id)
208 }
209 }}
210 class={cx(
211 styles().routesRowContainer(route.id === activeId(), !!match()),
212 )}
213 >
214 <div
215 class={cx(
216 styles().matchIndicator(getRouteStatusColor(matches(), route)),
217 )}
218 />
219 <NavigateLink
220 class={cx(styles().routesRow(!!match()))}
221 left={
222 <Show when={navigationTarget()}>
223 {(navigate) => <NavigateButton to={navigate()} router={router} />}
224 </Show>
225 }
226 right={<AgeTicker match={match()} router={router} />}
227 >
228 <code class={styles().code}>
229 {isRoot ? rootRouteId : route.path || trimPath(route.id)}{' '}
230 </code>
231 <code class={styles().routeParamInfo}>{param()}</code>
232 </NavigateLink>
233 </div>
234 {route.children?.length ? (
235 <div class={styles().nestedRouteRow(!!isRoot)}>
236 {[...(route.children as Array<AnyRoute>)]
237 .sort((a, b) => {
238 return a.rank - b.rank
239 })
240 .map((r) => (
241 <RouteComp
242 routerState={routerState}
243 pendingMatches={pendingMatches}
244 router={router}
245 route={r}
246 activeId={activeId}
247 setActiveId={setActiveId}
248 />
249 ))}
250 </div>
251 ) : null}
252 </div>
253 )
255​
256export const BaseTanStackRouterDevtoolsPanel =
257 function BaseTanStackRouterDevtoolsPanel(
258 props: BaseDevtoolsPanelOptions,
259 ): JSX.Element {
260 const [visibility, options] = splitProps(props, ['isOpen'])
261 const {
262 setIsOpen,
263 handleDragStart,
264 router,
265 routerState,
266 shadowDOMTarget,
267 ...panelProps
268 } = options
269​
270 const { onCloseClick } = useDevtoolsOnClose()
271 const styles = useStyles()
272 const { className, style, ...otherPanelProps } = panelProps
273​
274 // useStore(router.stores.__store)
275​
276 const [currentTab, setCurrentTab] = useLocalStorage<
277 'routes' | 'matches' | 'history'
278 >('tanstackRouterDevtoolsActiveTab', 'routes')
279​
280 const [activeId, setActiveId] = useLocalStorage(
281 'tanstackRouterDevtoolsActiveRouteId',
282 '',
283 )
284​
285 const [history, setHistory] = createSignal<Array<AnyRouteMatch>>([])
286 const [hasHistoryOverflowed, setHasHistoryOverflowed] = createSignal(false)
287​
288 const pendingMatches = () => {
289 const matches = routerState().matches
290 return matches.some((match: AnyRouteMatch) => match.status === 'pending')
291 ? matches
292 : []
293 }
294 let cache = router()._cache
295 let cacheMatches = [...cache.values()]
296 const [cachedMatches, setCachedMatches] = createSignal(cacheMatches)
297​
298 createEffect(() => {
299 if (visibility.isOpen === false) {
300 return
301 }
302 const refreshCache = () => {
303 const next = router()._cache
304 let valuesChanged = next.size !== cacheMatches.length
305 if (!valuesChanged) {
306 let index = 0
307 for (const match of next.values()) {
308 if (match !== cacheMatches[index++]) {
309 valuesChanged = true
310 break
311 }
312 }
313 }
314​
315 if (next !== cache || valuesChanged) {
316 cache = next
317 cacheMatches = [...next.values()]
318 setCachedMatches(cacheMatches)
319 }
320 }
321 refreshCache()
322 const interval = setInterval(refreshCache, 500)
323 onCleanup(() => clearInterval(interval))
324 })
325​
326 createEffect(() => {
327 const matches = routerState().matches
328 const currentMatch = matches[matches.length - 1]
329 if (!currentMatch) {
330 return
331 }
332 // Read history WITHOUT tracking it to avoid infinite loops
333 const historyUntracked = untrack(() => history())
334 const lastMatch = historyUntracked[0]
335 const sameLocation =
336 lastMatch &&
337 lastMatch.pathname === currentMatch.pathname &&
338 JSON.stringify(lastMatch.search ?? {}) ===
339 JSON.stringify(currentMatch.search ?? {})
340 if (!lastMatch || !sameLocation) {
341 if (historyUntracked.length >= HISTORY_LIMIT) {
342 setHasHistoryOverflowed(true)
343 }
344 setHistory((prev) => {
345 const newHistory = [currentMatch, ...prev]
346 // truncate to ensure we don't overflow too much the ui
347 newHistory.splice(HISTORY_LIMIT)
348 return newHistory
349 })
350 }
351 })
352​
353 const activeMatch = createMemo(() => {
354 const matches = [
355 ...pendingMatches(),
356 ...routerState().matches,
357 ...cachedMatches(),
358 ]
359 return matches.find(
360 (d) => d.routeId === activeId() || d.id === activeId(),
361 )
362 })
363​
364 const hasSearch = createMemo(() => hasKeys(routerState().location.search))
365​
366 const explorerState = createMemo(() => {
367 return {
368 ...router(),
369 state: routerState(),
370 }
371 })
372​
373 const routerExplorerValue = createMemo(() =>
374 Object.fromEntries(
375 multiSortBy(
376 Object.keys(explorerState()),
377 (
378 [
379 'state',
380 'routesById',
381 'routesByPath',
382 'options',
383 'manifest',
384 ] as const
385 ).map((d) => (dd) => dd !== d),
386 )
387 .map((key) => [key, (explorerState() as any)[key]])
388 .filter(
389 (d) =>
390 typeof d[1] !== 'function' &&
391 ![
392 'stores',
393 'basepath',
394 'subscribers',
395 '_scroll',
396 'tempLocationKey',
397 'latestLocation',
398 'routeTree',
399 'history',
400 ].includes(d[0]),
401 ),
402 ),
403 )
404 const activeMatchLoaderData = createMemo(() => activeMatch()?.loaderData)
405 const activeMatchValue = createMemo(() => activeMatch())
406 const locationSearchValue = createMemo(() => routerState().location.search)
407​
408 return (
409 <div
410 class={cx(
411 styles().devtoolsPanel,
412 'TanStackRouterDevtoolsPanel',
413 className ? className() : '',
414 )}
415 style={style ? style() : ''}
416 {...otherPanelProps}
417 >
418 {handleDragStart ? (
419 <div class={styles().dragHandle} onMouseDown={handleDragStart}></div>
420 ) : null}
421 <button
422 class={styles().panelCloseBtn}
423 onClick={(e: any) => {
424 if (setIsOpen) {
425 setIsOpen(false)
426 }
427 onCloseClick(e)
428 }}
429 >
430 <svg
431 xmlns="http://www.w3.org/2000/svg"
432 width="10"
433 height="6"
434 fill="none"
435 viewBox="0 0 10 6"
436 class={styles().panelCloseBtnIcon}
437 >
438 <path
439 stroke="currentColor"
440 stroke-linecap="round"
441 stroke-linejoin="round"
442 stroke-width="1.667"
443 d="M1 1l4 4 4-4"
444 ></path>
445 </svg>
446 </button>
447 <div class={styles().firstContainer}>
448 <div class={styles().row}>
449 <Logo
450 aria-hidden
451 onClick={(e: any) => {
452 if (setIsOpen) {
453 setIsOpen(false)
454 }
455 onCloseClick(e)
456 }}
457 />
458 </div>
459 <div class={styles().routerExplorerContainer}>
460 <div class={styles().routerExplorer}>
461 <Explorer
462 label="Router"
463 value={routerExplorerValue}
464 defaultExpanded={{
465 state: {} as any,
466 context: {} as any,
467 options: {} as any,
468 }}
469 filterSubEntries={(subEntries) => {
470 return subEntries.filter(
471 (d: any) => typeof d.value() !== 'function',
472 )
473 }}
474 />
475 </div>
476 </div>
477 </div>
478 <div class={styles().secondContainer}>
479 <div class={styles().matchesContainer}>
480 <div class={styles().detailsHeader}>
481 <span>Pathname</span>
482 {routerState().location.maskedLocation ? (
483 <div class={styles().maskedBadgeContainer}>
484 <span class={styles().maskedBadge}>masked</span>
485 </div>
486 ) : null}
487 </div>
488 <div class={styles().detailsContent}>
489 <code>{routerState().location.pathname}</code>
490 {routerState().location.maskedLocation ? (
491 <code class={styles().maskedLocation}>
492 {routerState().location.maskedLocation?.pathname}
493 </code>
494 ) : null}
495 </div>
496 <div class={styles().detailsHeader}>
497 <div class={styles().routeMatchesToggle}>
498 <button
499 type="button"
500 onClick={() => {
501 setCurrentTab('routes')
502 }}
503 disabled={currentTab() === 'routes'}
504 class={cx(
505 styles().routeMatchesToggleBtn(
506 currentTab() === 'routes',
507 true,
508 ),
509 )}
510 >
511 Routes
512 </button>
513 <button
514 type="button"
515 onClick={() => {
516 setCurrentTab('matches')
517 }}
518 disabled={currentTab() === 'matches'}
519 class={cx(
520 styles().routeMatchesToggleBtn(
521 currentTab() === 'matches',
522 true,
523 ),
524 )}
525 >
526 Matches
527 </button>
528 <button
529 type="button"
530 onClick={() => {
531 setCurrentTab('history')
532 }}
533 disabled={currentTab() === 'history'}
534 class={cx(
535 styles().routeMatchesToggleBtn(
536 currentTab() === 'history',
537 false,
538 ),
539 )}
540 >
541 History
542 </button>
543 </div>
544 <div class={styles().detailsHeaderInfo}>
545 <div>age / staleTime / gcTime</div>
546 </div>
547 </div>
548 <div class={cx(styles().routesContainer)}>
549 <Switch>
550 <Match when={currentTab() === 'routes'}>
551 <RouteComp
552 routerState={routerState}
553 pendingMatches={pendingMatches}
554 router={router}
555 route={router().routeTree}
556 isRoot
557 activeId={activeId}
558 setActiveId={setActiveId}
559 />
560 </Match>
561 <Match when={currentTab() === 'matches'}>
562 <div>
563 {(pendingMatches().length
564 ? pendingMatches()
565 : routerState().matches
566 ).map((match: any, _i: any) => {
567 return (
568 <div
569 role="button"
570 aria-label={`Open match details for ${match.id}`}
571 onClick={() =>
572 setActiveId(activeId() === match.id ? '' : match.id)
573 }
574 class={cx(styles().matchRow(match === activeMatch()))}
575 >
576 <div
577 class={cx(
578 styles().matchIndicator(getStatusColor(match)),
579 )}
580 />
581 <NavigateLink
582 left={
583 <NavigateButton
584 to={match.pathname}
585 params={match.params}
586 search={match.search}
587 router={router}
588 />
589 }
590 right={<AgeTicker match={match} router={router} />}
591 >
592 <code class={styles().matchID}>
593 {`${match.routeId === rootRouteId ? rootRouteId : match.pathname}`}
594 </code>
595 </NavigateLink>
596 </div>
597 )
598 })}
599 </div>
600 </Match>
601 <Match when={currentTab() === 'history'}>
602 <div>
603 <ul>
604 <For each={history()}>
605 {(match, index) => (
606 <li
607 class={cx(
608 styles().matchRow(match === activeMatch()),
609 )}
610 >
611 <div
612 class={cx(
613 styles().matchIndicator(
614 index() === 0 ? 'green' : 'gray',
615 ),
616 )}
617 />
618 <NavigateLink
619 left={
620 <NavigateButton
621 to={match.pathname}
622 params={match.params}
623 search={match.search}
624 router={router}
625 />
626 }
627 right={
628 <AgeTicker match={match} router={router} />
629 }
630 >
631 <code class={styles().matchID}>
632 {`${match.routeId === rootRouteId ? rootRouteId : match.pathname}`}
633 </code>
634 </NavigateLink>
635 </li>
636 )}
637 </For>
638 {hasHistoryOverflowed() ? (
639 <li class={styles().historyOverflowContainer}>
640 This panel displays the most recent {HISTORY_LIMIT}{' '}
641 navigations.
642 </li>
643 ) : null}
644 </ul>
645 </div>
646 </Match>
647 </Switch>
648 </div>
649 </div>
650 {cachedMatches().length ? (
651 <div class={styles().cachedMatchesContainer}>
652 <div class={styles().detailsHeader}>
653 <div>Cached Matches</div>
654 <div class={styles().detailsHeaderInfo}>
655 age / staleTime / gcTime
656 </div>
657 </div>
658 <div>
659 {cachedMatches().map((match: any) => {
660 return (
661 <div
662 role="button"
663 aria-label={`Open match details for ${match.id}`}
664 onClick={() =>
665 setActiveId(activeId() === match.id ? '' : match.id)
666 }
667 class={cx(styles().matchRow(match === activeMatch()))}
668 >
669 <div
670 class={cx(
671 styles().matchIndicator(getStatusColor(match)),
672 )}
673 />
674 <NavigateLink
675 left={
676 <NavigateButton
677 to={match.pathname}
678 params={match.params}
679 search={match.search}
680 router={router}
681 />
682 }
683 right={<AgeTicker match={match} router={router} />}
684 >
685 <code class={styles().matchID}>{`${match.id}`}</code>
686 </NavigateLink>
687 </div>
688 )
689 })}
690 </div>
691 </div>
692 ) : null}
693 </div>
694 {activeMatch() && activeMatch()?.status ? (
695 <div class={styles().thirdContainer}>
696 <div class={styles().detailsHeader}>Match Details</div>
697 <div>
698 <div class={styles().matchDetails}>
699 <div
700 class={styles().matchStatus(
701 activeMatch()?.status,
702 activeMatch()?.isFetching,
703 )}
704 >
705 <div>
706 {activeMatch()?.status === 'success' &&
707 activeMatch()?.isFetching
708 ? 'fetching'
709 : activeMatch()?.status}
710 </div>
711 </div>
712 <div class={styles().matchDetailsInfoLabel}>
713 <div>ID:</div>
714 <div class={styles().matchDetailsInfo}>
715 <code>{activeMatch()?.id}</code>
716 </div>
717 </div>
718 <div class={styles().matchDetailsInfoLabel}>
719 <div>State:</div>
720 <div class={styles().matchDetailsInfo}>
721 {pendingMatches().find(
722 (d: AnyRouteMatch) => d.id === activeMatch()?.id,
723 )
724 ? 'Pending'
725 : routerState().matches.find(
726 (d: any) => d.id === activeMatch()?.id,
727 )
728 ? 'Active'
729 : 'Cached'}
730 </div>
731 </div>
732 <div class={styles().matchDetailsInfoLabel}>
733 <div>Last Updated:</div>
734 <div class={styles().matchDetailsInfo}>
735 {activeMatch()?.updatedAt
736 ? new Date(activeMatch()?.updatedAt).toLocaleTimeString()
737 : 'N/A'}
738 </div>
739 </div>
740 </div>
741 </div>
742 {activeMatchLoaderData() ? (
743 <>
744 <div class={styles().detailsHeader}>Loader Data</div>
745 <div class={styles().detailsContent}>
746 <Explorer
747 label="loaderData"
748 value={activeMatchLoaderData}
749 defaultExpanded={{}}
750 />
751 </div>
752 </>
753 ) : null}
754 <div class={styles().detailsHeader}>Explorer</div>
755 <div class={styles().detailsContent}>
756 <Explorer
757 label="Match"
758 value={activeMatchValue}
759 defaultExpanded={{}}
760 />
761 </div>
762 </div>
763 ) : null}
764 {hasSearch() ? (
765 <div class={styles().fourthContainer}>
766 <div class={styles().detailsHeader}>
767 <span>Search Params</span>
768 {typeof navigator !== 'undefined' ? (
769 <span style="margin-left: 0.5rem;">
770 <CopyButton
771 getValue={() => {
772 const search = routerState().location.search
773 return JSON.stringify(search)
774 }}
775 />
776 </span>
777 ) : null}
778 </div>
779 <div class={styles().detailsContent}>
780 <Explorer
781 value={locationSearchValue}
782 defaultExpanded={Object.keys(
783 routerState().location.search,
784 ).reduce((obj: any, next) => {
785 obj[next] = {}
786 return obj
787 }, {})}
788 />
789 </div>
790 </div>
791 ) : null}
792 </div>
793 )
794 }
795​
796function CopyButton({ getValue }: { getValue: () => string }) {
797 const [copied, setCopied] = createSignal(false)
798​
799 let timeoutId: ReturnType<typeof setTimeout> | null = null
800​
801 const handleCopy = async () => {
802 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
803 if (typeof navigator === 'undefined' || !navigator.clipboard?.writeText) {
804 console.warn('TanStack Router Devtools: Clipboard API unavailable')
805 return
806 }
807 try {
808 const value = getValue()
809 await navigator.clipboard.writeText(value)
810 setCopied(true)
811 if (timeoutId) clearTimeout(timeoutId)
812 timeoutId = setTimeout(() => setCopied(false), 2500)
813 } catch (e) {
814 console.error('TanStack Router Devtools: Failed to copy', e)
815 }
816 }
817​
818 onCleanup(() => {
819 if (timeoutId) clearTimeout(timeoutId)
820 })
821​
822 return (
823 <button
824 type="button"
825 style="cursor: pointer;"
826 onClick={handleCopy}
827 aria-label="Copy value to clipboard"
828 title={copied() ? 'Copied!' : 'Copy'}
829 >
830 {copied() ? 'βœ…' : 'πŸ“‹'}
831 </button>
832 )
834​
835export default BaseTanStackRouterDevtoolsPanel