Open History to see the last commit
1import { serialize, stringify } from 'superjson'
2import { clsx as cx } from 'clsx'
3import {
4 Index,
5 Match,
6 Show,
7 Switch,
8 createEffect,
9 createMemo,
10 createSignal,
11 createUniqueId,
12 on,
13 onCleanup,
14 onMount,
15} from 'solid-js'
16import { Key } from '@solid-primitives/keyed'
17import * as goober from 'goober'
18import { tokens } from './theme'
19import {
20 deleteNestedDataByPath,
21 displayValue,
22 isPlainObject,
23 updateNestedDataByPath,
24} from './utils'
25import {
26 Check,
27 CopiedCopier,
28 Copier,
29 ErrorCopier,
30 List,
31 Pencil,
32 Trash,
33} from './icons'
34import { useQueryDevtoolsContext, useTheme } from './contexts'
35import { primitiveText, searchEntries, searchExplorer } from './explorerSearch'
36import { getNativeObjectType } from './nativeObjectType'
37import type { ExplorerSearch } from './explorerSearch'
38import type { Query } from '@tanstack/query-core'
39
40/**
41 * Chunk elements in the array by size.
42 *
43 * When the array cannot be chunked evenly by size, the last chunk will be
44 * filled with the remaining elements.
45 * @param array - The elements to chunk.
46 * @param size - The number of elements per chunk. Below `1`, no chunks are returned.
47 * @returns The chunks.
48 * @example
49 * chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
50 */
51function chunkArray<T extends { label: string; value: unknown }>(
52 array: Array<T>,
53 size: number,
54): Array<Array<T>> {
55 if (size < 1) return []
56 let i = 0
57 const result: Array<Array<T>> = []
58 while (i < array.length) {
59 result.push(array.slice(i, i + size))
60 i = i + size
61 }
62 return result
63}
64
65const Expander = (props: { expanded: boolean }) => {
66 const theme = useTheme()
67 const css = useQueryDevtoolsContext().shadowDOMTarget
68 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
69 : goober.css
70 const styles = createMemo(() => {
71 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
72 })
73
74 return (
75 <span
76 class={cx(
77 styles().expander,
78 css`
79 transform: rotate(${props.expanded ? 90 : 0}deg);
80 `,
81 props.expanded &&
82 css`
83 & svg {
84 top: -1px;
85 }
86 `,
87 )}
88 >
89 <svg
90 width="16"
91 height="16"
92 viewBox="0 0 16 16"
93 fill="none"
94 xmlns="http://www.w3.org/2000/svg"
95 >
96 <path
97 d="M6 12L10 8L6 4"
98 stroke-width="2"
99 stroke-linecap="round"
100 stroke-linejoin="round"
101 />
102 </svg>
103 </span>
104 )
105}
106
107type CopyState = 'NoCopy' | 'SuccessCopy' | 'ErrorCopy'
108const CopyButton = (props: { value: unknown }) => {
109 const theme = useTheme()
110 const css = useQueryDevtoolsContext().shadowDOMTarget
111 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
112 : goober.css
113 const styles = createMemo(() => {
114 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
115 })
116 const [copyState, setCopyState] = createSignal<CopyState>('NoCopy')
117
118 return (
119 <button
120 class={styles().actionButton}
121 title="Copy object to clipboard"
122 aria-label={`${
123 copyState() === 'NoCopy'
124 ? 'Copy object to clipboard'
125 : copyState() === 'SuccessCopy'
126 ? 'Object copied to clipboard'
127 : 'Error copying object to clipboard'
128 }`}
129 onClick={
130 copyState() === 'NoCopy'
131 ? () => {
132 navigator.clipboard.writeText(stringify(props.value)).then(
133 () => {
134 setCopyState('SuccessCopy')
135 setTimeout(() => {
136 setCopyState('NoCopy')
137 }, 1500)
138 },
139 (err) => {
140 console.error('Failed to copy: ', err)
141 setCopyState('ErrorCopy')
142 setTimeout(() => {
143 setCopyState('NoCopy')
144 }, 1500)
145 },
146 )
147 }
148 : undefined
149 }
150 >
151 <Switch>
152 <Match when={copyState() === 'NoCopy'}>
153 <Copier />
154 </Match>
155 <Match when={copyState() === 'SuccessCopy'}>
156 <CopiedCopier theme={theme()} />
157 </Match>
158 <Match when={copyState() === 'ErrorCopy'}>
159 <ErrorCopier />
160 </Match>
161 </Switch>
162 </button>
163 )
164}
165
166const ClearArrayButton = (props: {
167 dataPath: Array<string>
168 activeQuery: Query
169}) => {
170 const theme = useTheme()
171 const css = useQueryDevtoolsContext().shadowDOMTarget
172 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
173 : goober.css
174 const styles = createMemo(() => {
175 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
176 })
177 const queryClient = useQueryDevtoolsContext().client
178
179 return (
180 <button
181 class={styles().actionButton}
182 title={'Remove all items'}
183 aria-label={'Remove all items'}
184 onClick={() => {
185 const oldData = props.activeQuery.state.data
186 const newData = updateNestedDataByPath(oldData, props.dataPath, [])
187 queryClient.setQueryData(props.activeQuery.queryKey, newData)
188 }}
189 >
190 <List />
191 </button>
192 )
193}
194
195const DeleteItemButton = (props: {
196 dataPath: Array<string>
197 activeQuery: Query
198}) => {
199 const theme = useTheme()
200 const css = useQueryDevtoolsContext().shadowDOMTarget
201 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
202 : goober.css
203 const styles = createMemo(() => {
204 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
205 })
206 const queryClient = useQueryDevtoolsContext().client
207
208 return (
209 <button
210 class={cx(styles().actionButton)}
211 title={'Delete item'}
212 aria-label={'Delete item'}
213 onClick={() => {
214 const oldData = props.activeQuery.state.data
215 const newData = deleteNestedDataByPath(oldData, props.dataPath)
216 queryClient.setQueryData(props.activeQuery.queryKey, newData)
217 }}
218 >
219 <Trash />
220 </button>
221 )
222}
223
224const ToggleValueButton = (props: {
225 dataPath: Array<string>
226 activeQuery: Query
227 value: boolean
228}) => {
229 const theme = useTheme()
230 const css = useQueryDevtoolsContext().shadowDOMTarget
231 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
232 : goober.css
233 const styles = createMemo(() => {
234 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
235 })
236 const queryClient = useQueryDevtoolsContext().client
237
238 return (
239 <button
240 class={cx(
241 styles().actionButton,
242 css`
243 width: ${tokens.size[3.5]};
244 height: ${tokens.size[3.5]};
245 `,
246 )}
247 title={'Toggle value'}
248 aria-label={'Toggle value'}
249 aria-pressed={props.value}
250 onClick={() => {
251 const oldData = props.activeQuery.state.data
252 const newData = updateNestedDataByPath(
253 oldData,
254 props.dataPath,
255 !props.value,
256 )
257 queryClient.setQueryData(props.activeQuery.queryKey, newData)
258 }}
259 >
260 <Check theme={theme()} checked={props.value} />
261 </button>
262 )
263}
264
265type ExplorerProps = {
266 editable?: boolean
267 label: string
268 value: unknown
269 defaultExpanded?: Array<string>
270 dataPath?: Array<string>
271 activeQuery?: Query
272 itemsDeletable?: boolean
273 onEdit?: () => void
274 search?: ExplorerSearch
275 highlight?: Highlight
276}
277
278/**
279 * Adds nested data search without changing the explorer's manual expansion.
280 * @param props - Data explorer options, the selected query or mutation identity, and the search
281 * term to start with when another one is selected.
282 * @returns The search controls and the original data tree.
283 */
284export function SearchableExplorer(
285 props: ExplorerProps & { searchKey?: unknown; initialSearch?: string },
286) {
287 const theme = useTheme()
288 const css = useQueryDevtoolsContext().shadowDOMTarget
289 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
290 : goober.css
291 const styles = createMemo(() =>
292 theme() === 'dark' ? darkStyles(css) : lightStyles(css),
293 )
294 const [term, setTerm] = createSignal('')
295 const [debouncedTerm, setDebouncedTerm] = createSignal('')
296 const clear = () => {
297 setTerm('')
298 setDebouncedTerm('')
299 }
300 const searchKey = createMemo(() => props.searchKey)
301 createEffect(
302 on(searchKey, () => {
303 const initial = props.initialSearch ?? ''
304 setTerm(initial)
305 setDebouncedTerm(initial.toLowerCase())
306 }),
307 )
308 createEffect(() => {
309 const next = term().toLowerCase()
310 if (!next) {
311 setDebouncedTerm('')
312 return
313 }
314 const timeout = setTimeout(() => setDebouncedTerm(next), 150)
315 onCleanup(() => clearTimeout(timeout))
316 })
317 const search = createMemo<ExplorerSearch | undefined>(() => {
318 const activeTerm = debouncedTerm()
319 return activeTerm
320 ? { term: activeTerm, match: searchExplorer(props.value, activeTerm) }
321 : undefined
322 })
323 const highlightName = `tsqd-data-search-${createUniqueId()}`
324 const [nativeHighlight, setNativeHighlight] = createSignal<Highlight>()
325 let root!: HTMLDivElement
326 onMount(() => {
327 const view = root.ownerDocument.defaultView!
328 const registry = view.CSS.highlights
329 createEffect(
330 on(search, () => {
331 const highlight = new view.Highlight()
332 registry.set(highlightName, highlight)
333 setNativeHighlight(highlight)
334 onCleanup(() => {
335 registry.delete(highlightName)
336 highlight.clear()
337 })
338 }),
339 )
340 })
341 const nativeHighlightStyle = createMemo(
342 () => css`
343 & ::highlight(${highlightName}) {
344 color: ${
345 theme() === 'dark' ? tokens.colors.gray[100] : tokens.colors.gray[900]
346 };
347 background-color: ${
348 theme() === 'dark'
349 ? tokens.colors.yellow[900]
350 : tokens.colors.yellow[200]
351 };
352 }
353 `,
354 )
355 return (
356 <div ref={root} class={nativeHighlightStyle()}>
357 <div class={styles().search}>
358 <input
359 type="search"
360 aria-label={`Search ${props.label.toLowerCase()}`}
361 placeholder={`Search ${props.label.toLowerCase()}`}
362 class={styles().searchInput}
363 value={term()}
364 onInput={(event) => setTerm(event.currentTarget.value)}
365 onKeyDown={(event) => {
366 if (event.key === 'Escape') {
367 event.stopPropagation()
368 clear()
369 }
370 }}
371 />
372 <Show when={term()}>
373 <button
374 type="button"
375 class={styles().clearSearch}
376 onClick={clear}
377 aria-label="Clear search"
378 >
379 Clear
380 </button>
381 </Show>
382 </div>
383 <div role="status" aria-live="polite">
384 {search() && !search()!.match.hasMatch ? 'No matches' : ''}
385 </div>
386 <Explorer {...props} search={search()} highlight={nativeHighlight()} />
387 </div>
388 )
389}
390
391const MAX_HIGHLIGHT_RANGES = 1000
392
393/**
394 * Marks literal, case-insensitive matches in a label or primitive value.
395 * @param props - The text, normalized search term, and shared highlight instance.
396 * @returns Text with matching substrings marked.
397 */
398function HighlightedText(props: {
399 text: string
400 term?: string
401 highlight?: Highlight
402}) {
403 const matches = createMemo(() => {
404 const term = props.term
405 if (!term) return []
406 const lower = props.text.toLowerCase()
407 let originalStart = 0
408 let originalEnd = 0
409 let lowercaseEnd = 0
410 const originalPosition = (index: number) => {
411 while (lowercaseEnd <= index) {
412 const character = String.fromCodePoint(
413 props.text.codePointAt(originalEnd)!,
414 )
415 originalStart = originalEnd
416 originalEnd += character.length
417 lowercaseEnd += character.toLowerCase().length
418 }
419 return { start: originalStart, end: originalEnd }
420 }
421 const ranges: Array<{ start: number; end: number }> = []
422 let index = lower.indexOf(term)
423 while (index !== -1 && ranges.length < MAX_HIGHLIGHT_RANGES) {
424 const from = originalPosition(index).start
425 const to = originalPosition(index + term.length - 1).end
426 ranges.push({ start: from, end: to })
427 index = lower.indexOf(term, index + term.length)
428 }
429 return ranges
430 })
431 const text = document.createTextNode('')
432 createEffect(() => {
433 text.data = props.text
434 const highlight = props.highlight
435 if (!highlight) return
436 const ranges: Array<Range> = []
437 for (const match of matches()) {
438 if (highlight.size >= MAX_HIGHLIGHT_RANGES) break
439 const range = text.ownerDocument.createRange()
440 range.setStart(text, match.start)
441 range.setEnd(text, match.end)
442 highlight.add(range)
443 ranges.push(range)
444 }
445 onCleanup(() => {
446 for (const range of ranges) highlight.delete(range)
447 })
448 })
449 return text
450}
451
452/**
453 * Checks whether a value is iterable.
454 * @param x - The value to check.
455 * @returns `true` if `x` has a `Symbol.iterator` method.
456 */
457function isIterable(x: any): x is Iterable<unknown> {
458 return Symbol.iterator in x
459}
460
461/**
462 * Renders an expandable tree view of a value, used to explore a query's data in the devtools. It
463 * can also edit and delete entries in the query's data.
464 * @param props - The value to show and its label, plus the options for expanding, editing, and
465 * deleting entries.
466 * @returns The tree view.
467 */
468export default function Explorer(props: ExplorerProps) {
469 const theme = useTheme()
470 const css = useQueryDevtoolsContext().shadowDOMTarget
471 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
472 : goober.css
473 const styles = createMemo(() => {
474 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
475 })
476 const queryClient = useQueryDevtoolsContext().client
477
478 const [expanded, setExpanded] = createSignal(
479 (props.defaultExpanded || []).includes(props.label),
480 )
481 const hasSearchMatchingChild = () =>
482 !!props.search &&
483 [...props.search.match.children.values()].some((child) => child.hasMatch)
484 const isExpanded = () => expanded() || hasSearchMatchingChild()
485 const toggleExpanded = () => {
486 if (!hasSearchMatchingChild()) setExpanded((old) => !old)
487 }
488 const [expandedPages, setExpandedPages] = createSignal<Array<number>>([])
489 const nativeObjectType = createMemo(() => getNativeObjectType(props.value))
490 const childrenEditable = createMemo(
491 () =>
492 props.editable &&
493 (Array.isArray(props.value) ||
494 nativeObjectType() === 'Map' ||
495 nativeObjectType() === 'Set' ||
496 isPlainObject(props.value)),
497 )
498
499 const subEntries = createMemo(() => {
500 if (props.search) {
501 return props.search.match.kind === 'branch'
502 ? (searchEntries(props.value) ?? [])
503 : []
504 }
505 if (Array.isArray(props.value)) {
506 return props.value.map((d, i) => ({
507 label: i.toString(),
508 key: i.toString(),
509 value: d,
510 }))
511 } else if (nativeObjectType() === 'Map') {
512 return Array.from(
513 Map.prototype.entries.call(props.value),
514 ([key, val]) => ({
515 label: primitiveText(key) ?? '[Object key]',
516 key,
517 value: val,
518 }),
519 )
520 } else if (nativeObjectType() === 'Set') {
521 return Array.from(Set.prototype.values.call(props.value), (val, i) => ({
522 label: i.toString(),
523 key: i.toString(),
524 value: val,
525 }))
526 } else if (
527 props.value !== null &&
528 typeof props.value === 'object' &&
529 isIterable(props.value) &&
530 typeof props.value[Symbol.iterator] === 'function'
531 ) {
532 return Array.from(props.value, (val, i) => ({
533 label: i.toString(),
534 key: i.toString(),
535 value: val,
536 }))
537 } else if (typeof props.value === 'object' && props.value !== null) {
538 return Object.entries(props.value).map(([key, val]) => ({
539 label: key,
540 key,
541 value: val,
542 }))
543 }
544 return []
545 })
546
547 const type = createMemo<string>(() => {
548 if (props.search) {
549 if (Array.isArray(props.value)) return 'array'
550 if (nativeObjectType() === 'Map' || nativeObjectType() === 'Set')
551 return 'Iterable'
552 return props.value === null ? 'object' : typeof props.value
553 }
554 if (Array.isArray(props.value)) {
555 return 'array'
556 } else if (
557 props.value !== null &&
558 typeof props.value === 'object' &&
559 isIterable(props.value) &&
560 typeof props.value[Symbol.iterator] === 'function'
561 ) {
562 return 'Iterable'
563 } else if (typeof props.value === 'object' && props.value !== null) {
564 return 'object'
565 }
566 return typeof props.value
567 })
568
569 const subEntryPages = createMemo(() => chunkArray(subEntries(), 100))
570
571 const pageHasMatch = (index: number) =>
572 !!(
573 props.search &&
574 subEntryPages()[index]?.some(
575 (entry) => props.search?.match.children.get(entry.key)?.hasMatch,
576 )
577 )
578 const matchingPage = createMemo(() =>
579 subEntryPages().findIndex((_, index) => pageHasMatch(index)),
580 )
581 const isPageExpanded = (index: number) =>
582 expandedPages().includes(index) || matchingPage() === index
583 const childSearch = (key: unknown): ExplorerSearch | undefined => {
584 const search = props.search
585 const match = search?.match.children.get(key)
586 return search && match ? { term: search.term, match } : undefined
587 }
588 const label = () => (
589 <HighlightedText
590 text={props.label}
591 term={props.search?.match.label ? props.search.term : undefined}
592 highlight={props.highlight}
593 />
594 )
595 const valueText = () => {
596 if (!props.search) return displayValue(props.value)
597 switch (props.search.match.kind) {
598 case 'circular':
599 return '[Circular]'
600 case 'accessor':
601 return '[Getter]'
602 case 'opaque':
603 return '[Object]'
604 case 'branch':
605 return Array.isArray(props.value)
606 ? '[]'
607 : nativeObjectType() === 'Map'
608 ? 'Map(0)'
609 : nativeObjectType() === 'Set'
610 ? 'Set(0)'
611 : '{}'
612 case 'value':
613 return primitiveText(props.value)
614 }
615 }
616 const renderedValue = () => (
617 <>
618 {props.search && typeof props.value === 'string' ? '"' : ''}
619 <HighlightedText
620 text={valueText() ?? ''}
621 term={props.search?.match.value ? props.search.term : undefined}
622 highlight={props.highlight}
623 />
624 {props.search && typeof props.value === 'string' ? '"' : ''}
625 </>
626 )
627
628 const currentDataPath = props.dataPath ?? []
629
630 const inputId = createUniqueId()
631
632 return (
633 <div class={styles().entry}>
634 <Show when={subEntryPages().length}>
635 <div class={styles().expanderButtonContainer}>
636 <button
637 class={styles().expanderButton}
638 onClick={() => toggleExpanded()}
639 aria-expanded={isExpanded() ? 'true' : 'false'}
640 >
641 <Expander expanded={isExpanded()} /> <span>{label()}</span>{' '}
642 <span class={styles().info}>
643 {String(type()).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
644 {subEntries().length} {subEntries().length > 1 ? `items` : `item`}
645 </span>
646 </button>
647 <Show when={props.editable}>
648 <div class={styles().actions}>
649 <CopyButton value={props.value} />
650
651 <Show
652 when={props.itemsDeletable && props.activeQuery !== undefined}
653 >
654 <DeleteItemButton
655 activeQuery={props.activeQuery!}
656 dataPath={currentDataPath}
657 />
658 </Show>
659
660 <Show
661 when={type() === 'array' && props.activeQuery !== undefined}
662 >
663 <ClearArrayButton
664 activeQuery={props.activeQuery!}
665 dataPath={currentDataPath}
666 />
667 </Show>
668
669 <Show
670 when={
671 !!props.onEdit &&
672 !props.search &&
673 !serialize(props.value).meta
674 }
675 >
676 <button
677 class={styles().actionButton}
678 title={'Bulk Edit Data'}
679 aria-label={'Bulk Edit Data'}
680 onClick={() => {
681 props.onEdit?.()
682 }}
683 >
684 <Pencil />
685 </button>
686 </Show>
687 </div>
688 </Show>
689 </div>
690 <Show when={isExpanded()}>
691 <Show when={subEntryPages().length === 1}>
692 <div class={styles().subEntry}>
693 <Key each={subEntries()} by={(item) => item.key}>
694 {(entry) => {
695 return (
696 <Explorer
697 defaultExpanded={props.defaultExpanded}
698 label={entry().label}
699 search={childSearch(entry().key)}
700 highlight={props.highlight}
701 value={entry().value}
702 editable={childrenEditable()}
703 dataPath={[...currentDataPath, entry().key]}
704 activeQuery={props.activeQuery}
705 itemsDeletable={
706 type() === 'array' ||
707 type() === 'Iterable' ||
708 type() === 'object'
709 }
710 />
711 )
712 }}
713 </Key>
714 </div>
715 </Show>
716 <Show when={subEntryPages().length > 1}>
717 <div class={styles().subEntry}>
718 <Index each={subEntryPages()}>
719 {(entries, index) => (
720 <div>
721 <div class={styles().entry}>
722 <button
723 onClick={() => {
724 if (matchingPage() === index) return
725 setExpandedPages((old) =>
726 old.includes(index)
727 ? old.filter((d) => d !== index)
728 : [...old, index],
729 )
730 }}
731 class={cx(
732 styles().expanderButton,
733 pageHasMatch(index) && styles().highlight,
734 )}
735 aria-expanded={isPageExpanded(index)}
736 aria-description={
737 pageHasMatch(index)
738 ? 'Contains search matches'
739 : undefined
740 }
741 >
742 <Expander expanded={isPageExpanded(index)} /> [
743 {index * 100}...
744 {index * 100 + 100 - 1}]
745 </button>
746 <Show when={isPageExpanded(index)}>
747 <div class={styles().subEntry}>
748 <Key each={entries()} by={(entry) => entry.key}>
749 {(entry) => (
750 <Explorer
751 defaultExpanded={props.defaultExpanded}
752 label={entry().label}
753 search={childSearch(entry().key)}
754 highlight={props.highlight}
755 value={entry().value}
756 editable={childrenEditable()}
757 dataPath={[...currentDataPath, entry().key]}
758 activeQuery={props.activeQuery}
759 />
760 )}
761 </Key>
762 </div>
763 </Show>
764 </div>
765 </div>
766 )}
767 </Index>
768 </div>
769 </Show>
770 </Show>
771 </Show>
772 <Show when={subEntryPages().length === 0}>
773 <div class={styles().row}>
774 <label for={inputId} class={styles().label}>
775 {label()}:
776 </label>
777 <Show
778 when={
779 props.editable &&
780 props.activeQuery !== undefined &&
781 (type() === 'string' ||
782 type() === 'number' ||
783 type() === 'boolean')
784 }
785 fallback={<span class={styles().value}>{renderedValue()}</span>}
786 >
787 <Show
788 when={
789 props.editable &&
790 props.activeQuery !== undefined &&
791 (type() === 'string' || type() === 'number')
792 }
793 >
794 <input
795 id={inputId}
796 type={type() === 'number' ? 'number' : 'text'}
797 class={cx(
798 styles().value,
799 styles().editableInput,
800 props.search?.match.value && styles().highlight,
801 )}
802 data-search-match={props.search?.match.value || undefined}
803 value={props.value as string | number}
804 onChange={(changeEvent) => {
805 const oldData = props.activeQuery!.state.data
806
807 const newData = updateNestedDataByPath(
808 oldData,
809 currentDataPath,
810 type() === 'number'
811 ? changeEvent.target.valueAsNumber
812 : changeEvent.target.value,
813 )
814
815 queryClient.setQueryData(props.activeQuery!.queryKey, newData)
816 }}
817 />
818 </Show>
819
820 <Show when={type() === 'boolean'}>
821 <span
822 class={cx(
823 styles().value,
824 styles().actions,
825 styles().editableInput,
826 )}
827 >
828 <ToggleValueButton
829 activeQuery={props.activeQuery!}
830 dataPath={currentDataPath}
831 value={props.value as boolean}
832 />
833 {renderedValue()}
834 </span>
835 </Show>
836 </Show>
837
838 <Show
839 when={
840 props.editable &&
841 props.itemsDeletable &&
842 props.activeQuery !== undefined
843 }
844 >
845 <DeleteItemButton
846 activeQuery={props.activeQuery!}
847 dataPath={currentDataPath}
848 />
849 </Show>
850 </div>
851 </Show>
852 </div>
853 )
854}
855
856const stylesFactory = (
857 theme: 'light' | 'dark',
858 css: (typeof goober)['css'],
859) => {
860 const { colors, font, size, border } = tokens
861 const t = (light: string, dark: string) => (theme === 'light' ? light : dark)
862 return {
863 search: css`
864 display: flex;
865 gap: ${size[2]};
866 margin-bottom: ${size[2]};
867 `,
868 searchInput: css`
869 min-width: 0;
870 flex: 1;
871 padding: ${size[1]} ${size[2]};
872 color: inherit;
873 background: ${t(colors.gray[100], colors.darkGray[600])};
874 border: 1px solid ${t(colors.gray[300], colors.darkGray[400])};
875 border-radius: ${border.radius.xs};
876 `,
877 clearSearch: css`
878 color: inherit;
879 background: transparent;
880 border: none;
881 cursor: pointer;
882 `,
883 highlight: css`
884 && {
885 color: ${t(colors.gray[900], colors.gray[100])};
886 background-color: ${t(colors.yellow[200], colors.yellow[900])};
887 }
888 `,
889 entry: css`
890 & * {
891 font-size: ${font.size.xs};
892 font-family:
893 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
894 'Liberation Mono', 'Courier New', monospace;
895 }
896 position: relative;
897 outline: none;
898 word-break: break-word;
899 `,
900 subEntry: css`
901 margin: 0 0 0 0.5em;
902 padding-left: 0.75em;
903 border-left: 2px solid ${t(colors.gray[300], colors.darkGray[400])};
904 /* outline: 1px solid ${colors.teal[400]}; */
905 `,
906 expander: css`
907 & path {
908 stroke: ${colors.gray[400]};
909 }
910 & svg {
911 width: ${size[3]};
912 height: ${size[3]};
913 }
914 display: inline-flex;
915 align-items: center;
916 transition: all 0.1s ease;
917 /* outline: 1px solid ${colors.blue[400]}; */
918 `,
919 expanderButtonContainer: css`
920 display: flex;
921 align-items: center;
922 line-height: ${size[4]};
923 min-height: ${size[4]};
924 gap: ${size[2]};
925 `,
926 expanderButton: css`
927 cursor: pointer;
928 color: inherit;
929 font: inherit;
930 outline: inherit;
931 height: ${size[5]};
932 background: transparent;
933 border: none;
934 padding: 0;
935 display: inline-flex;
936 align-items: center;
937 gap: ${size[1]};
938 position: relative;
939 /* outline: 1px solid ${colors.green[400]}; */
940
941 &:focus-visible {
942 border-radius: ${border.radius.xs};
943 outline: 2px solid ${colors.blue[800]};
944 }
945
946 & svg {
947 position: relative;
948 left: 1px;
949 }
950 `,
951 info: css`
952 color: ${t(colors.gray[500], colors.gray[500])};
953 font-size: ${font.size.xs};
954 margin-left: ${size[1]};
955 /* outline: 1px solid ${colors.yellow[400]}; */
956 `,
957 label: css`
958 color: ${t(colors.gray[700], colors.gray[300])};
959 white-space: nowrap;
960 `,
961 value: css`
962 color: ${t(colors.purple[600], colors.purple[400])};
963 flex-grow: 1;
964 `,
965 actions: css`
966 display: inline-flex;
967 gap: ${size[2]};
968 align-items: center;
969 `,
970 row: css`
971 display: inline-flex;
972 gap: ${size[2]};
973 width: 100%;
974 margin: ${size[0.25]} 0px;
975 line-height: ${size[4.5]};
976 align-items: center;
977 `,
978 editableInput: css`
979 border: none;
980 padding: ${size[0.5]} ${size[1]} ${size[0.5]} ${size[1.5]};
981 flex-grow: 1;
982 border-radius: ${border.radius.xs};
983 background-color: ${t(colors.gray[200], colors.darkGray[500])};
984
985 &:hover {
986 background-color: ${t(colors.gray[300], colors.darkGray[600])};
987 }
988 `,
989 actionButton: css`
990 background-color: transparent;
991 color: ${t(colors.gray[500], colors.gray[500])};
992 border: none;
993 display: inline-flex;
994 padding: 0px;
995 align-items: center;
996 justify-content: center;
997 cursor: pointer;
998 width: ${size[3]};
999 height: ${size[3]};
1000 position: relative;
1001 z-index: 1;
1002
1003 &:hover svg {
1004 color: ${t(colors.gray[600], colors.gray[400])};
1005 }
1006
1007 &:focus-visible {
1008 border-radius: ${border.radius.xs};
1009 outline: 2px solid ${colors.blue[800]};
1010 outline-offset: 2px;
1011 }
1012 `,
1013 }
1014}
1015
1016const lightStyles = (css: (typeof goober)['css']) => stylesFactory('light', css)
1017const darkStyles = (css: (typeof goober)['css']) => stylesFactory('dark', css)