Selaa lähdekoodia

Merge pull request #268 from hanbin9775/fix/align-object-child

fix: align object's children to keep the consistency of graph illustration
Aykut Saraç 2 vuotta sitten
vanhempi
commit
e488ff524c
1 muutettua tiedostoa jossa 41 lisäystä ja 20 poistoa
  1. 41 20
      src/utils/jsonParser.ts

+ 41 - 20
src/utils/jsonParser.ts

@@ -1,4 +1,4 @@
-import { Node, parseTree } from "jsonc-parser";
+import { Node, NodeType, parseTree } from "jsonc-parser";
 import useGraph from "src/store/useGraph";
 import useStored from "src/store/useStored";
 
@@ -85,6 +85,25 @@ export const parser = (jsonStr: string) => {
       ];
     };
 
+    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[] = [];
@@ -204,26 +223,28 @@ export const parser = (jsonStr: string) => {
         } 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