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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
import { serialize, stringify } from 'superjson'
import { clsx as cx } from 'clsx'
import { Index, Match, Show, Switch, createMemo, createSignal } from 'solid-js'
import { Key } from '@solid-primitives/keyed'
import * as goober from 'goober'
import { tokens } from './theme'
import {
  deleteNestedDataByPath,
  displayValue,
  updateNestedDataByPath,
} from './utils'
import {
  Check,
  CopiedCopier,
  Copier,
  ErrorCopier,
  List,
  Pencil,
  Trash,
} from './icons'
import { useQueryDevtoolsContext, useTheme } from './contexts'
import type { Query } from '@tanstack/query-core'

/**
 * Chunk elements in the array by size
 *
 * when the array cannot be chunked evenly by size, the last chunk will be
 * filled with the remaining elements
 *
 * @example
 * chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
 */
function chunkArray<T extends { label: string; value: unknown }>(
  array: Array<T>,
  size: number,
): Array<Array<T>> {
  if (size < 1) return []
  let i = 0
  const result: Array<Array<T>> = []
  while (i < array.length) {
    result.push(array.slice(i, i + size))
    i = i + size
  }
  return result
}

const Expander = (props: { expanded: boolean }) => {
  const theme = useTheme()
  const css = useQueryDevtoolsContext().shadowDOMTarget
    ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
    : goober.css
  const styles = createMemo(() => {
    return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
  })

  return (
    <span
      class={cx(
        styles().expander,
        css`
          transform: rotate(${props.expanded ? 90 : 0}deg);
        `,
        props.expanded &&
          css`
            & svg {
              top: -1px;
            }
          `,
      )}
    >
      <svg
        width="16"
        height="16"
        viewBox="0 0 16 16"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          d="M6 12L10 8L6 4"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        />
      </svg>
    </span>
  )
}

type CopyState = 'NoCopy' | 'SuccessCopy' | 'ErrorCopy'
const CopyButton = (props: { value: unknown }) => {
  const theme = useTheme()
  const css = useQueryDevtoolsContext().shadowDOMTarget
    ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
    : goober.css
  const styles = createMemo(() => {
    return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
  })
  const [copyState, setCopyState] = createSignal<CopyState>('NoCopy')

  return (
    <button
      class={styles().actionButton}
      title="Copy object to clipboard"
      aria-label={`${
        copyState() === 'NoCopy'
          ? 'Copy object to clipboard'
          : copyState() === 'SuccessCopy'
            ? 'Object copied to clipboard'
            : 'Error copying object to clipboard'
      }`}
      onClick={
        copyState() === 'NoCopy'
          ? () => {
              navigator.clipboard.writeText(stringify(props.value)).then(
                () => {
                  setCopyState('SuccessCopy')
                  setTimeout(() => {
                    setCopyState('NoCopy')
                  }, 1500)
                },
                (err) => {
                  console.error('Failed to copy: ', err)
                  setCopyState('ErrorCopy')
                  setTimeout(() => {
                    setCopyState('NoCopy')
                  }, 1500)
                },
              )
            }
          : undefined
      }
    >
      <Switch>
        <Match when={copyState() === 'NoCopy'}>
          <Copier />
        </Match>
        <Match when={copyState() === 'SuccessCopy'}>
          <CopiedCopier theme={theme()} />
        </Match>
        <Match when={copyState() === 'ErrorCopy'}>
          <ErrorCopier />
        </Match>
      </Switch>
    </button>
  )
}

const ClearArrayButton = (props: {
  dataPath: Array<string>
  activeQuery: Query
}) => {
  const theme = useTheme()
  const css = useQueryDevtoolsContext().shadowDOMTarget
    ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
    : goober.css
  const styles = createMemo(() => {
    return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
  })
  const queryClient = useQueryDevtoolsContext().client

  return (
    <button
      class={styles().actionButton}
      title={'Remove all items'}
      aria-label={'Remove all items'}
      onClick={() => {
        const oldData = props.activeQuery.state.data
        const newData = updateNestedDataByPath(oldData, props.dataPath, [])
        queryClient.setQueryData(props.activeQuery.queryKey, newData)
      }}
    >
      <List />
    </button>
  )
}

const DeleteItemButton = (props: {
  dataPath: Array<string>
  activeQuery: Query
}) => {
  const theme = useTheme()
  const css = useQueryDevtoolsContext().shadowDOMTarget
    ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
    : goober.css
  const styles = createMemo(() => {
    return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
  })
  const queryClient = useQueryDevtoolsContext().client

  return (
    <button
      class={cx(styles().actionButton)}
      title={'Delete item'}
      aria-label={'Delete item'}
      onClick={() => {
        const oldData = props.activeQuery.state.data
        const newData = deleteNestedDataByPath(oldData, props.dataPath)
        queryClient.setQueryData(props.activeQuery.queryKey, newData)
      }}
    >
      <Trash />
    </button>
  )
}

const ToggleValueButton = (props: {
  dataPath: Array<string>
  activeQuery: Query
  value: boolean
}) => {
  const theme = useTheme()
  const css = useQueryDevtoolsContext().shadowDOMTarget
    ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
    : goober.css
  const styles = createMemo(() => {
    return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
  })
  const queryClient = useQueryDevtoolsContext().client

  return (
    <button
      class={cx(
        styles().actionButton,
        css`
          width: ${tokens.size[3.5]};
          height: ${tokens.size[3.5]};
        `,
      )}
      title={'Toggle value'}
      aria-label={'Toggle value'}
      onClick={() => {
        const oldData = props.activeQuery.state.data
        const newData = updateNestedDataByPath(
          oldData,
          props.dataPath,
          !props.value,
        )
        queryClient.setQueryData(props.activeQuery.queryKey, newData)
      }}
    >
      <Check theme={theme()} checked={props.value} />
    </button>
  )
}

type ExplorerProps = {
  editable?: boolean
  label: string
  value: unknown
  defaultExpanded?: Array<string>
  dataPath?: Array<string>
  activeQuery?: Query
  itemsDeletable?: boolean
  onEdit?: () => void
}

function isIterable(x: any): x is Iterable<unknown> {
  return Symbol.iterator in x
}

export default function Explorer(props: ExplorerProps) {
  const theme = useTheme()
  const css = useQueryDevtoolsContext().shadowDOMTarget
    ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
    : goober.css
  const styles = createMemo(() => {
    return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
  })
  const queryClient = useQueryDevtoolsContext().client

  const [expanded, setExpanded] = createSignal(
    (props.defaultExpanded || []).includes(props.label),
  )
  const toggleExpanded = () => setExpanded((old) => !old)
  const [expandedPages, setExpandedPages] = createSignal<Array<number>>([])

  const subEntries = createMemo(() => {
    if (Array.isArray(props.value)) {
      return props.value.map((d, i) => ({
        label: i.toString(),
        value: d,
      }))
    } else if (
      props.value !== null &&
      typeof props.value === 'object' &&
      isIterable(props.value) &&
      typeof props.value[Symbol.iterator] === 'function'
    ) {
      if (props.value instanceof Map) {
        return Array.from(props.value, ([key, val]) => ({
          label: key,
          value: val,
        }))
      }
      return Array.from(props.value, (val, i) => ({
        label: i.toString(),
        value: val,
      }))
    } else if (typeof props.value === 'object' && props.value !== null) {
      return Object.entries(props.value).map(([key, val]) => ({
        label: key,
        value: val,
      }))
    }
    return []
  })

  const type = createMemo<string>(() => {
    if (Array.isArray(props.value)) {
      return 'array'
    } else if (
      props.value !== null &&
      typeof props.value === 'object' &&
      isIterable(props.value) &&
      typeof props.value[Symbol.iterator] === 'function'
    ) {
      return 'Iterable'
    } else if (typeof props.value === 'object' && props.value !== null) {
      return 'object'
    }
    return typeof props.value
  })

  const subEntryPages = createMemo(() => chunkArray(subEntries(), 100))

  const currentDataPath = props.dataPath ?? []

  return (
    <div class={styles().entry}>
      <Show when={subEntryPages().length}>
        <div class={styles().expanderButtonContainer}>
          <button
            class={styles().expanderButton}
            onClick={() => toggleExpanded()}
          >
            <Expander expanded={expanded()} /> <span>{props.label}</span>{' '}
            <span class={styles().info}>
              {String(type()).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
              {subEntries().length} {subEntries().length > 1 ? `items` : `item`}
            </span>
          </button>
          <Show when={props.editable}>
            <div class={styles().actions}>
              <CopyButton value={props.value} />

              <Show
                when={props.itemsDeletable && props.activeQuery !== undefined}
              >
                <DeleteItemButton
                  activeQuery={props.activeQuery!}
                  dataPath={currentDataPath}
                />
              </Show>

              <Show
                when={type() === 'array' && props.activeQuery !== undefined}
              >
                <ClearArrayButton
                  activeQuery={props.activeQuery!}
                  dataPath={currentDataPath}
                />
              </Show>

              <Show when={!!props.onEdit && !serialize(props.value).meta}>
                <button
                  class={styles().actionButton}
                  title={'Bulk Edit Data'}
                  aria-label={'Bulk Edit Data'}
                  onClick={() => {
                    props.onEdit?.()
                  }}
                >
                  <Pencil />
                </button>
              </Show>
            </div>
          </Show>
        </div>
        <Show when={expanded()}>
          <Show when={subEntryPages().length === 1}>
            <div class={styles().subEntry}>
              <Key each={subEntries()} by={(item) => item.label}>
                {(entry) => {
                  return (
                    <Explorer
                      defaultExpanded={props.defaultExpanded}
                      label={entry().label}
                      value={entry().value}
                      editable={props.editable}
                      dataPath={[...currentDataPath, entry().label]}
                      activeQuery={props.activeQuery}
                      itemsDeletable={
                        type() === 'array' ||
                        type() === 'Iterable' ||
                        type() === 'object'
                      }
                    />
                  )
                }}
              </Key>
            </div>
          </Show>
          <Show when={subEntryPages().length > 1}>
            <div class={styles().subEntry}>
              <Index each={subEntryPages()}>
                {(entries, index) => (
                  <div>
                    <div class={styles().entry}>
                      <button
                        onClick={() =>
                          setExpandedPages((old) =>
                            old.includes(index)
                              ? old.filter((d) => d !== index)
                              : [...old, index],
                          )
                        }
                        class={styles().expanderButton}
                      >
                        <Expander expanded={expandedPages().includes(index)} />{' '}
                        [{index * 100}...
                        {index * 100 + 100 - 1}]
                      </button>
                      <Show when={expandedPages().includes(index)}>
                        <div class={styles().subEntry}>
                          <Key each={entries()} by={(entry) => entry.label}>
                            {(entry) => (
                              <Explorer
                                defaultExpanded={props.defaultExpanded}
                                label={entry().label}
                                value={entry().value}
                                editable={props.editable}
                                dataPath={[...currentDataPath, entry().label]}
                                activeQuery={props.activeQuery}
                              />
                            )}
                          </Key>
                        </div>
                      </Show>
                    </div>
                  </div>
                )}
              </Index>
            </div>
          </Show>
        </Show>
      </Show>
      <Show when={subEntryPages().length === 0}>
        <div class={styles().row}>
          <span class={styles().label}>{props.label}:</span>
          <Show
            when={
              props.editable &&
              props.activeQuery !== undefined &&
              (type() === 'string' ||
                type() === 'number' ||
                type() === 'boolean')
            }
            fallback={
              <span class={styles().value}>{displayValue(props.value)}</span>
            }
          >
            <Show
              when={
                props.editable &&
                props.activeQuery !== undefined &&
                (type() === 'string' || type() === 'number')
              }
            >
              <input
                type={type() === 'number' ? 'number' : 'text'}
                class={cx(styles().value, styles().editableInput)}
                value={props.value as string | number}
                onChange={(changeEvent) => {
                  const oldData = props.activeQuery!.state.data

                  const newData = updateNestedDataByPath(
                    oldData,
                    currentDataPath,
                    type() === 'number'
                      ? changeEvent.target.valueAsNumber
                      : changeEvent.target.value,
                  )

                  queryClient.setQueryData(props.activeQuery!.queryKey, newData)
                }}
              />
            </Show>

            <Show when={type() === 'boolean'}>
              <span
                class={cx(
                  styles().value,
                  styles().actions,
                  styles().editableInput,
                )}
              >
                <ToggleValueButton
                  activeQuery={props.activeQuery!}
                  dataPath={currentDataPath}
                  value={props.value as boolean}
                />
                {displayValue(props.value)}
              </span>
            </Show>
          </Show>

          <Show
            when={
              props.editable &&
              props.itemsDeletable &&
              props.activeQuery !== undefined
            }
          >
            <DeleteItemButton
              activeQuery={props.activeQuery!}
              dataPath={currentDataPath}
            />
          </Show>
        </div>
      </Show>
    </div>
  )
}

const stylesFactory = (
  theme: 'light' | 'dark',
  css: (typeof goober)['css'],
) => {
  const { colors, font, size, border } = tokens
  const t = (light: string, dark: string) => (theme === 'light' ? light : dark)
  return {
    entry: css`
      & * {
        font-size: ${font.size.xs};
        font-family:
          ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
          'Liberation Mono', 'Courier New', monospace;
      }
      position: relative;
      outline: none;
      word-break: break-word;
    `,
    subEntry: css`
      margin: 0 0 0 0.5em;
      padding-left: 0.75em;
      border-left: 2px solid ${t(colors.gray[300], colors.darkGray[400])};
      /* outline: 1px solid ${colors.teal[400]}; */
    `,
    expander: css`
      & path {
        stroke: ${colors.gray[400]};
      }
      & svg {
        width: ${size[3]};
        height: ${size[3]};
      }
      display: inline-flex;
      align-items: center;
      transition: all 0.1s ease;
      /* outline: 1px solid ${colors.blue[400]}; */
    `,
    expanderButtonContainer: css`
      display: flex;
      align-items: center;
      line-height: ${size[4]};
      min-height: ${size[4]};
      gap: ${size[2]};
    `,
    expanderButton: css`
      cursor: pointer;
      color: inherit;
      font: inherit;
      outline: inherit;
      height: ${size[5]};
      background: transparent;
      border: none;
      padding: 0;
      display: inline-flex;
      align-items: center;
      gap: ${size[1]};
      position: relative;
      /* outline: 1px solid ${colors.green[400]}; */

      &:focus-visible {
        border-radius: ${border.radius.xs};
        outline: 2px solid ${colors.blue[800]};
      }

      & svg {
        position: relative;
        left: 1px;
      }
    `,
    info: css`
      color: ${t(colors.gray[500], colors.gray[500])};
      font-size: ${font.size.xs};
      margin-left: ${size[1]};
      /* outline: 1px solid ${colors.yellow[400]}; */
    `,
    label: css`
      color: ${t(colors.gray[700], colors.gray[300])};
      white-space: nowrap;
    `,
    value: css`
      color: ${t(colors.purple[600], colors.purple[400])};
      flex-grow: 1;
    `,
    actions: css`
      display: inline-flex;
      gap: ${size[2]};
      align-items: center;
    `,
    row: css`
      display: inline-flex;
      gap: ${size[2]};
      width: 100%;
      margin: ${size[0.25]} 0px;
      line-height: ${size[4.5]};
      align-items: center;
    `,
    editableInput: css`
      border: none;
      padding: ${size[0.5]} ${size[1]} ${size[0.5]} ${size[1.5]};
      flex-grow: 1;
      border-radius: ${border.radius.xs};
      background-color: ${t(colors.gray[200], colors.darkGray[500])};

      &:hover {
        background-color: ${t(colors.gray[300], colors.darkGray[600])};
      }
    `,
    actionButton: css`
      background-color: transparent;
      color: ${t(colors.gray[500], colors.gray[500])};
      border: none;
      display: inline-flex;
      padding: 0px;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      width: ${size[3]};
      height: ${size[3]};
      position: relative;
      z-index: 1;

      &:hover svg {
        color: ${t(colors.gray[600], colors.gray[400])};
      }

      &:focus-visible {
        border-radius: ${border.radius.xs};
        outline: 2px solid ${colors.blue[800]};
        outline-offset: 2px;
      }
    `,
  }
}

const lightStyles = (css: (typeof goober)['css']) => stylesFactory('light', css)
const darkStyles = (css: (typeof goober)['css']) => stylesFactory('dark', css)