Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Json — JSON diff viewer.
*/
interface IJsonProps {
value: unknown;
previous?: unknown;
showUnchangedValues?: boolean;
keyValue?: boolean;
}
type DiffLine = {
key: string;
current?: unknown;
previous?: unknown;
status: 'added' | 'removed' | 'changed' | 'unchanged';
};
function buildDiff(current: unknown, previous: unknown | undefined): DiffLine[] {
if (typeof current !== 'object' || current === null) {
return [
{
key: 'value',
current,
previous,
status:
previous === undefined
? 'added'
: current === previous
? 'unchanged'
: 'changed',
},
];
}
const currentObj = current as Record<string, unknown>;
const previousObj = (previous ?? {}) as Record<string, unknown>;
const allKeys = new Set([...Object.keys(currentObj), ...Object.keys(previousObj)]);
const lines: DiffLine[] = [];
for (const key of allKeys) {
const curr = currentObj[key];
const prev = previousObj[key];
let status: DiffLine['status'] = 'unchanged';
if (!(key in previousObj)) status = 'added';
else if (!(key in currentObj)) status = 'removed';
else if (JSON.stringify(curr) !== JSON.stringify(prev)) status = 'changed';
lines.push({key, current: curr, previous: prev, status});
}
return lines;
}
export function Json({value, previous, showUnchangedValues = true, keyValue}: IJsonProps) {
if (keyValue) {
const diff = buildDiff(value, previous);
return (
<dl className="blong-json blong-json--kv">
{diff
.filter(l => showUnchangedValues || l.status !== 'unchanged')
.map(line => (
<div
key={line.key}
className={`blong-json__line blong-json__line--${line.status}`}
>
<dt className="blong-json__key">{line.key}</dt>
<dd className="blong-json__value">
{line.status === 'changed' && (
<span className="blong-json__prev">
{JSON.stringify(line.previous)}
</span>
)}
<span className="blong-json__curr">
{JSON.stringify(line.current ?? line.previous)}
</span>
</dd>
</div>
))}
</dl>
);
}
return <pre className="blong-json">{JSON.stringify(value, null, 2)}</pre>;
}
|