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

BaseTanStackRouterDevtoolsPanel.tsx

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