-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJson.tsx
More file actions
229 lines (213 loc) · 8.84 KB
/
Json.tsx
File metadata and controls
229 lines (213 loc) · 8.84 KB
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
import { ReactNode, useState } from 'react'
import { cn } from '../../lib'
import styles from './Json.module.css'
import { isPrimitive, shouldObjectCollapse, stringifyPrimitive } from './helpers.js'
import { useWidth } from './useWidth.js'
const defaultPageLimit = 100
interface JsonProps {
json: unknown
label?: string
className?: string
expandRoot?: boolean // Expand the top-level object/array by default
pageLimit?: number // Max items to render before showing "Show more..."
}
/**
* JSON viewer component with collapsible objects and arrays.
*/
export default function Json({ json, label, className, expandRoot = true, pageLimit }: JsonProps): ReactNode {
return <div className={cn(styles.json, className)} role="tree">
<JsonContent json={json} label={label} expandRoot={expandRoot} pageLimit={pageLimit} />
</div>
}
function JsonContent({ json, label, expandRoot, pageLimit }: JsonProps): ReactNode {
let div
if (Array.isArray(json)) {
div = <JsonArray array={json} label={label} expandRoot={expandRoot} pageLimit={pageLimit} />
} else if (json instanceof Date) {
const key = label ? <span className={styles.key}>{label}: </span> : ''
div = <>{key}<span className={styles.string}>{`"${json.toISOString()}"`}</span></>
} else if (json instanceof ArrayBuffer || json instanceof Uint8Array) {
const bytes = json instanceof ArrayBuffer ? new Uint8Array(json) : json
div = <ByteArray bytes={bytes} label={label} expandRoot={expandRoot} />
} else if (typeof json === 'object' && json !== null) {
div = <JsonObject label={label} obj={json} expandRoot={expandRoot} pageLimit={pageLimit} />
} else {
// primitive
const key = label ? <span className={styles.key}>{label}: </span> : ''
if (typeof json === 'string') {
div = <>{key}<span className={styles.string}>{`"${json}"`}</span></>
} else if (typeof json === 'number') {
div = <>{key}<span className={styles.number}>{json.toString()}</span></>
} else if (typeof json === 'boolean') {
div = <>{key}<span className={styles.boolean}>{json.toString()}</span></>
} else if (typeof json === 'bigint') {
// it's not really json, but show it anyway
div = <>{key}<span className={styles.number}>{json.toString()}</span></>
} else if (json === undefined) {
// it's not json
div = <>{key}<span className={styles.other}>undefined</span></>
} else {
div = <>{key}<span className={styles.other}>{JSON.stringify(json)}</span></>
}
}
return div
}
function formatHexDump(bytes: Uint8Array): { hex: string, ascii: string }[] {
const lines: { hex: string, ascii: string }[] = []
for (let i = 0; i < bytes.length; i += 16) {
const slice = bytes.slice(i, i + 16)
const hex = Array.from(slice).map(b => b.toString(16).padStart(2, '0')).join(' ')
const ascii = Array.from(slice).map(b => b >= 0x20 && b <= 0x7e ? String.fromCharCode(b) : '.').join('')
lines.push({ hex: hex.padEnd(47), ascii })
}
return lines
}
function ByteArray({ bytes, label, expandRoot }: { bytes: Uint8Array, label?: string, expandRoot?: boolean }): ReactNode {
const [collapsed, setCollapsed] = useState(!expandRoot)
const key = label ? <span className={styles.key}>{label}: </span> : ''
const summary = `${bytes.constructor.name}(${bytes.length})`
if (collapsed) {
return <div role="treeitem" className={styles.clickable} aria-expanded="false" onClick={() => { setCollapsed(false) }}>
{key}
<span className={styles.comment}>{summary}</span>
</div>
}
const lines = formatHexDump(bytes)
return <>
<div role="treeitem" className={styles.clickable} aria-expanded="true" onClick={() => { setCollapsed(true) }}>
{key}
<span className={styles.comment}>{summary}</span>
</div>
<pre className={styles.hexDump}>
{lines.map((line, i) => {
const offset = (i * 16).toString(16).padStart(8, '0')
return <div key={i}><span className={styles.comment}>{offset}</span> <span className={styles.number}>{line.hex}</span> <span className={styles.string}>{line.ascii}</span></div>
})}
</pre>
</>
}
function CollapsedArray({ array }: {array: unknown[]}): ReactNode {
const { elementRef, width } = useWidth()
const maxCharacterCount = Math.max(20, Math.floor(width / 8))
const separator = ', '
const children: ReactNode[] = []
let suffix: string | undefined
let characterCount = 0
for (const [index, value] of array.entries()) {
if (index > 0) {
characterCount += separator.length
children.push(<span key={`separator-${index - 1}`}>{separator}</span>)
}
// should we continue?
if (isPrimitive(value)) {
const asString = stringifyPrimitive(value)
characterCount += asString.length
if (characterCount < maxCharacterCount) {
children.push(<JsonContent json={value} key={`value-${index}`} />)
continue
}
}
// no: it was the last entry
children.push(<span key="rest">...</span>)
suffix = ` length: ${array.length}`
break
}
return (
<>
<span className={styles.array}>{'['}</span>
<span ref={elementRef} className={styles.array}>{children}</span>
<span className={styles.array}>{']'}</span>
{suffix && <span className={styles.comment}>{suffix}</span>}
</>
)
}
function JsonArray({ array, label, expandRoot, pageLimit = defaultPageLimit }: { array: unknown[], label?: string, expandRoot?: boolean, pageLimit?: number }): ReactNode {
const [collapsed, setCollapsed] = useState(!expandRoot && shouldObjectCollapse(array))
const [limit, setLimit] = useState(pageLimit)
const key = label ? <span className={styles.key}>{label}: </span> : ''
if (collapsed) {
return <div role="treeitem" className={styles.clickable} aria-expanded="false" onClick={() => { setCollapsed(false) }}>
{key}
<CollapsedArray array={array} />
</div>
}
return <>
<div role="treeitem" className={styles.clickable} aria-expanded="true" onClick={() => { setCollapsed(true) }}>
{key}
<span className={styles.array}>{'['}</span>
</div>
<ul role="group">
{array.slice(0, limit).map((item, index) => <li key={index}><JsonContent json={item} /></li>)}
{array.length > limit && <li>
<button className={styles.showMore} onClick={() => { setLimit(limit + pageLimit) }}>Show more...</button>
</li>}
</ul>
<div className={styles.array}>{']'}</div>
</>
}
function CollapsedObject({ obj }: { obj: object }): ReactNode {
const { elementRef, width } = useWidth()
const maxCharacterCount = Math.max(20, Math.floor(width / 8))
const separator = ', '
const kvSeparator = ': '
const children: ReactNode[] = []
let suffix: string | undefined
const entries = Object.entries(obj)
let characterCount = 0
for (const [index, [key, value]] of entries.entries()) {
if (index > 0) {
characterCount += separator.length
children.push(<span key={`separator-${index - 1}`}>{separator}</span>)
}
// should we continue?
if (isPrimitive(value)) {
const asString = stringifyPrimitive(value)
characterCount += key.length + kvSeparator.length + asString.length
if (characterCount < maxCharacterCount) {
children.push(<JsonContent json={value as unknown} label={key} key={`value-${index}`} />)
continue
}
}
// no: it was the last entry
children.push(<span key="rest">...</span>)
suffix = ` entries: ${entries.length}`
break
}
return (
<>
<span className={styles.object}>{'{'}</span>
<span ref={elementRef} className={styles.object}>{children}</span>
<span className={styles.object}>{'}'}</span>
{suffix && <span className={styles.comment}>{suffix}</span>}
</>
)
}
function JsonObject({ obj, label, expandRoot, pageLimit = defaultPageLimit }: { obj: object, label?: string, expandRoot?: boolean, pageLimit?: number }): ReactNode {
const [collapsed, setCollapsed] = useState(!expandRoot && shouldObjectCollapse(obj))
const [limit, setLimit] = useState(pageLimit)
const key = label ? <span className={styles.key}>{label}: </span> : ''
if (collapsed) {
return <div role="treeitem" className={styles.clickable} aria-expanded="false" onClick={() => { setCollapsed(false) }}>
{key}
<CollapsedObject obj={obj} />
</div>
}
const entries = Object.entries(obj)
return <>
<div role="treeitem" className={styles.clickable} aria-expanded="true" onClick={() => { setCollapsed(true) }}>
{key}
<span className={styles.object}>{'{'}</span>
</div>
<ul role="group">
{entries.slice(0, limit).map(([key, value]) =>
<li key={key}>
<JsonContent json={value as unknown} label={key} />
</li>
)}
{entries.length > limit && <li>
<button className={styles.showMore} onClick={() => { setLimit(limit + pageLimit) }}>Show more...</button>
</li>}
</ul>
<div className={styles.object}>{'}'}</div>
</>
}