|
1 | 1 | import React, { useEffect, useRef, useState } from 'react' |
2 | 2 | import { TanStackRouterDevtoolsCore } from '@tanstack/devtools' |
3 | | -import type { DevtoolsOptions } from '@tanstack/devtools' |
| 3 | +import { createRoot } from 'react-dom/client' |
| 4 | +import type { JSX } from 'react' |
| 5 | +import type { DevtoolsOptions, DevtoolsPlugin } from '@tanstack/devtools' |
4 | 6 |
|
5 | | -export const Devtools = (opts: DevtoolsOptions) => { |
| 7 | +type Render = JSX.Element | (() => JSX.Element) |
| 8 | +type ReactPlugin = Omit<DevtoolsPlugin, 'render' | 'name'> & { |
| 9 | + render: Render |
| 10 | + name: string | Render |
| 11 | +} |
| 12 | +interface DevtoolsProps { |
| 13 | + plugins?: Array<ReactPlugin> |
| 14 | + options?: DevtoolsOptions['options'] |
| 15 | +} |
| 16 | + |
| 17 | +const convertRender = ( |
| 18 | + el: HTMLDivElement | HTMLHeadingElement, |
| 19 | + Component: Render, |
| 20 | +) => { |
| 21 | + const domNode = document.createElement('div') |
| 22 | + const root = createRoot(domNode) |
| 23 | + root.render(typeof Component === 'function' ? <Component /> : Component) |
| 24 | + el.appendChild(domNode) |
| 25 | +} |
| 26 | + |
| 27 | +export const Devtools = ({ plugins, options }: DevtoolsProps) => { |
6 | 28 | const devToolRef = useRef<HTMLDivElement>(null) |
7 | | - const [devtools] = useState(() => new TanStackRouterDevtoolsCore(opts)) |
| 29 | + const [devtools] = useState( |
| 30 | + () => |
| 31 | + new TanStackRouterDevtoolsCore({ |
| 32 | + options, |
| 33 | + plugins: plugins?.map((plugin) => { |
| 34 | + return { |
| 35 | + ...plugin, |
| 36 | + name: |
| 37 | + typeof plugin.name === 'string' |
| 38 | + ? plugin.name |
| 39 | + : // The check above confirms that `plugin.name` is of Render type |
| 40 | + (el) => convertRender(el, plugin.name as Render), |
| 41 | + render: (el: HTMLDivElement) => convertRender(el, plugin.render), |
| 42 | + } |
| 43 | + }), |
| 44 | + }), |
| 45 | + ) |
8 | 46 | useEffect(() => { |
9 | 47 | if (devToolRef.current) { |
10 | 48 | devtools.mount(devToolRef.current) |
|
0 commit comments