Open History to see the last commit
1import { displayValue } from './utils'
2import { stringify } from 'superjson'
3import { css, cx } from '@emotion/css'
4import { tokens } from './theme'
5import { createMemo, createSignal, Index, Match, Show, Switch } from 'solid-js'
6import { Key } from '@solid-primitives/keyed'
7import { CopiedCopier, Copier, ErrorCopier } from './icons'
8β
9/**
10 * Chunk elements in the array by size
11 *
12 * when the array cannot be chunked evenly by size, the last chunk will be
13 * filled with the remaining elements
14 *
15 * @example
16 * chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
17 */
18export function chunkArray<T extends { label: string; value: unknown }>(
19 array: T[],
20 size: number,
21): T[][] {
22 if (size < 1) return []
23 let i = 0
24 const result: T[][] = []
25 while (i < array.length) {
26 result.push(array.slice(i, i + size))
27 i = i + size
28 }
29 return result
30}
31β
32const Expander = (props: { expanded: boolean }) => {
33 const styles = getStyles()
34β
35 return (
36 <span
37 class={cx(
38 styles.expander,
39 css`
40 transform: rotate(${props.expanded ? 90 : 0}deg);
41 `,
42 )}
43 >
44 <svg
45 width="16"
46 height="16"
47 viewBox="0 0 16 16"
48 fill="none"
49 xmlns="http://www.w3.org/2000/svg"
50 >
51 <path
52 d="M6 12L10 8L6 4"
53 stroke-width="2"
54 stroke-linecap="round"
55 stroke-linejoin="round"
56 />
57 </svg>
58 </span>
59 )
60}
61β
62type CopyState = 'NoCopy' | 'SuccessCopy' | 'ErrorCopy'
63const CopyButton = (props: { value: unknown }) => {
64 const styles = getStyles()
65 const [copyState, setCopyState] = createSignal<CopyState>('NoCopy')
66β
67 return (
68 <button
69 class={styles.copyButton}
70 aria-label={`${
71 copyState() === 'NoCopy'
72 ? 'Copy object to clipboard'
73 : copyState() === 'SuccessCopy'
74 ? 'Object copied to clipboard'
75 : 'Error copying object to clipboard'
76 }`}
77 onClick={
78 copyState() === 'NoCopy'
79 ? () => {
80 navigator.clipboard.writeText(stringify(props.value)).then(
81 () => {
82 setCopyState('SuccessCopy')
83 setTimeout(() => {
84 setCopyState('NoCopy')
85 }, 1500)
86 },
87 (err) => {
88 console.error('Failed to copy: ', err)
89 setCopyState('ErrorCopy')
90 setTimeout(() => {
91 setCopyState('NoCopy')
92 }, 1500)
93 },
94 )
95 }
96 : undefined
97 }
98 >
99 <Switch>
100 <Match when={copyState() === 'NoCopy'}>
101 <Copier />
102 </Match>
103 <Match when={copyState() === 'SuccessCopy'}>
104 <CopiedCopier />
105 </Match>
106 <Match when={copyState() === 'ErrorCopy'}>
107 <ErrorCopier />
108 </Match>
109 </Switch>
110 </button>
111 )
112}
113β
114type ExplorerProps = {
115 copyable?: boolean
116 label: string
117 value: unknown
118 defaultExpanded?: string[]
119}
120β
121function isIterable(x: any): x is Iterable<unknown> {
122 return Symbol.iterator in x
123}
124β
125export default function Explorer(props: ExplorerProps) {
126 const styles = getStyles()
127β
128 const [expanded, setExpanded] = createSignal(
129 (props.defaultExpanded || []).includes(props.label),
130 )
131 const toggleExpanded = () => setExpanded((old) => !old)
132 const [expandedPages, setExpandedPages] = createSignal<number[]>([])
133β
134 const subEntries = createMemo(() => {
135 if (Array.isArray(props.value)) {
136 return props.value.map((d, i) => ({
137 label: i.toString(),
138 value: d,
139 }))
140 } else if (
141 props.value !== null &&
142 typeof props.value === 'object' &&
143 isIterable(props.value) &&
144 typeof props.value[Symbol.iterator] === 'function'
145 ) {
146 if (props.value instanceof Map) {
147 return Array.from(props.value, ([key, val]) => ({
148 label: key,
149 value: val,
150 }))
151 }
152 return Array.from(props.value, (val, i) => ({
153 label: i.toString(),
154 value: val,
155 }))
156 } else if (typeof props.value === 'object' && props.value !== null) {
157 return Object.entries(props.value).map(([key, val]) => ({
158 label: key,
159 value: val,
160 }))
161 }
162 return []
163 })
164β
165 const type = createMemo<string>(() => {
166 if (Array.isArray(props.value)) {
167 return 'array'
168 } else if (
169 props.value !== null &&
170 typeof props.value === 'object' &&
171 isIterable(props.value) &&
172 typeof props.value[Symbol.iterator] === 'function'
173 ) {
174 return 'Iterable'
175 } else if (typeof props.value === 'object' && props.value !== null) {
176 return 'object'
177 }
178 return typeof props.value
179 })
180β
181 const subEntryPages = createMemo(() => chunkArray(subEntries(), 100))
182β
183 return (
184 <div class={styles.entry}>
185 <Show when={subEntryPages().length}>
186 <button class={styles.expanderButton} onClick={() => toggleExpanded()}>
187 <Expander expanded={expanded()} /> <span>{props.label}</span>{' '}
188 <span class={styles.info}>
189 {String(type()).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
190 {subEntries().length} {subEntries().length > 1 ? `items` : `item`}
191 </span>
192 </button>
193 <Show when={props.copyable}>
194 <CopyButton value={props.value} />
195 </Show>
196 <Show when={expanded()}>
197 <Show when={subEntryPages().length === 1}>
198 <div class={styles.subEntry}>
199 <Key each={subEntries()} by={(item) => item.label}>
200 {(entry) => {
201 return (
202 <Explorer
203 defaultExpanded={props.defaultExpanded}
204 label={entry().label}
205 value={entry().value}
206 copyable={props.copyable}
207 />
208 )
209 }}
210 </Key>
211 </div>
212 </Show>
213 <Show when={subEntryPages().length > 1}>
214 <div class={styles.subEntry}>
215 <Index each={subEntryPages()}>
216 {(entries, index) => (
217 <div>
218 <div class={styles.entry}>
219 <button
220 onClick={() =>
221 setExpandedPages((old) =>
222 old.includes(index)
223 ? old.filter((d) => d !== index)
224 : [...old, index],
225 )
226 }
227 class={styles.expanderButton}
228 >
229 <Expander expanded={expandedPages().includes(index)} />{' '}
230 [{index * 100}...
231 {index * 100 + 100 - 1}]
232 </button>
233 <Show when={expandedPages().includes(index)}>
234 <div class={styles.subEntry}>
235 <Key each={entries()} by={(entry) => entry.label}>
236 {(entry) => (
237 <Explorer
238 defaultExpanded={props.defaultExpanded}
239 label={entry().label}
240 value={entry().value}
241 copyable={props.copyable}
242 />
243 )}
244 </Key>
245 </div>
246 </Show>
247 </div>
248 </div>
249 )}
250 </Index>
251 </div>
252 </Show>
253 </Show>
254 </Show>
255 <Show when={subEntryPages().length === 0}>
256 <span class={styles.label}>{props.label}:</span>{' '}
257 <span class={styles.value}>{displayValue(props.value)}</span>
258 </Show>
259 </div>
260 )
261}
262β
263const getStyles = () => {
264 const { colors, font, size, border } = tokens
265β
266 return {
267 entry: css`
268 & * {
269 font-size: ${font.size.sm};
270 font-family: 'Menlo', 'Fira Code', monospace;
271 line-height: 1.7;
272 }
273 position: relative;
274 outline: none;
275 word-break: break-word;
276 `,
277 subEntry: css`
278 margin: 0 0 0 0.5em;
279 padding-left: 0.75em;
280 border-left: 2px solid ${colors.darkGray[400]};
281 `,
282 expander: css`
283 & path {
284 stroke: ${colors.gray[400]};
285 }
286 display: inline-flex;
287 align-items: center;
288 transition: all 0.1s ease;
289 `,
290 expanderButton: css`
291 cursor: pointer;
292 color: inherit;
293 font: inherit;
294 outline: inherit;
295 line-height: ${font.size.sm};
296 background: transparent;
297 border: none;
298 padding: 0;
299 display: inline-flex;
300 align-items: center;
301 gap: ${size[1]};
302β
303 &:focus-visible {
304 border-radius: ${border.radius.xs};
305 outline: 2px solid ${colors.blue[800]};
306 }
307 `,
308 info: css`
309 color: ${colors.gray[500]};
310 font-size: ${font.size.xs};
311 line-height: ${font.size.xs};
312 margin-left: ${size[1]};
313 `,
314 label: css`
315 color: ${colors.gray[300]};
316 `,
317 value: css`
318 color: ${colors.purple[400]};
319 `,
320 copyButton: css`
321 background-color: transparent;
322 border: none;
323 display: inline-flex;
324 padding: 0px;
325 align-items: center;
326 justify-content: center;
327 cursor: pointer;
328 width: ${size[3.5]};
329 height: ${size[3.5]};
330 position: relative;
331 top: 4px;
332 left: ${size[2]};
333 z-index: 1;
334β
335 &:hover svg .copier {
336 stroke: ${colors.gray[500]} !important;
337 }
338β
339 &:focus-visible {
340 border-radius: ${border.radius.xs};
341 outline: 2px solid ${colors.blue[800]};
342 outline-offset: 2px;
343 }
344 `,
345 }
346}