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

panel.tsx

58 lines1.9 KB

1/** @jsxImportSource preact */
2​
3import { useEffect, useRef } from 'preact/hooks'
4import type { TanStackDevtoolsPluginProps } from '@tanstack/devtools'
5​
6export interface DevtoolsPanelProps extends TanStackDevtoolsPluginProps {}
7​
8/**
9 * Creates a Preact component that dynamically imports and mounts a devtools panel. SSR friendly.
10 * @param devtoolsPackageName The name of the devtools package to be imported, e.g., '@tanstack/devtools-preact'
11 * @param importName The name of the export to be imported from the devtools package (e.g., 'default' or 'DevtoolsCore')
12 * @returns A Preact component that mounts the devtools
13 * @example
14 * ```tsx
15 * // if the export is default
16 * const [PreactDevtoolsPanel, NoOpPreactDevtoolsPanel] = createPreactPanel('@tanstack/devtools-preact')
17 * ```
18 *
19 * @example
20 * ```tsx
21 * // if the export is named differently
22 * const [PreactDevtoolsPanel, NoOpPreactDevtoolsPanel] = createPreactPanel('@tanstack/devtools-preact', 'DevtoolsCore')
23 * ```
24 */
25export function createPreactPanel<
26 TComponentProps extends DevtoolsPanelProps,
27 TCoreDevtoolsClass extends {
28 mount: (el: HTMLElement, props: TanStackDevtoolsPluginProps) => void
29 unmount: () => void
30 },
31>(CoreClass: new () => TCoreDevtoolsClass) {
32 function Panel(props: TComponentProps) {
33 const devToolRef = useRef<HTMLDivElement>(null)
34 const devtools = useRef<TCoreDevtoolsClass | null>(null)
35 useEffect(() => {
36 if (devtools.current) return
37 devtools.current = new CoreClass()
38​
39 if (devToolRef.current) {
40 devtools.current.mount(devToolRef.current, props)
41 }
42​
43 return () => {
44 if (devToolRef.current) {
45 devtools.current?.unmount()
46 devtools.current = null
47 }
48 }
49 }, [props])
50​
51 return <div style={{ height: '100%' }} ref={devToolRef} />
52 }
53​
54 function NoOpPanel(_props: TComponentProps) {
55 return <></>
56 }
57 return [Panel, NoOpPanel] as const