Open History to see the last commit
1import { stringify } from 'superjson'
2import { css } from 'goober'
3import { clsx as cx } from 'clsx'
4import { Index, Match, Show, Switch, createMemo, createSignal } from 'solid-js'
5import { Key } from '@solid-primitives/keyed'
6import { tokens } from './theme'
7import {
8 deleteNestedDataByPath,
9 displayValue,
10 updateNestedDataByPath,
11} from './utils'
12import { Check, CopiedCopier, Copier, ErrorCopier, List, Trash } from './icons'
13import { useQueryDevtoolsContext, useTheme } from './Context'
14import type { Query } from '@tanstack/query-core'
15β
16/**
17 * Chunk elements in the array by size
18 *
19 * when the array cannot be chunked evenly by size, the last chunk will be
20 * filled with the remaining elements
21 *
22 * @example
23 * chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
24 */
25export function chunkArray<T extends { label: string; value: unknown }>(
26 array: Array<T>,
27 size: number,
28): Array<Array<T>> {
29 if (size < 1) return []
30 let i = 0
31 const result: Array<Array<T>> = []
32 while (i < array.length) {
33 result.push(array.slice(i, i + size))
34 i = i + size
35 }
36 return result
37}
38β
39const Expander = (props: { expanded: boolean }) => {
40 const theme = useTheme()
41 const styles = createMemo(() => {
42 return theme() === 'dark' ? darkStyles : lightStyles
43 })
44β
45 return (
46 <span
47 class={cx(
48 styles().expander,
49 css`
50 transform: rotate(${props.expanded ? 90 : 0}deg);
51 `,
52 props.expanded &&
53 css`
54 & svg {
55 top: -1px;
56 }
57 `,
58 )}
59 >
60 <svg
61 width="16"
62 height="16"
63 viewBox="0 0 16 16"
64 fill="none"
65 xmlns="http://www.w3.org/2000/svg"
66 >
67 <path
68 d="M6 12L10 8L6 4"
69 stroke-width="2"
70 stroke-linecap="round"
71 stroke-linejoin="round"
72 />
73 </svg>
74 </span>
75 )
76}
77β
78type CopyState = 'NoCopy' | 'SuccessCopy' | 'ErrorCopy'
79const CopyButton = (props: { value: unknown }) => {
80 const theme = useTheme()
81 const styles = createMemo(() => {
82 return theme() === 'dark' ? darkStyles : lightStyles
83 })
84 const [copyState, setCopyState] = createSignal<CopyState>('NoCopy')
85β
86 return (
87 <button
88 class={styles().actionButton}
89 title="Copy object to clipboard"
90 aria-label={`${
91 copyState() === 'NoCopy'
92 ? 'Copy object to clipboard'
93 : copyState() === 'SuccessCopy'
94 ? 'Object copied to clipboard'
95 : 'Error copying object to clipboard'
96 }`}
97 onClick={
98 copyState() === 'NoCopy'
99 ? () => {
100 navigator.clipboard.writeText(stringify(props.value)).then(
101 () => {
102 setCopyState('SuccessCopy')
103 setTimeout(() => {
104 setCopyState('NoCopy')
105 }, 1500)
106 },
107 (err) => {
108 console.error('Failed to copy: ', err)
109 setCopyState('ErrorCopy')
110 setTimeout(() => {
111 setCopyState('NoCopy')
112 }, 1500)
113 },
114 )
115 }
116 : undefined
117 }
118 >
119 <Switch>
120 <Match when={copyState() === 'NoCopy'}>
121 <Copier />
122 </Match>
123 <Match when={copyState() === 'SuccessCopy'}>
124 <CopiedCopier theme={theme()} />
125 </Match>
126 <Match when={copyState() === 'ErrorCopy'}>
127 <ErrorCopier />
128 </Match>
129 </Switch>
130 </button>
131 )
132}
133β
134const ClearArrayButton = (props: {
135 dataPath: Array<string>
136 activeQuery: Query
137}) => {
138 const theme = useTheme()
139 const styles = createMemo(() => {
140 return theme() === 'dark' ? darkStyles : lightStyles
141 })
142 const queryClient = useQueryDevtoolsContext().client
143β
144 return (
145 <button
146 class={styles().actionButton}
147 title={'Remove all items'}
148 aria-label={'Remove all items'}
149 onClick={() => {
150 const oldData = props.activeQuery.state.data
151 const newData = updateNestedDataByPath(oldData, props.dataPath, [])
152 queryClient.setQueryData(props.activeQuery.queryKey, newData)
153 }}
154 >
155 <List />
156 </button>
157 )
158}
159β
160const DeleteItemButton = (props: {
161 dataPath: Array<string>
162 activeQuery: Query
163}) => {
164 const theme = useTheme()
165 const styles = createMemo(() => {
166 return theme() === 'dark' ? darkStyles : lightStyles
167 })
168 const queryClient = useQueryDevtoolsContext().client
169β
170 return (
171 <button
172 class={cx(styles().actionButton)}
173 title={'Delete item'}
174 aria-label={'Delete item'}
175 onClick={() => {
176 const oldData = props.activeQuery.state.data
177 const newData = deleteNestedDataByPath(oldData, props.dataPath)
178 queryClient.setQueryData(props.activeQuery.queryKey, newData)
179 }}
180 >
181 <Trash />
182 </button>
183 )
184}
185β
186const ToggleValueButton = (props: {
187 dataPath: Array<string>
188 activeQuery: Query
189 value: boolean
190}) => {
191 const theme = useTheme()
192 const styles = createMemo(() => {
193 return theme() === 'dark' ? darkStyles : lightStyles
194 })
195 const queryClient = useQueryDevtoolsContext().client
196β
197 return (
198 <button
199 class={cx(
200 styles().actionButton,
201 css`
202 width: ${tokens.size[3.5]};
203 height: ${tokens.size[3.5]};
204 `,
205 )}
206 title={'Toggle value'}
207 aria-label={'Toggle value'}
208 onClick={() => {
209 const oldData = props.activeQuery.state.data
210 const newData = updateNestedDataByPath(
211 oldData,
212 props.dataPath,
213 !props.value,
214 )
215 queryClient.setQueryData(props.activeQuery.queryKey, newData)
216 }}
217 >
218 <Check theme={theme()} checked={props.value} />
219 </button>
220 )
221}
222β
223type ExplorerProps = {
224 editable?: boolean
225 label: string
226 value: unknown
227 defaultExpanded?: Array<string>
228 dataPath?: Array<string>
229 activeQuery?: Query
230 itemsDeletable?: boolean
231}
232β
233function isIterable(x: any): x is Iterable<unknown> {
234 return Symbol.iterator in x
235}
236β
237export default function Explorer(props: ExplorerProps) {
238 const theme = useTheme()
239 const styles = createMemo(() => {
240 return theme() === 'dark' ? darkStyles : lightStyles
241 })
242 const queryClient = useQueryDevtoolsContext().client
243β
244 const [expanded, setExpanded] = createSignal(
245 (props.defaultExpanded || []).includes(props.label),
246 )
247 const toggleExpanded = () => setExpanded((old) => !old)
248 const [expandedPages, setExpandedPages] = createSignal<Array<number>>([])
249β
250 const subEntries = createMemo(() => {
251 if (Array.isArray(props.value)) {
252 return props.value.map((d, i) => ({
253 label: i.toString(),
254 value: d,
255 }))
256 } else if (
257 props.value !== null &&
258 typeof props.value === 'object' &&
259 isIterable(props.value) &&
260 typeof props.value[Symbol.iterator] === 'function'
261 ) {
262 if (props.value instanceof Map) {
263 return Array.from(props.value, ([key, val]) => ({
264 label: key,
265 value: val,
266 }))
267 }
268 return Array.from(props.value, (val, i) => ({
269 label: i.toString(),
270 value: val,
271 }))
272 } else if (typeof props.value === 'object' && props.value !== null) {
273 return Object.entries(props.value).map(([key, val]) => ({
274 label: key,
275 value: val,
276 }))
277 }
278 return []
279 })
280β
281 const type = createMemo<string>(() => {
282 if (Array.isArray(props.value)) {
283 return 'array'
284 } else if (
285 props.value !== null &&
286 typeof props.value === 'object' &&
287 isIterable(props.value) &&
288 typeof props.value[Symbol.iterator] === 'function'
289 ) {
290 return 'Iterable'
291 } else if (typeof props.value === 'object' && props.value !== null) {
292 return 'object'
293 }
294 return typeof props.value
295 })
296β
297 const subEntryPages = createMemo(() => chunkArray(subEntries(), 100))
298β
299 const currentDataPath = props.dataPath ?? []
300β
301 return (
302 <div class={styles().entry}>
303 <Show when={subEntryPages().length}>
304 <div class={styles().expanderButtonContainer}>
305 <button
306 class={styles().expanderButton}
307 onClick={() => toggleExpanded()}
308 >
309 <Expander expanded={expanded()} /> <span>{props.label}</span>{' '}
310 <span class={styles().info}>
311 {String(type()).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
312 {subEntries().length} {subEntries().length > 1 ? `items` : `item`}
313 </span>
314 </button>
315 <Show when={props.editable}>
316 <div class={styles().actions}>
317 <CopyButton value={props.value} />
318β
319 <Show
320 when={props.itemsDeletable && props.activeQuery !== undefined}
321 >
322 <DeleteItemButton
323 activeQuery={props.activeQuery!}
324 dataPath={currentDataPath}
325 />
326 </Show>
327β
328 <Show
329 when={type() === 'array' && props.activeQuery !== undefined}
330 >
331 <ClearArrayButton
332 activeQuery={props.activeQuery!}
333 dataPath={currentDataPath}
334 />
335 </Show>
336 </div>
337 </Show>
338 </div>
339 <Show when={expanded()}>
340 <Show when={subEntryPages().length === 1}>
341 <div class={styles().subEntry}>
342 <Key each={subEntries()} by={(item) => item.label}>
343 {(entry) => {
344 return (
345 <Explorer
346 defaultExpanded={props.defaultExpanded}
347 label={entry().label}
348 value={entry().value}
349 editable={props.editable}
350 dataPath={[...currentDataPath, entry().label]}
351 activeQuery={props.activeQuery}
352 itemsDeletable={
353 type() === 'array' ||
354 type() === 'Iterable' ||
355 type() === 'object'
356 }
357 />
358 )
359 }}
360 </Key>
361 </div>
362 </Show>
363 <Show when={subEntryPages().length > 1}>
364 <div class={styles().subEntry}>
365 <Index each={subEntryPages()}>
366 {(entries, index) => (
367 <div>
368 <div class={styles().entry}>
369 <button
370 onClick={() =>
371 setExpandedPages((old) =>
372 old.includes(index)
373 ? old.filter((d) => d !== index)
374 : [...old, index],
375 )
376 }
377 class={styles().expanderButton}
378 >
379 <Expander expanded={expandedPages().includes(index)} />{' '}
380 [{index * 100}...
381 {index * 100 + 100 - 1}]
382 </button>
383 <Show when={expandedPages().includes(index)}>
384 <div class={styles().subEntry}>
385 <Key each={entries()} by={(entry) => entry.label}>
386 {(entry) => (
387 <Explorer
388 defaultExpanded={props.defaultExpanded}
389 label={entry().label}
390 value={entry().value}
391 editable={props.editable}
392 dataPath={[...currentDataPath, entry().label]}
393 activeQuery={props.activeQuery}
394 />
395 )}
396 </Key>
397 </div>
398 </Show>
399 </div>
400 </div>
401 )}
402 </Index>
403 </div>
404 </Show>
405 </Show>
406 </Show>
407 <Show when={subEntryPages().length === 0}>
408 <div class={styles().row}>
409 <span class={styles().label}>{props.label}:</span>
410 <Show
411 when={
412 props.editable &&
413 props.activeQuery !== undefined &&
414 (type() === 'string' ||
415 type() === 'number' ||
416 type() === 'boolean')
417 }
418 fallback={
419 <span class={styles().value}>{displayValue(props.value)}</span>
420 }
421 >
422 <Show
423 when={
424 props.editable &&
425 props.activeQuery !== undefined &&
426 (type() === 'string' || type() === 'number')
427 }
428 >
429 <input
430 type={type() === 'number' ? 'number' : 'text'}
431 class={cx(styles().value, styles().editableInput)}
432 value={props.value as string | number}
433 onChange={(changeEvent) => {
434 const oldData = props.activeQuery!.state.data
435β
436 const newData = updateNestedDataByPath(
437 oldData,
438 currentDataPath,
439 type() === 'number'
440 ? changeEvent.target.valueAsNumber
441 : changeEvent.target.value,
442 )
443β
444 queryClient.setQueryData(props.activeQuery!.queryKey, newData)
445 }}
446 />
447 </Show>
448β
449 <Show when={type() === 'boolean'}>
450 <span
451 class={cx(
452 styles().value,
453 styles().actions,
454 styles().editableInput,
455 )}
456 >
457 <ToggleValueButton
458 activeQuery={props.activeQuery!}
459 dataPath={currentDataPath}
460 value={props.value as boolean}
461 />
462 {displayValue(props.value)}
463 </span>
464 </Show>
465 </Show>
466β
467 <Show
468 when={
469 props.editable &&
470 props.itemsDeletable &&
471 props.activeQuery !== undefined
472 }
473 >
474 <DeleteItemButton
475 activeQuery={props.activeQuery!}
476 dataPath={currentDataPath}
477 />
478 </Show>
479 </div>
480 </Show>
481 </div>
482 )
483}
484β
485const stylesFactory = (theme: 'light' | 'dark') => {
486 const { colors, font, size, border } = tokens
487 const t = (light: string, dark: string) => (theme === 'light' ? light : dark)
488 return {
489 entry: css`
490 & * {
491 font-size: ${font.size.xs};
492 font-family: 'Menlo', 'Fira Code', monospace;
493 }
494 position: relative;
495 outline: none;
496 word-break: break-word;
497 `,
498 subEntry: css`
499 margin: 0 0 0 0.5em;
500 padding-left: 0.75em;
501 border-left: 2px solid ${t(colors.gray[300], colors.darkGray[400])};
502 /* outline: 1px solid ${colors.teal[400]}; */
503 `,
504 expander: css`
505 & path {
506 stroke: ${colors.gray[400]};
507 }
508 & svg {
509 width: ${size[3]};
510 height: ${size[3]};
511 }
512 display: inline-flex;
513 align-items: center;
514 transition: all 0.1s ease;
515 /* outline: 1px solid ${colors.blue[400]}; */
516 `,
517 expanderButtonContainer: css`
518 display: flex;
519 align-items: center;
520 line-height: 1.125rem;
521 min-height: 1.125rem;
522 gap: ${size[2]};
523 `,
524 expanderButton: css`
525 cursor: pointer;
526 color: inherit;
527 font: inherit;
528 outline: inherit;
529 height: 1rem;
530 background: transparent;
531 border: none;
532 padding: 0;
533 display: inline-flex;
534 align-items: center;
535 gap: ${size[1]};
536 position: relative;
537 /* outline: 1px solid ${colors.green[400]}; */
538β
539 &:focus-visible {
540 border-radius: ${border.radius.xs};
541 outline: 2px solid ${colors.blue[800]};
542 }
543β
544 & svg {
545 position: relative;
546 left: 1px;
547 }
548 `,
549 info: css`
550 color: ${t(colors.gray[500], colors.gray[500])};
551 font-size: ${font.size.xs};
552 margin-left: ${size[1]};
553 /* outline: 1px solid ${colors.yellow[400]}; */
554 `,
555 label: css`
556 color: ${t(colors.gray[700], colors.gray[300])};
557 `,
558 value: css`
559 color: ${t(colors.purple[600], colors.purple[400])};
560 flex-grow: 1;
561 `,
562 actions: css`
563 display: inline-flex;
564 gap: ${size[2]};
565 align-items: center;
566 `,
567 row: css`
568 display: inline-flex;
569 gap: ${size[2]};
570 width: 100%;
571 margin-bottom: ${size[0.5]};
572 line-height: 1.125rem;
573 align-items: center;
574 `,
575 editableInput: css`
576 border: none;
577 padding: ${size[0.5]} ${size[1]} ${size[0.5]} ${size[1.5]};
578 flex-grow: 1;
579 border-radius: ${border.radius.xs};
580 background-color: ${t(colors.gray[200], colors.darkGray[500])};
581β
582 &:hover {
583 background-color: ${t(colors.gray[300], colors.darkGray[600])};
584 }
585 `,
586 actionButton: css`
587 background-color: transparent;
588 color: ${t(colors.gray[500], colors.gray[500])};
589 border: none;
590 display: inline-flex;
591 padding: 0px;
592 align-items: center;
593 justify-content: center;
594 cursor: pointer;
595 width: ${size[3]};
596 height: ${size[3]};
597 position: relative;
598 z-index: 1;
599β
600 &:hover svg {
601 color: ${t(colors.gray[600], colors.gray[400])};
602 }
603β
604 &:focus-visible {
605 border-radius: ${border.radius.xs};
606 outline: 2px solid ${colors.blue[800]};
607 outline-offset: 2px;
608 }
609 `,
610 }
611}
612β
613const lightStyles = stylesFactory('light')
614const darkStyles = stylesFactory('dark')