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