diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d558d0..fd74020 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and ### Added - Pin your favourite tools to the top. Use the pin next to any tool's name, or Pin in the ⌘K palette, and the tool appears in a Pinned section at the top of the sidebar and the home page, in order, with its ⌘1–⌘9 shortcut shown beside it. Up to nine tools can be pinned. +- JSON Formatter: narrow the output to one part of the document. Select a node in Tree view and press Filter, or type a path into the new Filter field as `.items[0].id`, `items[0].id`, `$.items[0].id` or `/items/0/id`. Both the text output and the tree show just that node, and Copy copies just that node. Copied paths still point into the whole document. A path that doesn't match says where it stopped (`.items has 3 items; there is no [5]`), and the ↑ button moves up one level. ### Fixed - On phones, the GitHub and Settings icons at the top right no longer have a wide empty gap between them. diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index 94560c8..03f7785 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -6,7 +6,9 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and ## [Unreleased] -Nothing yet. +### Added +- `/json`: `selectPath(root, path)` narrows a document to the node a path points at. The path can be a JSON pointer, a dot path or a jq path, and the result is `{ ok, value, path }` with array steps as numbers. When nothing matches, it returns a message saying where the walk stopped, written in the same path style that was typed. Also added `detectPathFlavor` and `formatPath`. +- `/json`: `parseDotPath` also reads a JSONPath-style `$.` or `$[` root. ## [0.2.0] — 2026-10-29 diff --git a/packages/core/src/json/paths.test.ts b/packages/core/src/json/paths.test.ts index cfbf060..80d1391 100644 --- a/packages/core/src/json/paths.test.ts +++ b/packages/core/src/json/paths.test.ts @@ -3,10 +3,13 @@ import { describe, expect, it } from 'vitest' import { toDotPath, toJsonPointer } from './embedded.ts' import { MISSING, + detectPathFlavor, + formatPath, parseDotPath, parseJqPath, parsePointer, resolvePath, + selectPath, toJqPath, } from './paths.ts' import { allContainerPointers, flattenTree, pathOf } from './tree.ts' @@ -90,3 +93,94 @@ describe('round-trip properties', () => { ) }) }) + +describe('parseDotPath with a JSONPath root', () => { + it('reads $. and $[ as the root marker', () => { + expect(parseDotPath('$.items[0].id')).toEqual(['items', 0, 'id']) + expect(parseDotPath('$[0]')).toEqual([0]) + expect(parseDotPath('$ref.a')).toEqual(['$ref', 'a']) + }) +}) + +describe('detectPathFlavor', () => { + it('tells the flavours apart by their first character', () => { + expect(detectPathFlavor('/items/0')).toBe('pointer') + expect(detectPathFlavor('.items[0]')).toBe('jq') + expect(detectPathFlavor('items[0]')).toBe('dot') + expect(detectPathFlavor('[0].id')).toBe('dot') + expect(detectPathFlavor('$.items')).toBe('dot') + }) +}) + +describe('selectPath', () => { + const data = { items: [{ id: 7, tags: ['a'] }], 'a b': null, '': 'empty' } + + it('selects the same node from every flavour', () => { + for (const src of ['/items/0/id', 'items[0].id', '.items[0].id', '$.items[0].id', ' .items[0].id ']) { + const r = selectPath(data, src) + expect(r).toMatchObject({ ok: true, value: 7, path: ['items', 0, 'id'] }) + } + }) + + it('treats blank, "/", "." and "$" as the whole document', () => { + for (const src of ['', ' ', '/', '.', '$']) { + expect(selectPath(data, src)).toMatchObject({ ok: true, value: data, path: [] }) + } + }) + + it('normalises pointer tokens into array indices', () => { + const r = selectPath(data, '/items/0/tags/0') + expect(r).toMatchObject({ ok: true, value: 'a', path: ['items', 0, 'tags', 0] }) + }) + + it('reaches keys that are not identifiers', () => { + expect(selectPath(data, '.["a b"]')).toMatchObject({ ok: true, value: null }) + expect(selectPath(data, '.[""]')).toMatchObject({ ok: true, value: 'empty' }) + }) + + it('says where the walk stopped, in the flavour that was typed', () => { + expect(selectPath(data, '.items[0].nope')).toEqual({ + ok: false, + flavor: 'jq', + message: '.items[0] has no key "nope"', + }) + expect(selectPath(data, '/items/3')).toEqual({ + ok: false, + flavor: 'pointer', + message: '/items has 1 item; there is no [3]', + }) + expect(selectPath(data, 'items[0].id.x')).toEqual({ + ok: false, + flavor: 'dot', + message: 'items[0].id is a number, so it has no children', + }) + expect(selectPath(data, '/items/-')).toMatchObject({ + ok: false, + message: '/items is an array; "-" is not an index', + }) + expect(selectPath(data, '.missing')).toMatchObject({ ok: false, message: 'the root has no key "missing"' }) + }) + + it('reports a malformed path instead of throwing', () => { + const r = selectPath(data, '.items[0') + expect(r.ok).toBe(false) + if (!r.ok) expect(r.message).toMatch(/^Not a valid path/) + }) + + it('agrees with resolvePath on every row of a document', () => { + const { expanded } = allContainerPointers(doc) + const rows = flattenTree(doc, expanded) + for (const [index] of rows.entries()) { + const path = pathOf(rows, index) + for (const flavor of ['pointer', 'dot', 'jq'] as const) { + const src = formatPath(path, flavor) + // '' as a pointer is the root, but so is '/' here; the one key that + // collides is the "" key, which needs the jq or dot form. + if (flavor === 'pointer' && path.length === 1 && path[0] === '') continue + const r = selectPath(doc, src) + expect(r).toMatchObject({ ok: true, path }) + if (r.ok) expect(r.value).toBe(resolvePath(doc, path)) + } + } + }) +}) diff --git a/packages/core/src/json/paths.ts b/packages/core/src/json/paths.ts index 2bcdf58..bd55100 100644 --- a/packages/core/src/json/paths.ts +++ b/packages/core/src/json/paths.ts @@ -11,7 +11,9 @@ * than none. */ +import { toDotPath, toJsonPointer } from './embedded.ts' import { isRawNumber } from './rawjson.ts' +import { kindOf } from './tree.ts' export type PathSegment = string | number @@ -84,9 +86,17 @@ function parseAccessors(src: string, start: number, ident: RegExp): PathSegment[ return out } +const DOT_IDENT = /^[A-Za-z_$][\w$]*/ + +/** + * Also reads a JSONPath-style `$.a[0]` / `$[0]` root. `toDotPath` never writes + * one (a leading `$` key comes out as `["$"]`), so this cannot misread a path + * it produced. + */ export function parseDotPath(path: string): PathSegment[] { if (path === '$') return [] - return parseAccessors(path, 0, /^[A-Za-z_$][\w$]*/) + if (path.startsWith('$.') || path.startsWith('$[')) return parseAccessors(path, 1, DOT_IDENT) + return parseAccessors(path, 0, DOT_IDENT) } export function parseJqPath(path: string): PathSegment[] { @@ -121,3 +131,91 @@ export function resolvePath(root: unknown, path: readonly PathSegment[]): unknow } export { MISSING } + +export type PathFlavor = 'pointer' | 'dot' | 'jq' + +/** + * Which flavour a typed path is in. The three are told apart by their first + * character, so detection never has to guess: `/` is a pointer, `.` is jq, and + * anything else is a dot path. + */ +export function detectPathFlavor(src: string): PathFlavor { + if (src === '' || src.startsWith('/')) return 'pointer' + if (src.startsWith('.')) return 'jq' + return 'dot' +} + +export function formatPath(path: readonly PathSegment[], flavor: PathFlavor): string { + if (flavor === 'pointer') return toJsonPointer(path) + return flavor === 'jq' ? toJqPath(path) : toDotPath(path) +} + +export type Selection = + | { + ok: true + value: unknown + /** Normalised: array steps are numbers, whatever flavour was typed. */ + path: PathSegment[] + flavor: PathFlavor + } + | { ok: false; message: string; flavor: PathFlavor } + +/** + * Narrow a document to the node a typed path points at, for "filter to this + * node". Accepts any of the three flavours, and JSONPath's `$.` root. + * Blank selects the whole document, and so does `/`, which is what the tree's + * Pointer button copies for the root; RFC 6901 would read it as the `""` key, + * which stays reachable as `.[""]`. + * + * Failures say where the walk stopped, written in the flavour that was typed, + * because "not found" alone sends you counting brackets. + */ +export function selectPath(root: unknown, src: string): Selection { + const text = src.trim() + const flavor = detectPathFlavor(text) + if (text === '' || text === '/') return { ok: true, value: root, path: [], flavor } + + let segments: PathSegment[] + try { + segments = + flavor === 'pointer' + ? parsePointer(text) + : flavor === 'jq' + ? parseJqPath(text) + : parseDotPath(text) + } catch (e) { + return { ok: false, message: `Not a valid path: ${(e as Error).message}`, flavor } + } + + const path: PathSegment[] = [] + let node = root + for (const segment of segments) { + const here = path.length === 0 ? 'the root' : formatPath(path, flavor) + const kind = kindOf(node) + if (kind === 'array') { + const items = node as unknown[] + const i = + typeof segment === 'number' ? segment : /^(0|[1-9]\d*)$/.test(segment) ? Number(segment) : -1 + if (i < 0) { + const message = `${here} is an array; ${JSON.stringify(segment)} is not an index` + return { ok: false, message, flavor } + } + if (i >= items.length) { + const noun = items.length === 1 ? 'item' : 'items' + return { ok: false, message: `${here} has ${items.length} ${noun}; there is no [${i}]`, flavor } + } + path.push(i) + node = items[i] + } else if (kind === 'object') { + const key = String(segment) + if (!Object.hasOwn(node as object, key)) { + return { ok: false, message: `${here} has no key ${JSON.stringify(key)}`, flavor } + } + path.push(key) + node = (node as Record)[key] + } else { + return { ok: false, message: `${here} is a ${kind}, so it has no children`, flavor } + } + } + return { ok: true, value: node, path, flavor } +} diff --git a/src/tools/json/JsonTool.tsx b/src/tools/json/JsonTool.tsx index cf1d055..d439635 100644 --- a/src/tools/json/JsonTool.tsx +++ b/src/tools/json/JsonTool.tsx @@ -1,6 +1,6 @@ import { useDeferredValue, useMemo, useState } from 'react' import { useNavigate } from 'react-router' -import { AlertTriangle, Braces, CheckCircle2, GitCompare, Wand2 } from 'lucide-react' +import { AlertTriangle, ArrowUp, Braces, CheckCircle2, GitCompare, ListFilter, Wand2, X } from 'lucide-react' import { ToolFrame } from '@/components/layout/ToolFrame' import { TwoPane } from '@/components/layout/TwoPane' import { Badge } from '@/components/ui/Badge' @@ -35,6 +35,12 @@ import { unescapeJsonString, withSortedKeys, type Indent, + formatPath, + selectPath, + toJqPath, + toJsonPointer, + type PathSegment, + type Selection, } from '@fadeltd/devtools-core/json' import { TreeView } from './TreeView' @@ -57,6 +63,8 @@ interface State { /** When not expanding all: the pointers picked one by one. */ expandPointers: string[] view: View + /** Path the output is narrowed to, as typed; '' shows the whole document. */ + filter: string } const INITIAL: State = { @@ -68,6 +76,7 @@ const INITIAL: State = { expandEmbedded: false, expandPointers: [], view: 'text', + filter: '', } function IssueCard({ issue }: { issue: JsonIssue }) { @@ -109,6 +118,74 @@ function IssueCard({ issue }: { issue: JsonIssue }) { ) } +function FilterBar({ + value, + selection, + onChange, +}: { + value: string + selection: Selection + onChange: (next: string) => void +}) { + const narrowed = selection.ok && selection.path.length > 0 + return ( +
+
+ + onChange(e.target.value)} + placeholder=".items[0] · items[0].id · /items/0" + aria-invalid={!selection.ok} + aria-describedby={selection.ok ? undefined : 'json-filter-error'} + spellCheck={false} + autoCapitalize="off" + autoCorrect="off" + autoComplete="off" + /> + {narrowed && ( + + )} + {value !== '' && ( + + )} +
+ {!selection.ok && ( +

+ {selection.message} +

+ )} +
+ ) +} + const CHIP_LIMIT = 6 function EmbeddedPanel({ @@ -240,6 +317,18 @@ export default function JsonTool() { return deferred.sortKeys ? withSortedKeys(value) : value }, [parsed, embeddedOptions, deferred]) + // Narrowing runs last, on what the user sees: embedded payloads are already + // expanded, so a path can reach inside one. + const selection = useMemo( + () => (shown === undefined ? undefined : selectPath(shown, deferred.filter)), + [shown, deferred.filter], + ) + const focused = selection?.ok === true ? selection : undefined + + function setFilter(filter: string) { + setState((p) => ({ ...p, filter })) + } + const isFieldActive = (pointer: string) => state.expandEmbedded || state.expandPointers.includes(pointer) const anyFieldActive = fields.some((f) => isFieldActive(f.pointer)) @@ -267,12 +356,12 @@ export default function JsonTool() { const r = unescapeJsonString(text) return r.ok ? r.value : '' } - if (shown === undefined) return '' + if (focused === undefined) return '' return mode === 'minify' - ? minifyValue(shown, { sortKeys: false }) - : formatValue(shown, { indent, sortKeys: false }) - }, [shown, deferred]) + ? minifyValue(focused.value, { sortKeys: false }) + : formatValue(focused.value, { indent, sortKeys: false }) + }, [focused, deferred]) const unescapeError = deferred.mode === 'unescape' && deferred.text !== '' @@ -284,7 +373,7 @@ export default function JsonTool() { const isTextMode = state.mode === 'escape' || state.mode === 'unescape' const valid = analysis.flavor === 'json' || analysis.flavor === 'jsonc' - const showTree = state.mode === 'format' && state.view === 'tree' && valid && shown !== undefined + const showTree = state.mode === 'format' && state.view === 'tree' && valid // Only worth running on a document that does not parse. Counts are exact: // each fix sees the previous one's output. @@ -543,6 +632,10 @@ export default function JsonTool() { )} + {!isTextMode && valid && selection !== undefined && ( + + )} + {unescapeError !== null ? (
{unescapeError} @@ -553,10 +646,20 @@ export default function JsonTool() { ))}
- ) : showTree ? ( - + ) : showTree && focused !== undefined ? ( + setFilter(toJqPath(path))} + /> ) : ( - + )} } diff --git a/src/tools/json/TreeView.tsx b/src/tools/json/TreeView.tsx index e683ac2..73764b9 100644 --- a/src/tools/json/TreeView.tsx +++ b/src/tools/json/TreeView.tsx @@ -1,6 +1,6 @@ import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent } from 'react' import { useVirtualizer } from '@tanstack/react-virtual' -import { ChevronRight } from 'lucide-react' +import { ChevronRight, ListFilter } from 'lucide-react' import { Button } from '@/components/ui/Button' import { CopyButton } from '@/components/ui/CopyButton' import { formatCount } from '@/lib/util/bytes' @@ -13,6 +13,7 @@ import { pathOf, toggle, type FlatNode, + type PathSegment, toDotPath, toJsonPointer, toJqPath, @@ -75,7 +76,18 @@ function RowValue({ row }: { row: FlatNode }) { ) } -export function TreeView({ value }: { value: unknown }) { +const ROOT: readonly PathSegment[] = [] + +export function TreeView({ + value, + basePath = ROOT, + onFilter, +}: { + value: unknown + /** Where `value` sits in the whole document, so copied paths stay absolute. */ + basePath?: readonly PathSegment[] + onFilter?: (path: PathSegment[]) => void +}) { const rowHeight = useRowHeight() const [expansion, setExpansion] = useState(() => ({ @@ -111,9 +123,16 @@ export function TreeView({ value }: { value: unknown }) { // row itself, so they are reachable on touch and never hover-only. const selectedPaths = useMemo(() => { if (selectedIndex < 0) return null - const path = pathOf(rows, selectedIndex) - return { pointer: toJsonPointer(path), dot: toDotPath(path), jq: toJqPath(path) } - }, [rows, selectedIndex]) + const relative = pathOf(rows, selectedIndex) + const path = [...basePath, ...relative] + return { + path, + isViewRoot: relative.length === 0, + pointer: toJsonPointer(path), + dot: toDotPath(path), + jq: toJqPath(path), + } + }, [rows, selectedIndex, basePath]) const scrollRef = useRef(null) // The rule guards React Compiler memoisation, and this build does not run the @@ -218,6 +237,17 @@ export function TreeView({ value }: { value: unknown }) { + {onFilter !== undefined && ( + + )} )}