Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Workflow detail: add on-canvas zoom controls for click/touch navigation and improve controls styling for dark mode. [PR #524](https://github.com/riverqueue/riverui/pull/524).
- Workflow detail: improve default workflow diagram framing for legibility while still allowing manual zoom-out to view the full graph. [PR #524](https://github.com/riverqueue/riverui/pull/524).
- Workflow detail: truncate long workflow names in the header to prevent overflow and add a copy button for the full name. [PR #524](https://github.com/riverqueue/riverui/pull/524).
- JSON viewer: sort keys alphabetically in rendered and copied output for object payloads. [PR #525](https://github.com/riverqueue/riverui/pull/525).

## [v0.15.0] - 2026-02-26

Expand Down
106 changes: 106 additions & 0 deletions src/components/JSONView.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,44 @@ describe("JSONView Component", () => {
expect(screen.getByText(/true/)).toBeInTheDocument();
});

it("renders object keys alphabetically at root and nested levels", () => {
const unsortedData = Object.fromEntries([
["zebra", 3],
[
"alpha",
Object.fromEntries([
["zulu", true],
["bravo", true],
]),
],
["middle", 2],
]);

render(<JSONView data={unsortedData} defaultExpandDepth={2} />);

const alphaKey = screen.getByText(/"alpha"/);
const middleKey = screen.getByText(/"middle"/);
const zebraKey = screen.getByText(/"zebra"/);

const alphaBeforeMiddle =
alphaKey.compareDocumentPosition(middleKey) &
Node.DOCUMENT_POSITION_FOLLOWING;
const middleBeforeZebra =
middleKey.compareDocumentPosition(zebraKey) &
Node.DOCUMENT_POSITION_FOLLOWING;

expect(alphaBeforeMiddle).toBeTruthy();
expect(middleBeforeZebra).toBeTruthy();

const bravoKey = screen.getByText(/"bravo"/);
const zuluKey = screen.getByText(/"zulu"/);
const bravoBeforeZulu =
bravoKey.compareDocumentPosition(zuluKey) &
Node.DOCUMENT_POSITION_FOLLOWING;

expect(bravoBeforeZulu).toBeTruthy();
});

it("renders nested JSON data with collapsed nodes but visible keys by default", () => {
render(<JSONView data={nestedData} defaultExpandDepth={1} />);

Expand Down Expand Up @@ -188,6 +226,74 @@ describe("JSONView Component", () => {
});
});

it("copies alphabetically sorted JSON to clipboard", async () => {
const unsortedData = Object.fromEntries([
["zebra", 3],
[
"alpha",
Object.fromEntries([
["zulu", true],
["bravo", true],
]),
],
["middle", 2],
]);

render(<JSONView copyTitle="Test Data" data={unsortedData} />);

const copyButton = screen.getByTestId("text-copy-button");

await act(async () => {
fireEvent.click(copyButton);
});

expect(navigator.clipboard.writeText).toHaveBeenCalled();
const clipboardCall = (
navigator.clipboard.writeText as unknown as {
mock: { calls: string[][] };
}
).mock.calls[0][0];

const parsed = JSON.parse(clipboardCall) as Record<string, unknown>;
expect(Object.keys(parsed)).toEqual(["alpha", "middle", "zebra"]);
expect(Object.keys(parsed.alpha as Record<string, unknown>)).toEqual([
"bravo",
"zulu",
]);
});

it("preserves __proto__ as data when rendering and copying", async () => {
const dataWithProtoKey = JSON.parse(
'{"zebra":3,"__proto__":{"safe":"value"},"alpha":1}',
) as Record<string, unknown>;

render(<JSONView copyTitle="Test Data" data={dataWithProtoKey} />);

expect(screen.getByText(/"__proto__"/)).toBeInTheDocument();

const copyButton = screen.getByTestId("text-copy-button");

await act(async () => {
fireEvent.click(copyButton);
});

expect(navigator.clipboard.writeText).toHaveBeenCalled();
const clipboardCall = (
navigator.clipboard.writeText as unknown as {
mock: { calls: string[][] };
}
).mock.calls[0][0];

expect(clipboardCall).toContain('"__proto__"');

const parsed = JSON.parse(clipboardCall) as Record<string, unknown>;
expect(Object.prototype.hasOwnProperty.call(parsed, "__proto__")).toBe(
true,
);
expect(parsed["__proto__"]).toEqual({ safe: "value" });
expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype);
});

it("renders null and undefined values", () => {
const data = {
nullValue: null,
Expand Down
67 changes: 65 additions & 2 deletions src/components/JSONView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,12 @@ export default function JSONView({
data,
defaultExpandDepth = 1,
}: JSONViewProps) {
const sortedData = React.useMemo(() => sortObjectKeys(data), [data]);

const jsonContent = (
<>
<JSONNodeRenderer
data={data}
data={sortedData}
defaultExpandDepth={defaultExpandDepth}
depth={0}
isLastItemInParent={true}
Expand All @@ -63,11 +65,20 @@ export default function JSONView({
codeClassName="pl-6"
content={jsonContent}
copyTitle={copyTitle}
rawText={JSON.stringify(data, null, 2)}
rawText={JSON.stringify(sortedData, null, 2)}
/>
);
}

function isPlainObject(value: unknown): value is Record<string, unknown> {
if (value === null || typeof value !== "object") {
return false;
}

const prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.prototype;
}

function JSONNodeRenderer({
data,
defaultExpandDepth,
Expand Down Expand Up @@ -570,3 +581,55 @@ function renderValue(
</Disclosure>
);
}

function sortObjectKeys(value: unknown): unknown {
return sortObjectKeysInternal(value, new WeakMap<object, unknown>());
}

function sortObjectKeysInternal(
value: unknown,
sortedValues: WeakMap<object, unknown>,
): unknown {
if (Array.isArray(value)) {
const cachedArray = sortedValues.get(value);
if (cachedArray) {
return cachedArray;
}

const sortedArray: unknown[] = [];
sortedValues.set(value, sortedArray);
for (const item of value) {
sortedArray.push(sortObjectKeysInternal(item, sortedValues));
}
return sortedArray;
}

if (!isPlainObject(value)) {
return value;
}

const cachedObject = sortedValues.get(value);
if (cachedObject) {
return cachedObject;
}

const sortedObject = Object.create(Object.getPrototypeOf(value)) as Record<
string,
unknown
>;
sortedValues.set(value, sortedObject);

const sortedEntries = Object.entries(value).sort(([leftKey], [rightKey]) =>
leftKey.localeCompare(rightKey),
);
for (const [key, item] of sortedEntries) {
Object.defineProperty(sortedObject, key, {
configurable: true,
enumerable: true,
value: sortObjectKeysInternal(item, sortedValues),
writable: true,
});
}

return sortedObject;
}
Loading