/
Explorer.tsx
384 lines (353 loc) · 9.41 KB
/
Explorer.tsx
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
import * as React from 'react'
import { displayValue, styled } from './utils'
import superjson from 'superjson'
export const Entry = styled('div', {
fontFamily: 'Menlo, monospace',
fontSize: '1em',
lineHeight: '1.7',
outline: 'none',
wordBreak: 'break-word',
})
export const Label = styled('span', {
color: 'white',
})
export const LabelButton = styled('button', {
cursor: 'pointer',
color: 'white',
})
export const ExpandButton = styled('button', {
cursor: 'pointer',
color: 'inherit',
font: 'inherit',
outline: 'inherit',
background: 'transparent',
border: 'none',
padding: 0,
})
type CopyState = 'NoCopy' | 'SuccessCopy' | 'ErrorCopy'
export const CopyButton = ({ value }: { value: unknown }) => {
const [copyState, setCopyState] = React.useState<CopyState>('NoCopy')
return (
<button
onClick={
copyState === 'NoCopy'
? () => {
navigator.clipboard.writeText(superjson.stringify(value)).then(
() => {
setCopyState('SuccessCopy')
setTimeout(() => {
setCopyState('NoCopy')
}, 1500)
},
(err) => {
console.error('Failed to copy: ', err)
setCopyState('ErrorCopy')
setTimeout(() => {
setCopyState('NoCopy')
}, 1500)
},
)
}
: undefined
}
style={{
cursor: 'pointer',
color: 'inherit',
font: 'inherit',
outline: 'inherit',
background: 'transparent',
border: 'none',
padding: 0,
}}
>
{copyState === 'NoCopy' ? (
<Copier />
) : copyState === 'SuccessCopy' ? (
<CopiedCopier />
) : (
<ErrorCopier />
)}
</button>
)
}
export const Value = styled('span', (_props, theme) => ({
color: theme.danger,
}))
export const SubEntries = styled('div', {
marginLeft: '.1em',
paddingLeft: '1em',
borderLeft: '2px solid rgba(0,0,0,.15)',
})
export const Info = styled('span', {
color: 'grey',
fontSize: '.7em',
})
type ExpanderProps = {
expanded: boolean
style?: React.CSSProperties
}
export const Expander = ({ expanded, style = {} }: ExpanderProps) => (
<span
style={{
display: 'inline-block',
transition: 'all .1s ease',
transform: `rotate(${expanded ? 90 : 0}deg) ${style.transform || ''}`,
...style,
}}
>
▶
</span>
)
const Copier = () => (
<span
aria-label="Copy object to clipboard"
title="Copy object to clipboard"
style={{
paddingLeft: '1em',
}}
>
<svg height="12" viewBox="0 0 16 12" width="10">
<path
fill="currentColor"
d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 010 1.5h-1.5a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-1.5a.75.75 0 011.5 0v1.5A1.75 1.75 0 019.25 16h-7.5A1.75 1.75 0 010 14.25v-7.5z"
></path>
<path
fill="currentColor"
d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0114.25 11h-7.5A1.75 1.75 0 015 9.25v-7.5zm1.75-.25a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-7.5a.25.25 0 00-.25-.25h-7.5z"
></path>
</svg>
</span>
)
const ErrorCopier = () => (
<span
aria-label="Failed copying to clipboard"
title="Failed copying to clipboard"
style={{
paddingLeft: '1em',
display: 'flex',
alignItems: 'center',
}}
>
<svg height="12" viewBox="0 0 16 12" width="10" display="block">
<path
fill="red"
d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"
></path>
</svg>
<span
style={{
color: 'red',
fontSize: '12px',
paddingLeft: '4px',
position: 'relative',
top: '2px',
}}
>
See console
</span>
</span>
)
const CopiedCopier = () => (
<span
aria-label="Object copied to clipboard"
title="Object copied to clipboard"
style={{
paddingLeft: '1em',
display: 'inline-block',
verticalAlign: 'middle',
}}
>
<svg height="16" viewBox="0 0 16 16" width="16" display="block">
<path
fill="green"
d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"
></path>
</svg>
</span>
)
type Entry = {
label: string
}
type RendererProps = {
handleEntry: (entry: Entry) => JSX.Element
label?: string
value: unknown
subEntries: Entry[]
subEntryPages: Entry[][]
type: string
expanded: boolean
copyable: boolean
toggleExpanded: () => void
pageSize: number
}
/**
* 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']]
*/
export function chunkArray<T>(array: T[], size: number): T[][] {
if (size < 1) return []
let i = 0
const result: T[][] = []
while (i < array.length) {
result.push(array.slice(i, i + size))
i = i + size
}
return result
}
type Renderer = (props: RendererProps) => JSX.Element
export const DefaultRenderer: Renderer = ({
handleEntry,
label,
value,
subEntries = [],
subEntryPages = [],
type,
expanded = false,
copyable = false,
toggleExpanded,
pageSize,
}) => {
const [expandedPages, setExpandedPages] = React.useState<number[]>([])
return (
<Entry key={label}>
{subEntryPages.length ? (
<>
<ExpandButton onClick={() => toggleExpanded()}>
<Expander expanded={expanded} /> {label}{' '}
<Info>
{String(type).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
{subEntries.length} {subEntries.length > 1 ? `items` : `item`}
</Info>
</ExpandButton>
{copyable ? <CopyButton value={value} /> : null}
{expanded ? (
subEntryPages.length === 1 ? (
<SubEntries>{subEntries.map(handleEntry)}</SubEntries>
) : (
<SubEntries>
{subEntryPages.map((entries, index) => (
<div key={index}>
<Entry>
<LabelButton
onClick={() =>
setExpandedPages((old) =>
old.includes(index)
? old.filter((d) => d !== index)
: [...old, index],
)
}
>
<Expander expanded={expanded} /> [{index * pageSize} ...{' '}
{index * pageSize + pageSize - 1}]
</LabelButton>
{expandedPages.includes(index) ? (
<SubEntries>{entries.map(handleEntry)}</SubEntries>
) : null}
</Entry>
</div>
))}
</SubEntries>
)
) : null}
</>
) : (
<>
<Label>{label}:</Label> <Value>{displayValue(value)}</Value>
</>
)}
</Entry>
)
}
type ExplorerProps = Partial<RendererProps> & {
renderer?: Renderer
defaultExpanded?: true | Record<string, boolean>
copyable?: boolean
}
type Property = {
defaultExpanded?: boolean | Record<string, boolean>
label: string
value: unknown
}
function isIterable(x: any): x is Iterable<unknown> {
return Symbol.iterator in x
}
export default function Explorer({
value,
defaultExpanded,
renderer = DefaultRenderer,
pageSize = 100,
copyable = false,
...rest
}: ExplorerProps) {
const [expanded, setExpanded] = React.useState(Boolean(defaultExpanded))
const toggleExpanded = React.useCallback(() => setExpanded((old) => !old), [])
let type: string = typeof value
let subEntries: Property[] = []
const makeProperty = (sub: { label: string; value: unknown }): Property => {
const subDefaultExpanded =
defaultExpanded === true
? { [sub.label]: true }
: defaultExpanded?.[sub.label]
return {
...sub,
defaultExpanded: subDefaultExpanded,
}
}
if (Array.isArray(value)) {
type = 'array'
subEntries = value.map((d, i) =>
makeProperty({
label: i.toString(),
value: d,
}),
)
} else if (
value !== null &&
typeof value === 'object' &&
isIterable(value) &&
typeof value[Symbol.iterator] === 'function'
) {
type = 'Iterable'
subEntries = Array.from(value, (val, i) =>
makeProperty({
label: i.toString(),
value: val,
}),
)
} else if (typeof value === 'object' && value !== null) {
type = 'object'
subEntries = Object.entries(value).map(([key, val]) =>
makeProperty({
label: key,
value: val,
}),
)
}
const subEntryPages = chunkArray(subEntries, pageSize)
return renderer({
handleEntry: (entry) => (
<Explorer
key={entry.label}
value={value}
renderer={renderer}
copyable={copyable}
{...rest}
{...entry}
/>
),
type,
subEntries,
subEntryPages,
value,
expanded,
copyable,
toggleExpanded,
pageSize,
...rest,
})
}