Skip to content

Commit

Permalink
fix: align object's children to keep the consistency of graph illustr…
Browse files Browse the repository at this point in the history
…ation
  • Loading branch information
hanbin9775 authored and hanbinYanolja committed Dec 8, 2022
1 parent debe13f commit e276566
Showing 1 changed file with 41 additions and 20 deletions.
61 changes: 41 additions & 20 deletions src/utils/jsonParser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Node, parseTree } from "jsonc-parser";
import { Node, NodeType, parseTree } from "jsonc-parser";

const calculateSize = (
text: string | [string, string][],
Expand Down Expand Up @@ -74,6 +74,25 @@ export const parser = (jsonStr: string, isFolded = false) => {
];
};

const isPrimitiveOrNullType = (type?: NodeType) => {
return (
type === "boolean" ||
type === "string" ||
type === "number" ||
type === "null"
);
};

const alignChildren = (a: Node, b: Node) => {
if (
isPrimitiveOrNullType(a?.children?.[1]?.type) &&
!isPrimitiveOrNullType(b?.children?.[1]?.type)
) {
return -1;
}
return 0;
};

let parentName: string = "";
let bracketOpen: { id: string; type: string }[] = [];
let objectsFromArray: number[] = [];
Expand Down Expand Up @@ -203,26 +222,28 @@ export const parser = (jsonStr: string, isFolded = false) => {
} else if (parentType === "array") {
objectsFromArray = [...objectsFromArray, objectsFromArrayId++];
}
children.forEach((branch, index, array) => {
if (array[index + 1]) {
traverse(
branch,
type,
bracketOpen[bracketOpen.length - 1]
? bracketOpen[bracketOpen.length - 1].id
: undefined,
array[index + 1].type
);
} else {
traverse(
branch,
type,
bracketOpen[bracketOpen.length - 1]
? bracketOpen[bracketOpen.length - 1].id
: undefined
);
(type === "object" ? children.sort(alignChildren) : children).forEach(
(branch, index, array) => {
if (array[index + 1]) {
traverse(
branch,
type,
bracketOpen[bracketOpen.length - 1]
? bracketOpen[bracketOpen.length - 1].id
: undefined,
array[index + 1].type
);
} else {
traverse(
branch,
type,
bracketOpen[bracketOpen.length - 1]
? bracketOpen[bracketOpen.length - 1].id
: undefined
);
}
}
});
);

if (type !== "property") {
// when children end
Expand Down

0 comments on commit e276566

Please sign in to comment.