refactor(client): replace patched JSON tree dependency

This commit is contained in:
_Kerman
2026-07-28 14:37:00 +08:00
parent 1ac0eb9611
commit 64b9535c31
13 changed files with 757 additions and 504 deletions

View File

@@ -1,6 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write
README.md: 58e450451ab64f69762817dfb277b8a888e2177f
README.zh.md: 6824f3efe4981adf9549941afa7e2f5db2ac005d
# pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md
README.md: 29d7b5e20dbc3a53fe4b85e219b0c957c05ed873
README.zh.md: 92d256f7f1d413a9792aa54f50317c2a15dd09a0

View File

@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, markdown family (MessageText/MarkdownText/JsonBlock). Contract: api-contracts v3 §8.
Pure React atoms (zero cordis): StateDot, ic_ds_* icons, Button/Pill/Menu/Modal/Input, the markdown family (MessageText/MarkdownText/JsonBlock), and the read-only JsonTree inspector. Contract: api-contracts v3 §8.
## Markdown rendering

View File

@@ -2,7 +2,7 @@
[English](README.md) | 中文
纯 React 原子组件(零 cordisStateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Input,以及 markdown 家族MessageText/MarkdownText/JsonBlock。契约api-contracts v3 §8。
纯 React 原子组件(零 cordisStateDot、ic_ds_* 图标、Button/Pill/Menu/Modal/Inputmarkdown 家族MessageText/MarkdownText/JsonBlock,以及只读 JsonTree 检查器。契约api-contracts v3 §8。
## Markdown 渲染

View File

@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-client-ui-primitives",
"description": "Pure React atoms for the dsh web UI: StateDot, ic_ds_* icon set, Button/Pill/Menu/Modal/Input, markdown family (zero cordis)",
"description": "Pure React atoms for the dsh web UI: controls, icons, markdown, and JSON inspectors (zero cordis)",
"version": "0.0.1",
"private": true,
"type": "module",
@@ -27,7 +27,6 @@
"micromark-extension-gfm": "^3.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-json-view-lite": "^2.5.0",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"shiki": "^4.3.1"

View File

@@ -1,8 +1,11 @@
import clsx from 'clsx'
import { collapseAllNested, JsonView } from 'react-json-view-lite'
import { useEffect, useRef, useState } from 'react'
import type { MouseEvent as ReactMouseEvent, ReactNode, UIEvent as ReactUIEvent } from 'react'
import type { Props as LiteJsonViewProps } from 'react-json-view-lite'
import { useEffect, useId, useRef, useState } from 'react'
import type {
KeyboardEvent as ReactKeyboardEvent,
MouseEvent as ReactMouseEvent,
ReactNode,
UIEvent as ReactUIEvent,
} from 'react'
import { IconCheckOutline16, IconCopyOutline16 } from './icons/index.tsx'
import { Menu } from './Menu.tsx'
import type { MenuEntry } from './Menu.tsx'
@@ -22,34 +25,35 @@ const OBJECT_COPY_MENU_ITEMS: readonly MenuEntry[] = [
{ id: 'path', label: 'Copy property path' },
]
const TREE_STYLES: NonNullable<LiteJsonViewProps['style']> = {
container: clsx(css.container),
childFieldsContainer: clsx(css.children),
basicChildStyle: clsx(css.row),
label: clsx(css.label),
clickableLabel: clsx(css.label, css.clickableLabel),
nullValue: clsx(css.keywordValue),
undefinedValue: clsx(css.keywordValue),
numberValue: clsx(css.numberValue),
stringValue: clsx(css.stringValue),
booleanValue: clsx(css.keywordValue),
otherValue: clsx(css.otherValue),
punctuation: clsx(css.punctuation),
expandIcon: clsx(css.expander, css.expandIcon),
collapseIcon: clsx(css.expander, css.collapseIcon),
collapsedContent: clsx(css.collapsedContent),
noQuotesForStringValues: false,
quotesForFieldNames: false,
stringifyStringValues: true,
ariaLables: {
collapseJson: 'Collapse JSON node',
expandJson: 'Expand JSON node',
},
type JsonPath = readonly (number | string)[]
interface RowTarget {
path: JsonPath
value: unknown
}
const EXPANDED_TOP_LEVEL_TREE_STYLES: NonNullable<LiteJsonViewProps['style']> = {
...TREE_STYLES,
container: clsx(css.container, css.expandedTopLevelContainer),
interface CopyTarget extends RowTarget {
left: number
side: 'bottom' | 'top'
top: number
}
function isExpandableValue(value: unknown): value is object | unknown[] {
return typeof value === 'object' && value !== null && !(value instanceof Date)
}
function entriesOf(value: object | unknown[]): readonly (readonly [string, unknown])[] {
if (Array.isArray(value)) {
return value.map((item, index) => [String(index), item] as const)
}
return Object.keys(value).map(key => [
key,
(value as Record<string, unknown>)[key],
] as const)
}
function bracketOf(value: object | unknown[]): readonly [string, string] {
return Array.isArray(value) ? ['[', ']'] : ['{', '}']
}
function previewPrimitive(value: unknown): ReactNode {
@@ -79,16 +83,13 @@ function previewPrimitive(value: unknown): ReactNode {
}
function previewValue(value: unknown, depth: number): ReactNode {
if (typeof value !== 'object' || value === null) return previewPrimitive(value)
if (!isExpandableValue(value)) return previewPrimitive(value)
const array = Array.isArray(value)
const entries = array
? value.map((item, index) => [String(index), item] as const)
: Object.entries(value)
const entries = entriesOf(value)
const limit = array ? ARRAY_PREVIEW_LIMIT : OBJECT_PREVIEW_LIMIT
const visible = entries.slice(0, limit)
const open = array ? '[' : '{'
const close = array ? ']' : '}'
const [open, close] = bracketOf(value)
return (
<>
@@ -108,71 +109,208 @@ function previewValue(value: unknown, depth: number): ReactNode {
</span>
))}
{depth < PREVIEW_DEPTH_LIMIT && entries.length > limit && (
<span className={css.previewEllipsis}>{visible.length > 0 ? ', …' : '…'}</span>
<span className={css.previewEllipsis}>, </span>
)}
<span className={css.punctuation}>{close}</span>
</>
)
}
function renderExpandableValue(value: object): ReactNode {
return <span className={css.preview}>{previewValue(value, 0)}</span>
function primitiveValue(value: unknown): ReactNode {
if (value === null) return <span className={css.keywordValue}>null</span>
if (typeof value === 'string') {
return <span className={css.stringValue}>{JSON.stringify(value)}</span>
}
if (typeof value === 'boolean') {
return <span className={css.keywordValue}>{String(value)}</span>
}
if (typeof value === 'number') {
return <span className={css.numberValue}>{String(value)}</span>
}
if (typeof value === 'bigint') {
return <span className={css.numberValue}>{`${value.toString()}n`}</span>
}
if (value instanceof Date) {
return <span className={css.otherValue}>{value.toISOString()}</span>
}
if (typeof value === 'function') {
return <span className={css.otherValue}>function() {'{ }'}</span>
}
if (typeof value === 'undefined') {
return <span className={css.otherValue}>undefined</span>
}
return <span className={css.otherValue}>{(value as symbol).toString()}</span>
}
interface CopyTarget {
left: number
path: readonly (number | string)[]
side: 'bottom' | 'top'
top: number
value: unknown
function fieldText(field: string): string {
return field === '' ? '""' : field
}
function fieldOf(row: HTMLElement): string | undefined {
const label = Array.from(row.children).find(
child => child instanceof HTMLElement && child.classList.contains(clsx(css.label)),
function pathId(path: JsonPath): string {
return path.map(part => (
typeof part === 'number' ? `n${String(part)}` : `s${String(part.length)}:${part}`
)).join('/')
}
function claimFocus(button: HTMLElement): void {
button.focus()
}
function moveFocus(button: HTMLElement, direction: -1 | 1): void {
const tree = button.closest<HTMLElement>('[role="tree"]')
/* v8 ignore next -- JsonTree attaches expander handlers only beneath its owning role=tree. */
if (tree === null) return
const expanders = Array.from(tree.querySelectorAll<HTMLElement>('[data-json-expander]'))
const current = expanders.indexOf(button)
/* v8 ignore next -- the current expander is a member of the queried non-empty set. */
if (current < 0 || expanders.length === 0) return
const next = (current + direction + expanders.length) % expanders.length
const nextExpander = expanders[next]
/* v8 ignore next -- modulo over the non-empty expander set always resolves a member. */
if (nextExpander !== undefined) claimFocus(nextExpander)
}
function NodeField({
field,
expandable,
onToggle,
}: {
field: string | undefined
expandable: boolean
onToggle: () => void
}) {
if (field === undefined) return null
return (
<span
className={clsx(css.label, expandable && css.clickableLabel)}
onClick={expandable ? onToggle : undefined}
>
{fieldText(field)}:
</span>
)
const text = label?.textContent
return text === undefined ? undefined : text.slice(0, -1)
}
function resolveRow(data: object | unknown[], row: HTMLElement, expandTopLevel: boolean): {
path: readonly (number | string)[]
interface JsonTreeNodeProps {
field?: string
initialExpanded: boolean
lastElement: boolean
onClaimTabStop: (id: string) => void
onRowHover: (row: HTMLElement, target: RowTarget) => void
path: JsonPath
tabStopId: string | null
value: unknown
} | undefined {
if (row.hasAttribute('data-json-root-row')) return { path: [], value: data }
}
const lineage: HTMLElement[] = []
let cursor: HTMLElement | null = row
while (cursor !== null) {
lineage.unshift(cursor)
const group: HTMLElement | null = cursor.parentElement
const parentRow: Element | null = group?.getAttribute('role') === 'group'
? group.parentElement?.closest('[role="treeitem"]') ?? null
: null
cursor = parentRow instanceof HTMLElement ? parentRow : null
function JsonTreeNode({
field,
initialExpanded,
lastElement,
onClaimTabStop,
onRowHover,
path,
tabStopId,
value,
}: JsonTreeNodeProps) {
const contentsId = useId()
const expanderRef = useRef<HTMLSpanElement>(null)
const [expanded, setExpanded] = useState(initialExpanded)
const nodeId = pathId(path)
const container = isExpandableValue(value)
const entries = container ? entriesOf(value) : []
const expandable = entries.length > 0
const toggle = () => {
setExpanded(current => !current)
claimFocus(expanderRef.current as HTMLSpanElement)
}
let value: unknown = data
const path: (number | string)[] = []
for (const item of expandTopLevel ? lineage : lineage.slice(1)) {
const field = fieldOf(item)
if (field === undefined) return undefined
if (Array.isArray(value)) {
const index = Number(field)
if (!Number.isInteger(index)) return undefined
path.push(index)
value = value[index]
} else if (typeof value === 'object' && value !== null) {
path.push(field)
value = (value as Record<string, unknown>)[field]
} else {
return undefined
const onExpanderKeyDown = (event: ReactKeyboardEvent<HTMLSpanElement>) => {
if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') {
event.preventDefault()
setExpanded(event.key === 'ArrowRight')
return
}
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
event.preventDefault()
moveFocus(event.currentTarget, event.key === 'ArrowUp' ? -1 : 1)
}
}
return { path, value }
const row = (children: ReactNode, ariaExpanded?: boolean) => (
<div
className={css.row}
role="treeitem"
aria-expanded={ariaExpanded}
onMouseOver={(event) => {
event.stopPropagation()
onRowHover(event.currentTarget, { path, value })
}}
>
{children}
</div>
)
if (!container) {
return row((
<>
<NodeField field={field} expandable={false} onToggle={toggle} />
{primitiveValue(value)}
{!lastElement && <span className={css.punctuation}>,</span>}
</>
))
}
const [open, close] = bracketOf(value)
if (!expandable) {
return row((
<>
<NodeField field={field} expandable={false} onToggle={toggle} />
<span className={css.punctuation}>{open}</span>
<span className={css.punctuation}>{close}</span>
{!lastElement && <span className={css.punctuation}>,</span>}
</>
))
}
return row((
<>
<span
ref={expanderRef}
className={clsx(css.expander, expanded ? css.collapseIcon : css.expandIcon)}
data-json-expander
role="button"
aria-label={expanded ? 'Collapse JSON node' : 'Expand JSON node'}
aria-expanded={expanded}
aria-controls={expanded ? contentsId : undefined}
tabIndex={tabStopId === nodeId ? 0 : -1}
onFocus={() => { onClaimTabStop(nodeId) }}
onClick={toggle}
onKeyDown={onExpanderKeyDown}
/>
<NodeField field={field} expandable onToggle={toggle} />
<span className={css.preview}>{previewValue(value, 0)}</span>
{expanded && (
<ul id={contentsId} role="group" className={css.children}>
{entries.map(([key, item], index) => (
<JsonTreeNode
key={key}
field={key}
value={item}
path={[...path, Array.isArray(value) ? index : key]}
lastElement={index === entries.length - 1}
initialExpanded={false}
tabStopId={tabStopId}
onClaimTabStop={onClaimTabStop}
onRowHover={onRowHover}
/>
))}
</ul>
)}
</>
), expanded)
}
function formattedPath(path: readonly (number | string)[]): string {
function formattedPath(path: JsonPath): string {
return path.reduce<string>((result, part) => {
if (typeof part === 'number') return `${result}[${String(part)}]`
return /^[A-Za-z_$][\w$]*$/.test(part)
@@ -186,9 +324,6 @@ function copyText(target: CopyTarget, mode: 'json' | 'path' | 'prettyJson' | 'va
if (mode === 'prettyJson') return JSON.stringify(target.value, null, 2)
if (mode === 'json') return JSON.stringify(target.value)
if (typeof target.value === 'string') return target.value
if (typeof target.value === 'object' && target.value !== null) {
return JSON.stringify(target.value, null, 2)
}
if (typeof target.value === 'undefined') return 'undefined'
if (typeof target.value === 'bigint') return target.value.toString()
if (typeof target.value === 'symbol') return target.value.description ?? 'Symbol'
@@ -222,6 +357,16 @@ export function JsonTree({
copyable = true,
expandTopLevel = true,
}: JsonTreeProps) {
const rootEntries = entriesOf(data)
const firstExpandableIndex = rootEntries.findIndex(([, value]) => (
isExpandableValue(value) && entriesOf(value).length > 0
))
const firstExpandableEntry = rootEntries[firstExpandableIndex]
const initialTabStopId = expandTopLevel
? firstExpandableEntry === undefined
? null
: pathId([Array.isArray(data) ? firstExpandableIndex : firstExpandableEntry[0]])
: isExpandableValue(data) && rootEntries.length > 0 ? pathId([]) : null
const rootRef = useRef<HTMLDivElement>(null)
const activeRowRef = useRef<HTMLElement>()
const copyButtonRef = useRef<HTMLButtonElement>(null)
@@ -230,11 +375,7 @@ export function JsonTree({
const [copyTarget, setCopyTarget] = useState<CopyTarget>()
const [copyState, setCopyState] = useState<'idle' | 'copied' | 'failed'>('idle')
const [copyMenuOpen, setCopyMenuOpen] = useState(false)
useEffect(() => () => {
if (resetTimer.current !== undefined) clearTimeout(resetTimer.current)
activeRowRef.current?.removeAttribute('data-json-copy-active')
}, [])
const [tabStopId, setTabStopId] = useState<string | null>(initialTabStopId)
const setActiveRow = (row: HTMLElement | undefined) => {
activeRowRef.current?.removeAttribute('data-json-copy-active')
@@ -242,38 +383,6 @@ export function JsonTree({
row?.setAttribute('data-json-copy-active', '')
}
const positionCopyButton = (row: HTMLElement, target: {
path: readonly (number | string)[]
value: unknown
}) => {
const root = rootRef.current
if (root === null) return
const rootRect = root.getBoundingClientRect()
const rowRect = row.getBoundingClientRect()
setCopyTarget({
left: rootRect.left + root.clientWidth - 26,
path: target.path,
side: rowRect.top - rootRect.top > root.clientHeight / 2 ? 'top' : 'bottom',
top: rowRect.top,
value: target.value,
})
}
useEffect(() => {
const reposition = () => {
const row = activeRowRef.current
if (row === undefined) return
const resolved = resolveRow(data, row, expandTopLevel)
if (resolved !== undefined) positionCopyButton(row, resolved)
}
window.addEventListener('scroll', reposition, true)
window.addEventListener('resize', reposition)
return () => {
window.removeEventListener('scroll', reposition, true)
window.removeEventListener('resize', reposition)
}
}, [data, expandTopLevel])
const clearCopyTarget = () => {
setActiveRow(undefined)
setCopyTarget(undefined)
@@ -282,35 +391,85 @@ export function JsonTree({
setCopyMenuOpen(false)
}
const handleMouseOver = (event: ReactMouseEvent<HTMLDivElement>) => {
if (!copyable || !(event.target instanceof Element)) return
if (copyMenuOpenRef.current) return
if (!event.currentTarget.contains(event.target)) return
if (event.target.closest('[data-json-copy-button]') !== null) return
const row = event.target.closest<HTMLElement>('[data-json-root-row], [role="treeitem"]')
if (row === null) {
clearCopyTarget()
return
const copyPosition = (row: HTMLElement): Pick<CopyTarget, 'left' | 'side' | 'top'> => {
const root = rootRef.current
/* v8 ignore next -- row events and viewport listeners run only after the root ref mounts. */
if (root === null) throw new Error('JsonTree root is not mounted')
const rootRect = root.getBoundingClientRect()
const rowRect = row.getBoundingClientRect()
return {
left: rootRect.left + root.clientWidth - 26,
side: rowRect.top - rootRect.top > root.clientHeight / 2 ? 'top' : 'bottom',
top: rowRect.top,
}
}
const positionCopyButton = (row: HTMLElement, target: RowTarget) => {
const position = copyPosition(row)
setCopyTarget({ ...target, ...position })
}
const repositionCopyButton = (row: HTMLElement) => {
const position = copyPosition(row)
setCopyTarget((current) => {
/* v8 ignore next -- an active row and its copy target are installed together. */
if (current === undefined) return current
return { ...current, ...position }
})
}
useEffect(() => () => {
if (resetTimer.current !== undefined) clearTimeout(resetTimer.current)
activeRowRef.current?.removeAttribute('data-json-copy-active')
}, [])
useEffect(() => {
activeRowRef.current?.removeAttribute('data-json-copy-active')
activeRowRef.current = undefined
copyMenuOpenRef.current = false
setCopyTarget(undefined)
setCopyState('idle')
setCopyMenuOpen(false)
setTabStopId(initialTabStopId)
}, [data, expandTopLevel, initialTabStopId])
useEffect(() => {
const reposition = () => {
const row = activeRowRef.current
if (row !== undefined) repositionCopyButton(row)
}
window.addEventListener('scroll', reposition, true)
window.addEventListener('resize', reposition)
return () => {
window.removeEventListener('scroll', reposition, true)
window.removeEventListener('resize', reposition)
}
}, [])
const handleRowHover = (row: HTMLElement, target: RowTarget) => {
if (!copyable || copyMenuOpenRef.current) return
if (activeRowRef.current === row) return
const resolved = resolveRow(data, row, expandTopLevel)
if (resolved === undefined) return
setActiveRow(row)
setCopyState('idle')
copyMenuOpenRef.current = false
setCopyMenuOpen(false)
positionCopyButton(row, resolved)
positionCopyButton(row, target)
}
const handleScroll = (event: ReactUIEvent<HTMLDivElement>) => {
if (event.currentTarget !== event.target) return
const handleRootMouseOver = (event: ReactMouseEvent<HTMLDivElement>) => {
if (!copyable || copyMenuOpenRef.current) return
/* v8 ignore next -- browser mouse events delivered through React target an Element. */
if (!(event.target instanceof Element)) return
if (event.target.closest('[data-json-copy-button]') === null) clearCopyTarget()
}
const handleScroll = (_event: ReactUIEvent<HTMLDivElement>) => {
const row = activeRowRef.current
if (row === undefined) return
const resolved = resolveRow(data, row, expandTopLevel)
if (resolved !== undefined) positionCopyButton(row, resolved)
if (row !== undefined) repositionCopyButton(row)
}
const copy = async (mode: 'json' | 'path' | 'prettyJson' | 'value') => {
/* v8 ignore next -- copy controls only render while their target exists. */
if (copyTarget === undefined) return
try {
await navigator.clipboard.writeText(copyText(copyTarget, mode))
@@ -322,6 +481,7 @@ export function JsonTree({
resetTimer.current = setTimeout(() => { setCopyState('idle') }, 1_500)
}
const [rootOpen, rootClose] = bracketOf(data)
const copyTargetIsObject = typeof copyTarget?.value === 'object' && copyTarget.value !== null
const defaultCopyMode = copyTargetIsObject ? 'prettyJson' : 'value'
const copyTitle = copyState === 'copied'
@@ -334,7 +494,7 @@ export function JsonTree({
<div
ref={rootRef}
className={clsx(css.root, className)}
onMouseOver={handleMouseOver}
onMouseOver={handleRootMouseOver}
onMouseLeave={() => {
if (!copyMenuOpenRef.current) clearCopyTarget()
}}
@@ -343,32 +503,52 @@ export function JsonTree({
{expandTopLevel
? (
<div className={css.expandedTopLevel}>
<div className={clsx(css.row, css.topLevelBracket)} data-json-root-row>
<span className={css.punctuation}>{Array.isArray(data) ? '[' : '{'}</span>
<div
className={clsx(css.row, css.topLevelBracket)}
data-json-root-row
onMouseOver={(event) => {
event.stopPropagation()
handleRowHover(event.currentTarget, { path: [], value: data })
}}
>
<span className={css.punctuation}>{rootOpen}</span>
</div>
<JsonView
<div
aria-label={label}
compactTopLevel
data={data}
style={EXPANDED_TOP_LEVEL_TREE_STYLES}
shouldExpandNode={collapseAllNested}
clickToExpandNode
renderExpandableValue={renderExpandableValue}
/>
className={clsx(css.container, css.expandedTopLevelContainer)}
role="tree"
>
{rootEntries.map(([key, value], index) => (
<JsonTreeNode
key={key}
field={key}
value={value}
path={[Array.isArray(data) ? index : key]}
lastElement
initialExpanded={false}
tabStopId={tabStopId}
onClaimTabStop={setTabStopId}
onRowHover={handleRowHover}
/>
))}
</div>
<div className={clsx(css.row, css.topLevelBracket)}>
<span className={css.punctuation}>{Array.isArray(data) ? ']' : '}'}</span>
<span className={css.punctuation}>{rootClose}</span>
</div>
</div>
)
: (
<JsonView
aria-label={label}
data={data}
style={TREE_STYLES}
shouldExpandNode={collapseAllNested}
clickToExpandNode
renderExpandableValue={renderExpandableValue}
/>
<div aria-label={label} className={css.container} role="tree">
<JsonTreeNode
value={data}
path={[]}
lastElement
initialExpanded
tabStopId={tabStopId}
onClaimTabStop={setTabStopId}
onRowHover={handleRowHover}
/>
</div>
)}
{copyTarget !== undefined && (
<span
@@ -405,14 +585,14 @@ export function JsonTree({
)}
items={copyTargetIsObject ? OBJECT_COPY_MENU_ITEMS : VALUE_COPY_MENU_ITEMS}
onSelect={(id) => {
if (id === 'value' || id === 'json' || id === 'prettyJson' || id === 'path') {
void copy(id)
}
void copy(id as 'json' | 'path' | 'prettyJson' | 'value')
copyMenuOpenRef.current = false
setCopyMenuOpen(false)
}}
onClose={clearCopyTarget}
getAnchorRect={() => copyButtonRef.current?.getBoundingClientRect() ?? null}
getAnchorRect={() => (
copyButtonRef.current as HTMLButtonElement
).getBoundingClientRect()}
/>
</span>
)}

View File

@@ -0,0 +1,339 @@
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { JsonTree } from '@deepseek-ai/dsh-client-ui-primitives'
let writeText: ReturnType<typeof vi.fn>
beforeEach(() => {
writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
})
})
afterEach(() => {
cleanup()
vi.useRealTimers()
})
describe('JsonTree', () => {
it('keeps the top level open and renders expandable value previews', () => {
render(
<JsonTree
label="Payload"
data={{
nested: { answer: 42 },
list: ['alpha', 'beta'],
}}
/>,
)
const tree = screen.getByRole('tree', { name: 'Payload' })
const rows = within(tree).getAllByRole('treeitem')
expect(rows).toHaveLength(2)
expect(rows[0]?.textContent).toBe('nested:{answer: 42}')
expect(rows[1]?.textContent).toBe('list:["alpha", "beta"]')
const expanders = within(tree).getAllByRole('button', { name: 'Expand JSON node' })
expect(expanders[0]?.tabIndex).toBe(0)
expect(expanders[1]?.tabIndex).toBe(-1)
fireEvent.click(expanders[0] as HTMLElement)
expect(within(tree).getAllByRole('treeitem')).toHaveLength(3)
expect(screen.getByText('answer:')).toBeDefined()
expect(within(tree).getByRole('button', { name: 'Collapse JSON node' })).toBeDefined()
})
it('moves the single tab stop between visible expanders with arrow keys', () => {
render(
<JsonTree
expandTopLevel={false}
data={{
first: { nested: 1 },
second: { nested: 2 },
}}
/>,
)
const tree = screen.getByRole('tree', { name: 'JSON' })
const root = within(tree).getByRole('button', { name: 'Collapse JSON node' })
const children = within(tree).getAllByRole('button', { name: 'Expand JSON node' })
expect(root.tabIndex).toBe(0)
fireEvent.keyDown(root, { key: 'ArrowDown' })
expect(document.activeElement).toBe(children[0])
expect(root.tabIndex).toBe(-1)
expect(children[0]?.tabIndex).toBe(0)
fireEvent.keyDown(children[0] as HTMLElement, { key: 'ArrowRight' })
expect(children[0]?.getAttribute('aria-expanded')).toBe('true')
fireEvent.keyDown(children[0] as HTMLElement, { key: 'ArrowLeft' })
expect(children[0]?.getAttribute('aria-expanded')).toBe('false')
fireEvent.keyDown(children[0] as HTMLElement, { key: 'Enter' })
fireEvent.keyDown(children[0] as HTMLElement, { key: 'ArrowUp' })
expect(document.activeElement).toBe(root)
fireEvent.keyDown(root, { key: 'ArrowUp' })
expect(document.activeElement).toBe(children[1])
})
it('copies an array element path without recovering data from rendered labels', async () => {
render(<JsonTree data={{ list: [{ value: 'x' }, 'tail'] }} />)
const tree = screen.getByRole('tree')
fireEvent.click(within(tree).getByRole('button', { name: 'Expand JSON node' }))
const arrayRow = within(tree).getAllByRole('treeitem')
.find(row => row.textContent?.startsWith('0:'))
expect(arrayRow).toBeDefined()
fireEvent.mouseOver(arrayRow as HTMLElement)
const copyButton = screen.getByRole('button', { name: 'Copy pretty JSON' })
fireEvent.contextMenu(copyButton)
fireEvent.click(screen.getByRole('menuitem', { name: 'Copy property path' }))
await waitFor(() => {
expect(writeText).toHaveBeenCalledWith('$.list[0]')
})
})
it('renders empty containers, JSON-adjacent primitives, and bounded deep previews', () => {
const anonymous = Object.defineProperty(() => {}, 'name', { value: '' })
const date = new Date('2026-07-28T00:00:00.000Z')
const data = {
'': 'empty key',
nil: null,
text: 'quoted',
flag: true,
count: 3,
big: 4n,
date,
named: function named() {},
missing: undefined,
symbol: Symbol('token'),
emptyObject: {},
emptyArray: [],
primitivePreview: {
nil: null,
flag: false,
big: 9n,
missing: undefined,
},
exoticPreview: {
symbol: Symbol(),
named: function sample() {},
anonymous,
date,
},
wideObject: { a: 1, b: 2, c: 3, d: 4, e: 5 },
wideArray: [1, 2, 3, 4, 5, 6],
deep: { a: { b: { c: 1 } } },
}
render(<JsonTree copyable={false} data={data} />)
const text = screen.getByRole('tree').textContent
expect(text).toContain('"":\"empty key\"')
expect(text).toContain('nil:null')
expect(text).toContain('flag:true')
expect(text).toContain('count:3')
expect(text).toContain('big:4n')
expect(text).toContain('date:2026-07-28T00:00:00.000Z')
expect(text).toContain('named:function() { }')
expect(text).toContain('missing:undefined')
expect(text).toContain('symbol:Symbol(token)')
expect(text).toContain('emptyObject:{}')
expect(text).toContain('emptyArray:[]')
expect(text).toContain('primitivePreview:{nil: null, flag: false, big: 9, missing: undefined}')
expect(text).toContain('exoticPreview:{symbol: Symbol, named: sample, anonymous: Function, date: }')
expect(text).toContain('wideObject:{a: 1, b: 2, c: 3, d: 4, …}')
expect(text).toContain('wideArray:[1, 2, 3, 4, 5, …]')
expect(text).toContain('deep:{a: {b: {…}}}')
expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
fireEvent.mouseOver(screen.getByRole('tree').parentElement as HTMLElement)
})
it('renders child commas and lets a clickable property label toggle its node', () => {
render(<JsonTree data={{ parent: { emptyObject: {}, emptyArray: [], scalar: 1, last: 2 } }} />)
fireEvent.click(screen.getByText('parent:'))
const tree = screen.getByRole('tree')
const rows = within(tree).getAllByRole('treeitem')
expect(rows.find(row => row.textContent === 'emptyObject:{},')).toBeDefined()
expect(rows.find(row => row.textContent === 'emptyArray:[],')).toBeDefined()
expect(rows.find(row => row.textContent === 'scalar:1,')).toBeDefined()
expect(rows.find(row => row.textContent === 'last:2')).toBeDefined()
fireEvent.click(screen.getByText('parent:'))
expect(within(tree).getAllByRole('treeitem')).toHaveLength(1)
})
it('assigns the initial array tab stop and supports an empty collapsible root', () => {
const first = render(<JsonTree data={['plain', { nested: true }]} />)
const tree = screen.getByRole('tree')
expect(tree.textContent).toContain('0:"plain"')
expect(within(tree).getByRole('button', { name: 'Expand JSON node' }).tabIndex).toBe(0)
first.unmount()
render(<JsonTree expandTopLevel={false} data={{}} />)
expect(screen.getByRole('tree').textContent).toBe('{}')
expect(screen.queryByRole('button', { name: /JSON node/ })).toBeNull()
})
it('copies primitive and object values in every menu mode', async () => {
const anonymous = Object.defineProperty(() => {}, 'name', { value: '' })
render(
<JsonTree
data={{
plain: 'hello',
'odd-key': 3,
object: { a: 1 },
missing: undefined,
big: 7n,
symbol: Symbol(),
symbolNamed: Symbol('token'),
named: function named() {},
anonymous,
}}
/>,
)
const tree = screen.getByRole('tree')
const row = (prefix: string) => {
const match = within(tree).getAllByRole('treeitem')
.find(item => item.textContent?.startsWith(prefix))
expect(match).toBeDefined()
return match as HTMLElement
}
const hover = (prefix: string) => {
fireEvent.mouseOver(row(prefix))
return screen.getByRole('button', { name: /Cop/ })
}
const select = (name: string) => {
const button = screen.getByRole('button', { name: /Cop/ })
fireEvent.contextMenu(button)
fireEvent.click(screen.getByRole('menuitem', { name }))
}
fireEvent.click(hover('plain:'))
await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('hello') })
hover('odd-key:')
select('Copy property path')
await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('$["odd-key"]') })
select('Copy JSON')
await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('3') })
fireEvent.click(hover('odd-key:'))
await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('3') })
fireEvent.click(hover('object:'))
await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('{\n "a": 1\n}') })
select('Copy compact JSON')
await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith('{"a":1}') })
for (const [prefix, expected] of [
['missing:', 'undefined'],
['big:', '7'],
['symbol:', 'Symbol'],
['symbolNamed:', 'token'],
['named:', 'named'],
['anonymous:', 'Function'],
] as const) {
fireEvent.click(hover(prefix))
await waitFor(() => { expect(writeText).toHaveBeenLastCalledWith(expected) })
}
})
it('reports clipboard failure, resets feedback, and clears a prior timer', async () => {
vi.useFakeTimers()
writeText.mockRejectedValue(new Error('denied'))
const view = render(<JsonTree data={{ value: 'x' }} />)
const row = screen.getByRole('treeitem')
fireEvent.mouseOver(row)
fireEvent.click(screen.getByRole('button', { name: 'Copy value' }))
await act(async () => { await Promise.resolve() })
expect(screen.getByRole('button', { name: 'Copy failed' })).toBeDefined()
fireEvent.click(screen.getByRole('button', { name: 'Copy failed' }))
await act(async () => { await Promise.resolve() })
act(() => { vi.advanceTimersByTime(1_500) })
expect(screen.getByRole('button', { name: 'Copy value' })).toBeDefined()
view.unmount()
})
it('keeps copy placement synchronized and clears stale targets', () => {
const view = render(<JsonTree data={{ first: { a: 1 }, second: 2 }} />)
const root = view.container.firstElementChild as HTMLElement
const tree = screen.getByRole('tree')
const firstRow = within(tree).getAllByRole('treeitem')[0] as HTMLElement
const secondRow = within(tree).getAllByRole('treeitem')[1] as HTMLElement
Object.defineProperty(root, 'clientHeight', { configurable: true, value: 100 })
Object.defineProperty(root, 'clientWidth', { configurable: true, value: 300 })
vi.spyOn(root, 'getBoundingClientRect').mockReturnValue({
bottom: 100,
height: 100,
left: 10,
right: 310,
top: 0,
width: 300,
x: 10,
y: 0,
toJSON: () => ({}),
})
vi.spyOn(firstRow, 'getBoundingClientRect').mockReturnValue({
bottom: 91,
height: 16,
left: 10,
right: 200,
top: 75,
width: 190,
x: 10,
y: 75,
toJSON: () => ({}),
})
fireEvent.mouseOver(firstRow)
const copyButton = screen.getByRole('button', { name: 'Copy pretty JSON' })
expect((copyButton.closest('span')?.parentElement as HTMLElement).style.left).toBe('284px')
fireEvent.mouseOver(copyButton)
expect(screen.getByRole('button', { name: 'Copy pretty JSON' })).toBeDefined()
fireEvent.mouseOver(firstRow)
fireEvent.scroll(root)
fireEvent.scroll(window)
fireEvent.resize(window)
fireEvent.contextMenu(copyButton)
fireEvent.mouseOver(secondRow)
fireEvent.mouseOver(root)
fireEvent.mouseLeave(root)
expect(screen.getByRole('menu')).toBeDefined()
fireEvent.keyDown(document, { key: 'Escape' })
expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
fireEvent.mouseOver(secondRow)
expect(screen.getByRole('button', { name: 'Copy value' })).toBeDefined()
fireEvent.mouseOver(root)
expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
fireEvent.scroll(root)
view.rerender(<JsonTree data={{ replacement: 3 }} />)
expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
})
it('copies the fixed root and clears it when the pointer leaves', async () => {
const view = render(<JsonTree data={{ value: 1 }} />)
const root = view.container.firstElementChild as HTMLElement
const openingBracket = root.querySelector<HTMLElement>('[data-json-root-row]')
expect(openingBracket).not.toBeNull()
fireEvent.mouseOver(openingBracket as HTMLElement)
fireEvent.click(screen.getByRole('button', { name: 'Copy pretty JSON' }))
await waitFor(() => { expect(writeText).toHaveBeenCalledWith('{\n "value": 1\n}') })
fireEvent.mouseLeave(root)
expect(screen.queryByRole('button', { name: /Copy/ })).toBeNull()
})
})