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