Open History to see the last commit
1import { TanStackDevtoolsCore } from '@tanstack/devtools'
2import * as Solid from 'solid-js'
3import type {
4 ClientEventBusConfig,
5 TanStackDevtoolsConfig,
6 TanStackDevtoolsPlugin,
7 TanStackDevtoolsPluginProps,
8 TanStackDevtoolsTheme,
9} from '@tanstack/devtools'
10β
11// This file works with Solid 1 and Solid 2, so it uses only the `solid-js`
12// APIs that both have, and no JSX (the two compilers emit different code).
13const { children, createMemo, createRoot, getOwner, onCleanup, runWithOwner } =
14 Solid
15β
16/**
17 * Runs `apply` with the value of `compute` now and each time it changes.
18 * Solid 2 splits an effect into these two functions; Solid 1 runs one
19 * function, so the tracked read and the untracked write go in it in order.
20 */
21const isSolid2: boolean = 'onSettled' in Solid
22function watch<T>(compute: () => T, apply: (value: T) => void) {
23 if (isSolid2) {
24 ;(Solid.createEffect as any)(compute, apply)
25 } else {
26 ;(Solid.createEffect as any)(() => {
27 const value = compute()
28 Solid.untrack(() => apply(value))
29 })
30 }
31}
32β
33/**
34 * Puts `values` into `el` in order. Nodes that are already in place stay
35 * attached, so an input that is not replaced keeps its focus. Only nodes that
36 * this function put in `el` are removed.
37 */
38function place(el: Element, current: Array<Node>, values: Array<unknown>) {
39 const next = values.flatMap((value) =>
40 value instanceof Node
41 ? [value]
42 : typeof value === 'string' || typeof value === 'number'
43 ? [document.createTextNode(String(value))]
44 : [],
45 )
46 for (const node of current) {
47 if (!next.includes(node) && node.parentNode === el) el.removeChild(node)
48 }
49 let anchor: Node | null = null
50 for (let i = next.length - 1; i >= 0; i--) {
51 const node = next[i]!
52 if (node.parentNode !== el || node.nextSibling !== anchor) {
53 el.insertBefore(node, anchor)
54 }
55 anchor = node
56 }
57 return next
58}
59β
60/**
61 * A Solid element: `JSX.Element` in Solid 1, `Element` in Solid 2. It has no
62 * function type in it, so TypeScript can still type the `render` callback.
63 */
64type SolidElement = object | string | number | boolean | null | undefined
65β
66type SolidPluginRender =
67 | SolidElement
68 | ((
69 el: HTMLDivElement | HTMLHeadingElement,
70 props: TanStackDevtoolsPluginProps,
71 ) => SolidElement)
72export type TanStackDevtoolsSolidPlugin = Omit<
73 TanStackDevtoolsPlugin,
74 'render' | 'name'
75> & {
76 /**
77 * The render function can be a SolidJS element or a function that returns a SolidJS element.
78 * If it's a function, it will be called to render the plugin, otherwise it will be rendered directly.
79 *
80 * Example:
81 * ```ts
82 * {
83 * render: () => <CustomPluginComponent />,
84 * }
85 * ```
86 * or
87 * ```ts
88 * {
89 * render: <CustomPluginComponent />,
90 * }
91 * ```
92 */
93 render: SolidPluginRender
94 /**
95 * Name to be displayed in the devtools UI.
96 * If a string, it will be used as the plugin name.
97 * If a function, it will be called with the mount element.
98 *
99 * Example:
100 * ```ts
101 * {
102 * name: "Your Plugin",
103 * render: () => <CustomPluginComponent />,
104 * }
105 * ```
106 * or
107 * ```ts
108 * {
109 * name: <h1>Your Plugin title</h1>,
110 * render: () => <CustomPluginComponent />,
111 * }
112 * ```
113 */
114 name: string | SolidPluginRender
115}
116interface TriggerProps {
117 theme: TanStackDevtoolsTheme
118}
119interface TanStackDevtoolsInit {
120 /**
121 * Array of plugins to be used in the devtools.
122 * Each plugin should have a `render` function that returns a Solid element or a function
123 *
124 * Example:
125 * ```jsx
126 * <TanStackDevtools
127 * plugins={[
128 * {
129 * id: "your-plugin-id",
130 * name: "Your Plugin",
131 * render: <CustomPluginComponent />,
132 * }
133 * ]}
134 * />
135 * ```
136 */
137 plugins?: Array<TanStackDevtoolsSolidPlugin>
138 /**
139 * Configuration for the devtools shell. These configuration options are used to set the
140 * initial state of the devtools when it is started for the first time. Afterwards,
141 * the settings are persisted in local storage and changed through the settings panel.
142 */
143 config?: Omit<Partial<TanStackDevtoolsConfig>, 'customTrigger'> & {
144 /**
145 * An optional custom function to render the dev tools trigger component.
146 */
147 customTrigger?:
148 | ((el: HTMLElement, props: TriggerProps) => SolidElement)
149 | SolidElement
150 }
151 /**
152 * Configuration for the TanStack Devtools client event bus.
153 */
154 eventBusConfig?: ClientEventBusConfig
155}
156β
157/**
158 * Renders nothing. After the first render it mounts the devtools shell into an
159 * element at the end of `<body>`, so server and client output always match.
160 */
161export default function SolidDevtoolsCore(props: TanStackDevtoolsInit) {
162 // The shell calls `render`, `name` and `customTrigger` from its own
163 // effects, on its own copy of Solid. Each mount node gets a root owned by
164 // this component, so plugins see the app's context and are disposed with
165 // it. A new call replaces the node's previous root.
166 const owner = getOwner()
167 const mounts = new Map<Element, () => void>()
168 const mountInto = (el: Element, content: () => unknown) => {
169 mounts.get(el)?.()
170 runWithOwner(owner, () =>
171 createRoot((dispose) => {
172 mounts.set(el, () => {
173 dispose()
174 el.replaceChildren()
175 mounts.delete(el)
176 })
177 const resolved = children(content as () => any)
178 // Insert the first nodes now, before the plugin's `onMount` runs, so
179 // it finds them in the document. The effect then applies updates.
180 let current = place(el, [], Solid.untrack(resolved.toArray))
181 watch(resolved.toArray, (nodes) => {
182 current = place(el, current, nodes)
183 })
184 }),
185 )
186 }
187 const convertRender = (
188 el: HTMLDivElement | HTMLHeadingElement,
189 Component: SolidPluginRender,
190 renderProps: TanStackDevtoolsPluginProps,
191 ) =>
192 mountInto(el, () =>
193 typeof Component === 'function' ? Component(el, renderProps) : Component,
194 )
195β
196 // Convert plugins to the format expected by the core
197 const pluginsMap = createMemo<Array<TanStackDevtoolsPlugin> | undefined>(() =>
198 props.plugins?.map((plugin) => {
199 // The pane elements of this plugin. The shell calls `destroy` when a
200 // pane closes, so their roots are disposed then.
201 // ponytail: title roots stay until the adapter unmounts, because the
202 // shell does not say when a title element goes away.
203 const panes = new Set<Element>()
204 return {
205 ...plugin,
206 name:
207 typeof plugin.name === 'string'
208 ? plugin.name
209 : (el, renderProps) => convertRender(el, plugin.name, renderProps),
210 render: (
211 el: HTMLDivElement,
212 renderProps: TanStackDevtoolsPluginProps,
213 ) => {
214 panes.add(el)
215 convertRender(el, plugin.render, renderProps)
216 },
217 destroy: (pluginId: string) => {
218 for (const el of panes) mounts.get(el)?.()
219 panes.clear()
220 plugin.destroy?.(pluginId)
221 },
222 }
223 }),
224 )
225β
226 const convertTrigger = (el: HTMLElement, triggerProps: TriggerProps) => {
227 const Trigger = props.config?.customTrigger
228 mountInto(el, () =>
229 typeof Trigger === 'function' ? Trigger(el, triggerProps) : Trigger,
230 )
231 }
232 const shellConfig = (): Partial<TanStackDevtoolsConfig> => ({
233 ...props.config,
234 customTrigger: props.config?.customTrigger
235 ? (el, triggerProps) => convertTrigger(el, triggerProps)
236 : undefined,
237 })
238β
239 let core: TanStackDevtoolsCore | undefined
240 let host: HTMLDivElement | undefined
241 // Effects run only in the browser and after the first render, so this is
242 // where the shell is created and mounted. Later runs pass on new config.
243 watch(
244 () => ({ config: shellConfig(), eventBusConfig: props.eventBusConfig }),
245 ({ config, eventBusConfig }) => {
246 if (core) {
247 core.setConfig({ config })
248 return
249 }
250 host = document.createElement('div')
251 document.body.append(host)
252 core = new TanStackDevtoolsCore({
253 config,
254 eventBusConfig,
255 plugins: Solid.untrack(pluginsMap),
256 })
257 core.mount(host)
258 },
259 )
260 // Update plugins when they change
261 watch(pluginsMap, (plugins) => {
262 if (plugins) core?.setConfig({ plugins })
263 })
264β
265 onCleanup(() => {
266 core?.unmount()
267 host?.remove()
268 core = undefined
269 for (const dispose of mounts.values()) dispose()
270 mounts.clear()
271 })
272 return null
273}