Open History to see the last commit
1/* eslint-disable @typescript-eslint/no-unnecessary-condition */
2import { clsx as cx } from 'clsx'
3import * as goober from 'goober'
4import { createMemo, createSignal, useContext } from 'solid-js'
5import { tokens } from './tokens'
6import {
7 displayValue,
8 getServerComponentSlotUsageSummary,
9 getServerComponentSlots,
10 getServerComponentType,
11} from './utils'
12import { ShadowDomTargetContext } from './context'
13import type { Accessor, JSX } from 'solid-js'
14β
15type ExpanderProps = {
16 expanded: boolean
17 style?: JSX.CSSProperties
18}
19β
20export const Expander = ({ expanded, style: _style = {} }: ExpanderProps) => {
21 const styles = useStyles()
22 return (
23 <span class={styles().expander}>
24 <svg
25 xmlns="http://www.w3.org/2000/svg"
26 width="12"
27 height="12"
28 fill="none"
29 viewBox="0 0 24 24"
30 class={cx(styles().expanderIcon(expanded))}
31 >
32 <path
33 stroke="currentColor"
34 stroke-linecap="round"
35 stroke-linejoin="round"
36 stroke-width="2"
37 d="M9 18l6-6-6-6"
38 ></path>
39 </svg>
40 </span>
41 )
42}
43β
44type Entry = {
45 label: string
46}
47β
48type RendererProps = {
49 handleEntry: HandleEntryFn
50 label?: JSX.Element
51 value: Accessor<unknown>
52 subEntries: Array<Entry>
53 subEntryPages: Array<Array<Entry>>
54 type: string
55 expanded: Accessor<boolean>
56 toggleExpanded: () => void
57 pageSize: number
58 filterSubEntries?: (subEntries: Array<Property>) => Array<Property>
59}
60β
61/**
62 * Chunk elements in the array by size
63 *
64 * when the array cannot be chunked evenly by size, the last chunk will be
65 * filled with the remaining elements
66 *
67 * @example
68 * chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
69 */
70export function chunkArray<T>(array: Array<T>, size: number): Array<Array<T>> {
71 if (size < 1) return []
72 let i = 0
73 const result: Array<Array<T>> = []
74 while (i < array.length) {
75 result.push(array.slice(i, i + size))
76 i = i + size
77 }
78 return result
79}
80β
81type HandleEntryFn = (entry: Entry) => JSX.Element
82β
83type ExplorerProps = Partial<RendererProps> & {
84 defaultExpanded?: true | Record<string, boolean>
85 value: Accessor<unknown>
86}
87β
88type Property = {
89 defaultExpanded?: boolean | Record<string, boolean>
90 label: string
91 value: unknown
92}
93β
94function isIterable(x: any): x is Iterable<unknown> {
95 return Symbol.iterator in x
96}
97β
98function isPlainObject(value: unknown): value is Record<string, unknown> {
99 if (!value || typeof value !== 'object') return false
100 const proto = Object.getPrototypeOf(value)
101 return proto === Object.prototype || proto === null
102}
103β
104export function Explorer({
105 value,
106 defaultExpanded,
107 pageSize = 100,
108 filterSubEntries,
109 ...rest
110}: ExplorerProps) {
111 const [expanded, setExpanded] = createSignal(Boolean(defaultExpanded))
112 const toggleExpanded = () => setExpanded((old) => !old)
113β
114 const type = createMemo(() => typeof value())
115 const subEntries = createMemo(() => {
116 let entries: Array<Property> = []
117β
118 const makeProperty = (sub: { label: string; value: unknown }): Property => {
119 const subDefaultExpanded =
120 defaultExpanded === true
121 ? { [sub.label]: true }
122 : defaultExpanded?.[sub.label]
123 return {
124 ...sub,
125 value: () => sub.value,
126 defaultExpanded: subDefaultExpanded,
127 }
128 }
129β
130 if (
131 Array.isArray(value()) &&
132 (value() as Array<any>).length === 2 &&
133 (value() as Array<any>)[0] === 'React element' &&
134 isPlainObject((value() as Array<any>)[1])
135 ) {
136 // Special case: treat `["React element", { ...meta }]` as sibling entries
137 // to avoid the meta object being rendered as a deeper nested tree.
138 const v = value() as ['React element', Record<string, unknown>]
139 entries = [
140 makeProperty({ label: '0', value: v[0] }),
141 ...Object.entries(v[1]).map(([key, val]) =>
142 makeProperty({ label: key, value: val }),
143 ),
144 ]
145 } else if (Array.isArray(value())) {
146 // any[]
147 entries = (value() as Array<any>).map((d, i) =>
148 makeProperty({
149 label: i.toString(),
150 value: d,
151 }),
152 )
153 } else if (
154 value() !== null &&
155 typeof value() === 'object' &&
156 isIterable(value()) &&
157 typeof (value() as Iterable<unknown>)[Symbol.iterator] === 'function'
158 ) {
159 // Iterable<unknown>
160 entries = Array.from(value() as Iterable<unknown>, (val, i) =>
161 makeProperty({
162 label: i.toString(),
163 value: val,
164 }),
165 )
166 } else if (typeof value() === 'object' && value() !== null) {
167 // object
168 entries = Object.entries(value() as object).map(([key, val]) =>
169 makeProperty({
170 label: key,
171 value: val,
172 }),
173 )
174 }
175β
176 return filterSubEntries ? filterSubEntries(entries) : entries
177 })
178β
179 const subEntryPages = createMemo(() => chunkArray(subEntries(), pageSize))
180β
181 const [expandedPages, setExpandedPages] = createSignal<Array<number>>([])
182 const [valueSnapshot, setValueSnapshot] = createSignal(undefined)
183 const styles = useStyles()
184β
185 const refreshValueSnapshot = () => {
186 setValueSnapshot((value() as () => any)())
187 }
188β
189 const handleEntry = (entry: Entry) => (
190 <Explorer
191 value={value}
192 filterSubEntries={filterSubEntries}
193 {...rest}
194 {...entry}
195 />
196 )
197β
198 const serverComponentType = createMemo(() => getServerComponentType(value()))
199 const serverComponentSlots = createMemo(() =>
200 getServerComponentSlots(value()),
201 )
202 const serverComponentSlotUsageSummary = createMemo(() =>
203 getServerComponentSlotUsageSummary(value()),
204 )
205β
206 const isCompositeWithSlots = createMemo(
207 () =>
208 serverComponentType() === 'compositeSource' &&
209 serverComponentSlots().length > 0,
210 )
211β
212 return (
213 <div class={styles().entry}>
214 {serverComponentType() !== null ? (
215 isCompositeWithSlots() ? (
216 <>
217 <button
218 class={styles().expandButton}
219 onClick={() => toggleExpanded()}
220 >
221 <Expander expanded={expanded() ?? false} />
222 <span>{rest.label}:</span>
223 <span class={styles().compositeComponent}>
224 {displayValue(value())}
225 </span>
226 </button>
227 {(expanded() ?? false) ? (
228 <div class={styles().rscMetaRow}>
229 <span class={styles().rscMetaLabel}>slots</span>
230 <div class={styles().subEntries}>
231 {serverComponentSlots().map((name) => {
232 const usage = serverComponentSlotUsageSummary()[name]
233 if (!usage) return null
234 return (
235 <Explorer
236 label={`${name}:`}
237 value={() =>
238 usage.invocations.map((args) =>
239 args.length === 1 ? args[0] : args,
240 )
241 }
242 />
243 )
244 })}
245 </div>
246 </div>
247 ) : null}
248 </>
249 ) : (
250 <>
251 <span>{rest.label}:</span>{' '}
252 <span
253 class={
254 serverComponentType() === 'compositeSource'
255 ? styles().compositeComponent
256 : styles().renderableComponent
257 }
258 >
259 {displayValue(value())}
260 </span>
261 </>
262 )
263 ) : subEntryPages().length ? (
264 <>
265 <button
266 class={styles().expandButton}
267 onClick={() => toggleExpanded()}
268 >
269 <Expander expanded={expanded() ?? false} />
270 {rest.label}
271 <span class={styles().info}>
272 {String(type).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
273 {subEntries().length} {subEntries().length > 1 ? `items` : `item`}
274 </span>
275 </button>
276 {(expanded() ?? false) ? (
277 subEntryPages().length === 1 ? (
278 <div class={styles().subEntries}>
279 {subEntries().map((entry, index) => handleEntry(entry))}
280 </div>
281 ) : (
282 <div class={styles().subEntries}>
283 {subEntryPages().map((entries, index) => {
284 return (
285 <div>
286 <div class={styles().entry}>
287 <button
288 class={cx(styles().labelButton, 'labelButton')}
289 onClick={() =>
290 setExpandedPages((old) =>
291 old.includes(index)
292 ? old.filter((d) => d !== index)
293 : [...old, index],
294 )
295 }
296 >
297 <Expander
298 expanded={expandedPages().includes(index)}
299 />{' '}
300 [{index * pageSize} ...{' '}
301 {index * pageSize + pageSize - 1}]
302 </button>
303 {expandedPages().includes(index) ? (
304 <div class={styles().subEntries}>
305 {entries.map((entry) => handleEntry(entry))}
306 </div>
307 ) : null}
308 </div>
309 </div>
310 )
311 })}
312 </div>
313 )
314 ) : null}
315 </>
316 ) : type() === 'function' ? (
317 <>
318 <Explorer
319 label={
320 <button
321 onClick={refreshValueSnapshot}
322 class={styles().refreshValueBtn}
323 >
324 <span>{rest.label}</span> π{' '}
325 </button>
326 }
327 value={valueSnapshot}
328 defaultExpanded={{}}
329 />
330 </>
331 ) : (
332 <>
333 <span>{rest.label}:</span>{' '}
334 <span class={styles().value}>{displayValue(value())}</span>
335 </>
336 )}
337 </div>
338 )
339}
340β
341const stylesFactory = (shadowDOMTarget?: ShadowRoot) => {
342 const { colors, font, size, border } = tokens
343 const { fontFamily, lineHeight, size: fontSize } = font
344 const css = shadowDOMTarget
345 ? goober.css.bind({ target: shadowDOMTarget })
346 : goober.css
347β
348 return {
349 entry: css`
350 font-family: ${fontFamily.mono};
351 font-size: ${fontSize.xs};
352 line-height: ${lineHeight.sm};
353 outline: none;
354 word-break: break-word;
355 `,
356 labelButton: css`
357 cursor: pointer;
358 color: inherit;
359 font: inherit;
360 outline: inherit;
361 background: transparent;
362 border: none;
363 padding: 0;
364 `,
365 expander: css`
366 display: inline-flex;
367 align-items: center;
368 justify-content: center;
369 width: ${size[3]};
370 height: ${size[3]};
371 padding-left: 3px;
372 box-sizing: content-box;
373 `,
374 expanderIcon: (expanded: boolean) => {
375 if (expanded) {
376 return css`
377 transform: rotate(90deg);
378 transition: transform 0.1s ease;
379 `
380 }
381 return css`
382 transform: rotate(0deg);
383 transition: transform 0.1s ease;
384 `
385 },
386 expandButton: css`
387 display: flex;
388 gap: ${size[1]};
389 align-items: center;
390 cursor: pointer;
391 color: inherit;
392 font: inherit;
393 outline: inherit;
394 background: transparent;
395 border: none;
396 padding: 0;
397 `,
398 value: css`
399 color: ${colors.purple[400]};
400 `,
401 compositeComponent: css`
402 display: inline-flex;
403 align-items: center;
404 padding: 1px ${size[1]};
405 border-radius: ${border.radius.full};
406 border: 1px solid ${colors.darkGray[500]};
407 background: ${colors.darkGray[700]};
408 color: ${colors.cyan[300]};
409 font-style: normal;
410 font-weight: ${font.weight.medium};
411 `,
412 renderableComponent: css`
413 display: inline-flex;
414 align-items: center;
415 padding: 1px ${size[1]};
416 border-radius: ${border.radius.full};
417 border: 1px solid ${colors.darkGray[500]};
418 background: ${colors.darkGray[700]};
419 color: ${colors.teal[300]};
420 font-style: normal;
421 font-weight: ${font.weight.medium};
422 `,
423 rscMetaRow: css`
424 display: flex;
425 gap: ${size[1]};
426 align-items: flex-start;
427 margin-left: calc(${size[3]} + ${size[1]});
428 margin-top: ${size[0.5]};
429 flex-wrap: wrap;
430 `,
431 rscMetaLabel: css`
432 color: ${colors.gray[500]};
433 font-size: ${fontSize['2xs']};
434 text-transform: uppercase;
435 letter-spacing: 0.06em;
436 padding-top: 2px;
437 `,
438 rscChipRow: css`
439 display: flex;
440 gap: ${size[1]};
441 flex-wrap: wrap;
442 `,
443 rscChip: css`
444 display: inline-flex;
445 align-items: center;
446 gap: ${size[0.5]};
447 padding: 1px ${size[1]};
448 border-radius: ${border.radius.full};
449 border: 1px solid ${colors.darkGray[500]};
450 background: ${colors.darkGray[800]};
451 color: ${colors.gray[200]};
452 font-size: ${fontSize['2xs']};
453 line-height: ${lineHeight.xs};
454 `,
455 rscChipName: css`
456 color: ${colors.gray[100]};
457 `,
458 rscChipMeta: css`
459 color: ${colors.gray[400]};
460 font-size: ${fontSize['2xs']};
461 `,
462 subEntries: css`
463 margin-left: ${size[2]};
464 padding-left: ${size[2]};
465 border-left: 2px solid ${colors.darkGray[400]};
466 `,
467 info: css`
468 color: ${colors.gray[500]};
469 font-size: ${fontSize['2xs']};
470 padding-left: ${size[1]};
471 `,
472 refreshValueBtn: css`
473 appearance: none;
474 border: 0;
475 cursor: pointer;
476 background: transparent;
477 color: inherit;
478 padding: 0;
479 font-family: ${fontFamily.mono};
480 font-size: ${fontSize.xs};
481 `,
482 }
483}
484β
485function useStyles() {
486 const shadowDomTarget = useContext(ShadowDomTargetContext)
487 const [_styles] = createSignal(stylesFactory(shadowDomTarget))
488 return _styles
489}