Skip to content

✨ Innovative and open-source visualization application that transforms various data formats, such as JSON, YAML, XML and CSV into interactive graphs.

feat: update diagram layout (#490)

Aykut Saraç001bacb817bb
diff --git a/.env b/.env
index b6a491ec..6a89b747 100644
--- a/.env
+++ b/.env
@@ -1,2 +1,2 @@
-NEXT_PUBLIC_NODE_LIMIT=600
+NEXT_PUBLIC_NODE_LIMIT=800
NEXT_TELEMETRY_DISABLED=1
\ No newline at end of file
diff --git a/.env.development b/.env.development
index a13af921..7d391f7b 100644
--- a/.env.development
+++ b/.env.development
@@ -1 +1 @@
-NEXT_PUBLIC_NODE_LIMIT=1000
+NEXT_PUBLIC_DISABLE_EXTERNAL_MODE=false
\ No newline at end of file
diff --git a/README.md b/README.md
index 721e4345..e1a7f01e 100644
--- a/README.md
+++ b/README.md
@@ -127,6 +127,10 @@ docker compose up
# Go to http://localhost:8888
```
+## Configuration
+
+The supported node limit can be changed by editing the `NEXT_PUBLIC_NODE_LIMIT` value in the `.env` file at the project root.
+
<!-- LICENSE -->
## License
diff --git a/public/assets/editor.webp b/public/assets/editor.webp
index d5f3153c..7f1fd948 100644
Binary files a/public/assets/editor.webp and b/public/assets/editor.webp differ
diff --git a/src/data/example.json b/src/data/example.json
new file mode 100644
index 00000000..f9ae49e9
--- /dev/null
+++ b/src/data/example.json
@@ -0,0 +1,43 @@
+{
+ "fruits": [
+ {
+ "name": "Apple",
+ "color": "#FF0000",
+ "details": {
+ "type": "Pome",
+ "season": "Fall"
+ },
+ "nutrients": {
+ "calories": 52,
+ "fiber": "2.4g",
+ "vitaminC": "4.6mg"
+ }
+ },
+ {
+ "name": "Banana",
+ "color": "#FFFF00",
+ "details": {
+ "type": "Berry",
+ "season": "Year-round"
+ },
+ "nutrients": {
+ "calories": 89,
+ "fiber": "2.6g",
+ "potassium": "358mg"
+ }
+ },
+ {
+ "name": "Orange",
+ "color": "#FFA500",
+ "details": {
+ "type": "Citrus",
+ "season": "Winter"
+ },
+ "nutrients": {
+ "calories": 47,
+ "fiber": "2.4g",
+ "vitaminC": "53.2mg"
+ }
+ }
+ ]
+}
diff --git a/src/features/editor/BottomBar.tsx b/src/features/editor/BottomBar.tsx
index 171720bb..a97d92af 100644
--- a/src/features/editor/BottomBar.tsx
+++ b/src/features/editor/BottomBar.tsx
@@ -1,17 +1,13 @@
import React from "react";
-import Link from "next/link";
-import { Flex, Popover, Text } from "@mantine/core";
+import { Flex, Menu, Popover, Text } from "@mantine/core";
import styled from "styled-components";
import { event as gaEvent } from "nextjs-google-analytics";
import { BiSolidDockLeft } from "react-icons/bi";
-import {
- VscCheck,
- VscError,
- VscFeedback,
- VscRunAll,
- VscSync,
- VscSyncIgnored,
-} from "react-icons/vsc";
+import { FaCrown } from "react-icons/fa6";
+import { IoMdCheckmark } from "react-icons/io";
+import { MdArrowUpward } from "react-icons/md";
+import { VscCheck, VscError, VscRunAll, VscSync, VscSyncIgnored } from "react-icons/vsc";
+import { formats } from "../../enums/file.enum";
import useConfig from "../../store/useConfig";
import useFile from "../../store/useFile";
import useGraph from "./views/GraphView/stores/useGraph";
@@ -85,9 +81,10 @@ export const BottomBar = () => {
const liveTransformEnabled = useConfig(state => state.liveTransformEnabled);
const error = useFile(state => state.error);
const setContents = useFile(state => state.setContents);
- const nodeCount = useGraph(state => state.nodes.length);
const toggleFullscreen = useGraph(state => state.toggleFullscreen);
const fullscreen = useGraph(state => state.fullscreen);
+ const setFormat = useFile(state => state.setFormat);
+ const currentFormat = useFile(state => state.format);
const toggleEditor = () => {
toggleFullscreen(!fullscreen);
@@ -144,17 +141,40 @@ export const BottomBar = () => {
</StyledLeft>
<StyledRight>
- <StyledBottomBarItem>Nodes: {nodeCount}</StyledBottomBarItem>
- <Link
- href="https://github.com/AykutSarac/jsoncrack.com/discussions"
- target="_blank"
- rel="noopener"
- >
- <StyledBottomBarItem>
- <VscFeedback />
- Feedback
- </StyledBottomBarItem>
- </Link>
+ <Menu offset={8}>
+ <Menu.Target>
+ <StyledBottomBarItem>
+ <Flex align="center" gap={2}>
+ <MdArrowUpward />
+ <Text size="xs">{currentFormat?.toUpperCase()}</Text>
+ </Flex>
+ </StyledBottomBarItem>
+ </Menu.Target>
+ <Menu.Dropdown>
+ {formats.map(format => (
+ <Menu.Item
+ key={format.value}
+ fz={12}
+ onClick={() => setFormat(format.value)}
+ rightSection={currentFormat === format.value && <IoMdCheckmark />}
+ >
+ {format.label}
+ </Menu.Item>
+ ))}
+ <Menu.Item
+ fz={12}
+ onClick={() =>
+ window.open(
+ "https://todiagram.com/blog/how-to-create-custom-diagrams-in-todiagram?utm_source=jsoncrack&utm_medium=bottom-bar&utm_campaign=custom-diagram",
+ "_blank"
+ )
+ }
+ rightSection={<FaCrown color="gray" />}
+ >
+ Custom
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
</StyledRight>
</StyledBottomBar>
);
diff --git a/src/features/editor/ExternalMode.tsx b/src/features/editor/ExternalMode.tsx
index c4620b63..ddcbe94b 100644
--- a/src/features/editor/ExternalMode.tsx
+++ b/src/features/editor/ExternalMode.tsx
@@ -1,97 +1,154 @@
import React from "react";
-import { Anchor, Button, Group, Modal, Text } from "@mantine/core";
-import styled from "styled-components";
-import { VscCode } from "react-icons/vsc";
-import { VscArrowRight } from "react-icons/vsc";
-
-const StyledAlert = styled.div`
- position: fixed;
- bottom: 36px;
- right: 10px;
- background: rgba(255, 255, 255, 0.2);
- border-radius: 16px;
- box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
- backdrop-filter: blur(5px);
- -webkit-backdrop-filter: blur(5px);
- border: 1px solid rgba(255, 255, 255, 0.3);
- font-weight: 500;
- overflow: hidden;
-`;
-
-const StyledTitle = styled.div`
- display: flex;
- align-items: center;
- color: ${({ theme }) => theme.TEXT_POSITIVE};
- flex: 1;
- font-weight: 700;
-
- &::after {
- background: ${({ theme }) => theme.TEXT_POSITIVE};
- height: 1px;
-
- content: "";
- -webkit-box-flex: 1;
- -ms-flex: 1 1 auto;
- flex: 1 1 auto;
- margin-left: 4px;
- opacity: 0.6;
- }
-`;
+import { Accordion, Anchor, Code, Flex, FocusTrap, Group, Modal, Text } from "@mantine/core";
const ExternalMode = () => {
const [isExternal, setExternal] = React.useState(false);
- const [isOpen, setOpen] = React.useState(false);
React.useEffect(() => {
- if (typeof window !== "undefined") {
- if (window.location.pathname.includes("widget")) return setExternal(false);
- if (window.location.host !== "jsoncrack.com") return setExternal(true);
- return setExternal(false);
+ if (process.env.NEXT_PUBLIC_DISABLE_EXTERNAL_MODE === "false") {
+ if (typeof window !== "undefined") {
+ if (window.location.pathname.includes("widget")) return setExternal(false);
+ if (window.location.host !== "jsoncrack.com") return setExternal(true);
+ return setExternal(false);
+ }
}
}, []);
- const closeModal = () => setOpen(false);
-
if (!isExternal) return null;
return (
- <StyledAlert>
- <Button
- onClick={() => setOpen(true)}
- color="red"
- variant="subtle"
- leftSection={<VscCode size="1.2rem" />}
- >
- External Host
- </Button>
- <Modal title="External Host of JSON Crack" opened={isOpen} onClose={closeModal} centered>
- <Group>
- <StyledTitle>Dear valued user,</StyledTitle>
- <Text>
- We would like to inform you that you are presently utilizing the external release of the{" "}
- <Anchor href="https://jsoncrack.com">JSON Crack</Anchor>. Your continued support is
- crucial in sustaining and improving our services.
- <br />
- <br />
- We kindly encourage you to consider upgrading to the premium version, which not only
- enhances your experience but also contributes to the ongoing development of JSON Crack.
- </Text>
- </Group>
- <Group pt="lg" justify="right">
- <Button
- onClick={closeModal}
- component="a"
- href="https://jsoncrack.com"
- target="_blank"
- variant="outline"
- color="red"
- rightSection={<VscArrowRight />}
- >
- JSON Crack
- </Button>
- </Group>
- </Modal>
- </StyledAlert>
+ <Modal
+ title="Thanks for using JSON Crack"
+ opened={isExternal}
+ onClose={() => setExternal(false)}
+ centered
+ size="lg"
+ >
+ <FocusTrap.InitialFocus />
+ <Group>
+ <Accordion variant="separated" w="100%">
+ <Accordion.Item value="1">
+ <Accordion.Control>How can I change the file size limit?</Accordion.Control>
+ <Accordion.Panel>
+ The main reason for the file size limit is to prevent performance issues, not to push
+ you to upgrade. You can increase the limit by setting{" "}
+ <Code>NEXT_PUBLIC_NODE_LIMIT</Code> in your <Code>.env</Code> file.
+ <br />
+ <br />
+ If you&apos;d like to work with even larger files and unlock additional features, you
+ can upgrade to the{" "}
+ <Anchor
+ href="https://todiagram.com?utm_source=jsoncrack&utm_medium=external-mode"
+ rel="noopener"
+ target="_blank"
+ >
+ Pro
+ </Anchor>{" "}
+ version.
+ </Accordion.Panel>
+ </Accordion.Item>
+ <Accordion.Item value="2">
+ <Accordion.Control>How can I stop this dialog from appearing?</Accordion.Control>
+ <Accordion.Panel>
+ You can disable this dialog by setting <Code>NEXT_PUBLIC_DISABLE_EXTERNAL_MODE</Code>{" "}
+ to <Code>true</Code> in your <Code>.env.development</Code> file.
+ <br />
+ <br />
+ If you want to re-enable it, simply remove or set the value to <Code>false</Code>.
+ </Accordion.Panel>
+ </Accordion.Item>
+ <Accordion.Item value="3">
+ <Accordion.Control>What are the license terms?</Accordion.Control>
+ <Accordion.Panel>
+ Read the full license terms on{" "}
+ <Anchor
+ href="https://github.com/AykutSarac/jsoncrack.com/blob/main/LICENSE.md"
+ rel="noopener"
+ target="_blank"
+ >
+ GitHub
+ </Anchor>
+ .
+ </Accordion.Panel>
+ </Accordion.Item>
+ <Accordion.Item value="4">
+ <Accordion.Control>How do I report a bug or request a feature?</Accordion.Control>
+ <Accordion.Panel>
+ You can report bugs or request features by opening an issue on our{" "}
+ <Anchor
+ href="https://github.com/AykutSarac/jsoncrack.com/issues"
+ rel="noopener"
+ target="_blank"
+ >
+ GitHub Issues page
+ </Anchor>
+ .
+ <br />
+ <br />
+ Please provide as much detail as possible to help us address your feedback quickly.
+ </Accordion.Panel>
+ </Accordion.Item>
+ <Accordion.Item value="5">
+ <Accordion.Control>How do I contribute to the project?</Accordion.Control>
+ <Accordion.Panel>
+ We welcome contributions! Visit our{" "}
+ <Anchor
+ href="https://github.com/AykutSarac/jsoncrack.com"
+ rel="noopener"
+ target="_blank"
+ >
+ GitHub repository
+ </Anchor>{" "}
+ and read the{" "}
+ <Anchor
+ href="https://github.com/AykutSarac/jsoncrack.com/blob/main/CONTRIBUTING.md"
+ rel="noopener"
+ target="_blank"
+ >
+ contributing guide
+ </Anchor>{" "}
+ to get started.
+ </Accordion.Panel>
+ </Accordion.Item>
+ <Accordion.Item value="6">
+ <Accordion.Control>
+ What is the difference between JSON Crack and ToDiagram?
+ </Accordion.Control>
+ <Accordion.Panel>
+ JSON Crack is a free and open-source tool for visualizing JSON data. ToDiagram is the
+ professional version that offers advanced features, higher limits, and the ability to
+ edit data directly from diagrams. You can learn more or upgrade at{" "}
+ <Anchor
+ href="https://todiagram.com?utm_source=jsoncrack&utm_medium=external-mode"
+ rel="noopener"
+ target="_blank"
+ >
+ todiagram.com
+ </Anchor>
+ .
+ </Accordion.Panel>
+ </Accordion.Item>
+ </Accordion>
+ </Group>
+ <Flex justify="center" align="center" gap="sm" mt="md">
+ <Anchor
+ href="https://github.com/AykutSarac/jsoncrack.com"
+ rel="noopener"
+ target="_blank"
+ fz="sm"
+ >
+ GitHub
+ </Anchor>
+ <Text c="dimmed">•</Text>
+ <Anchor href="https://todiagram.com" rel="noopener" target="_blank" fz="sm">
+ ToDiagram
+ </Anchor>
+ <Text c="dimmed">•</Text>
+ <Anchor href="https://x.com/aykutsarach" rel="noopener" target="_blank" fz="sm">
+ Aykut Saraç (@aykutsarach)
+ </Anchor>
+ </Flex>
+ </Modal>
);
};
diff --git a/src/features/editor/Toolbar/SearchInput.tsx b/src/features/editor/Toolbar/SearchInput.tsx
index 054fb8eb..cbda77fc 100644
--- a/src/features/editor/Toolbar/SearchInput.tsx
+++ b/src/features/editor/Toolbar/SearchInput.tsx
@@ -1,11 +1,15 @@
import React from "react";
import { Flex, Text, TextInput } from "@mantine/core";
import { getHotkeyHandler } from "@mantine/hooks";
+import { useOs } from "@mantine/hooks";
import { AiOutlineSearch } from "react-icons/ai";
import { useFocusNode } from "../../../hooks/useFocusNode";
export const SearchInput = () => {
const [searchValue, setValue, skip, nodeCount, currentNode] = useFocusNode();
+ const os = useOs();
+
+ const coreKey = os === "macos" ? "⌘" : "Ctrl";
return (
<TextInput
@@ -16,7 +20,7 @@ export const SearchInput = () => {
w={180}
value={searchValue}
onChange={e => setValue(e.currentTarget.value)}
- placeholder="Search Node"
+ placeholder={`Search Node (${coreKey} + F)`}
autoComplete="off"
autoCorrect="off"
onKeyDown={getHotkeyHandler([["Enter", skip]])}
diff --git a/src/features/editor/Toolbar/index.tsx b/src/features/editor/Toolbar/index.tsx
index 09dfee37..9f617964 100644
--- a/src/features/editor/Toolbar/index.tsx
+++ b/src/features/editor/Toolbar/index.tsx
@@ -1,13 +1,13 @@
import React from "react";
import Link from "next/link";
-import { Flex, Group, Select, Button } from "@mantine/core";
+import { Flex, Group, Button } from "@mantine/core";
import styled from "styled-components";
import toast from "react-hot-toast";
import { AiOutlineFullscreen } from "react-icons/ai";
-import { FaFireFlameCurved, FaGithub } from "react-icons/fa6";
-import { type FileFormat, formats } from "../../../enums/file.enum";
+import { FaCrown, FaGithub } from "react-icons/fa6";
+import { LuLink } from "react-icons/lu";
import { JSONCrackLogo } from "../../../layout/JsonCrackLogo";
-import useFile from "../../../store/useFile";
+import { useModal } from "../../../store/useModal";
import { FileMenu } from "./FileMenu";
import { ToolsMenu } from "./ToolsMenu";
import { ViewMenu } from "./ViewMenu";
@@ -43,8 +43,7 @@ function fullscreenBrowser() {
}
export const Toolbar = () => {
- const setFormat = useFile(state => state.setFormat);
- const format = useFile(state => state.format);
+ const setVisible = useModal(state => state.setVisible);
return (
<StyledTools>
@@ -54,37 +53,35 @@ export const Toolbar = () => {
<JSONCrackLogo fontSize="0.8rem" hideLogo />
</Flex>
</StyledToolElement>
- <Select
- defaultValue="json"
- size="xs"
- value={format}
- onChange={e => setFormat(e as FileFormat)}
- miw={80}
- w={120}
- data={formats}
- allowDeselect={false}
- />
-
<FileMenu />
<ViewMenu />
<ToolsMenu />
- </Group>
- <Group gap="xs" justify="right" w="100%" style={{ flexWrap: "nowrap" }}>
<Button
component={Link}
href="https://todiagram.com/editor?utm_source=jsoncrack&utm_medium=toolbar"
target="_blank"
rel="noopener"
autoContrast
- color="green"
- variant="outline"
- c="bright"
- size="compact-sm"
+ color="yellow"
+ variant="light"
+ size="compact-xs"
fz="12"
fw="600"
- leftSection={<FaFireFlameCurved />}
+ leftSection={<FaCrown />}
+ >
+ Try Pro
+ </Button>
+ </Group>
+ <Group gap="xs" justify="right" w="100%" style={{ flexWrap: "nowrap" }}>
+ <Button
+ color="gray"
+ fz="12"
+ leftSection={<LuLink />}
+ size="compact-sm"
+ variant="default"
+ onClick={() => setVisible("UpgradeModal", true)}
>
- NEW! JSON Crack v2.0
+ Share
</Button>
<Link href="https://github.com/AykutSarac/jsoncrack.com" rel="noopener" target="_blank">
<StyledToolElement title="GitHub">
diff --git a/src/features/editor/views/GraphView/CustomEdge/index.tsx b/src/features/editor/views/GraphView/CustomEdge/index.tsx
index a49c2e39..69de00db 100644
--- a/src/features/editor/views/GraphView/CustomEdge/index.tsx
+++ b/src/features/editor/views/GraphView/CustomEdge/index.tsx
@@ -7,13 +7,16 @@ import useGraph from "../stores/useGraph";
const CustomEdgeWrapper = (props: EdgeProps) => {
const colorScheme = useComputedColorScheme();
const viewPort = useGraph(state => state.viewPort);
- const targetNodeId = props.id.split("-")[props.id.split("-").length - 1];
+ const edges = useGraph(state => state.edges);
const [hovered, setHovered] = React.useState(false);
const handeClick = () => {
- const targetNode = document.querySelector(`[data-id="node-${targetNodeId}"]`) as HTMLElement;
- if (targetNode && targetNode.parentElement) {
- viewPort?.camera.centerFitElementIntoView(targetNode.parentElement, {
+ const targetNodeId = edges.find(edge => edge.id === props.properties?.id)?.to;
+ const targetNodeDom = document.querySelector(
+ `[data-id$="node-${targetNodeId}"]`
+ ) as HTMLElement;
+ if (targetNodeDom && targetNodeDom.parentElement) {
+ viewPort?.camera.centerFitElementIntoView(targetNodeDom.parentElement, {
elementExtraMarginForZoom: 150,
});
}
diff --git a/src/features/editor/views/GraphView/CustomNode/ObjectNode.tsx b/src/features/editor/views/GraphView/CustomNode/ObjectNode.tsx
index 5c08987d..e13a495b 100644
--- a/src/features/editor/views/GraphView/CustomNode/ObjectNode.tsx
+++ b/src/features/editor/views/GraphView/CustomNode/ObjectNode.tsx
@@ -1,29 +1,30 @@
import React from "react";
import type { CustomNodeProps } from ".";
import { NODE_DIMENSIONS } from "../../../../../constants/graph";
+import type { NodeData } from "../../../../../types/graph";
import { TextRenderer } from "./TextRenderer";
import * as Styled from "./styles";
-type Value = [string, string];
-
type RowProps = {
- val: Value;
+ row: NodeData["text"][number];
x: number;
y: number;
index: number;
};
-const Row = ({ val, x, y, index }: RowProps) => {
- const key = JSON.stringify(val);
- const rowKey = JSON.stringify(val[0]).replaceAll('"', "");
- const rowValue = JSON.stringify(val[1]);
-
+const Row = ({ row, x, y, index }: RowProps) => {
const rowPosition = index * NODE_DIMENSIONS.ROW_HEIGHT;
+ const getRowText = () => {
+ if (row.type === "object") return `{${row.childrenCount ?? 0} keys}`;
+ if (row.type === "array") return `[${row.childrenCount ?? 0} items]`;
+ return row.value;
+ };
+
return (
- <Styled.StyledRow $value={rowValue} data-key={key} data-x={x} data-y={y + rowPosition}>
- <Styled.StyledKey $type="object">{rowKey}: </Styled.StyledKey>
- <TextRenderer>{rowValue}</TextRenderer>
+ <Styled.StyledRow $value={row.value} data-key={row.key} data-x={x} data-y={y + rowPosition}>
+ <Styled.StyledKey $type="object">{row.key}: </Styled.StyledKey>
+ <TextRenderer>{getRowText()}</TextRenderer>
</Styled.StyledRow>
);
};
@@ -37,14 +38,17 @@ const Node = ({ node, x, y }: CustomNodeProps) => (
y={0}
$isObject
>
- {(node.text as Value[]).map((val, idx) => (
- <Row val={val} index={idx} x={x} y={y} key={idx} />
+ {node.text.map((row, index) => (
+ <Row key={`${node.id}-${index}`} row={row} x={x} y={y} index={index} />
))}
</Styled.StyledForeignObject>
);
function propsAreEqual(prev: CustomNodeProps, next: CustomNodeProps) {
- return String(prev.node.text) === String(next.node.text) && prev.node.width === next.node.width;
+ return (
+ JSON.stringify(prev.node.text) === JSON.stringify(next.node.text) &&
+ prev.node.width === next.node.width
+ );
}
export const ObjectNode = React.memo(Node, propsAreEqual);
diff --git a/src/features/editor/views/GraphView/CustomNode/TextNode.tsx b/src/features/editor/views/GraphView/CustomNode/TextNode.tsx
index 0f34bc6f..718ced9d 100644
--- a/src/features/editor/views/GraphView/CustomNode/TextNode.tsx
+++ b/src/features/editor/views/GraphView/CustomNode/TextNode.tsx
@@ -1,39 +1,19 @@
-import React, { useMemo } from "react";
+import React from "react";
import styled from "styled-components";
-import { MdLink, MdLinkOff } from "react-icons/md";
import type { CustomNodeProps } from ".";
-import useToggleHide from "../../../../../hooks/useToggleHide";
import useConfig from "../../../../../store/useConfig";
import { isContentImage } from "../lib/utils/calculateNodeSize";
-import useGraph from "../stores/useGraph";
import { TextRenderer } from "./TextRenderer";
import * as Styled from "./styles";
-const StyledExpand = styled.button`
- pointer-events: all;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- color: ${({ theme }) => theme.TEXT_NORMAL};
- background: rgba(0, 0, 0, 0.1);
- height: 100%;
- width: 36px;
- border-left: 1px solid ${({ theme }) => theme.BACKGROUND_MODIFIER_ACCENT};
-
- &:hover {
- background-image: linear-gradient(rgba(0, 0, 0, 0.1) 0 0);
- }
-`;
-
-const StyledTextNodeWrapper = styled.span<{ $hasCollapse: boolean; $isParent: boolean }>`
+const StyledTextNodeWrapper = styled.span<{ $isParent: boolean }>`
display: flex;
- justify-content: ${({ $hasCollapse, $isParent }) =>
- $hasCollapse ? "space-between" : $isParent ? "center" : "flex-start"};
+ justify-content: ${({ $isParent }) => ($isParent ? "center" : "flex-start")};
align-items: center;
height: 100%;
width: 100%;
overflow: hidden;
- padding: ${({ $hasCollapse }) => ($hasCollapse ? "0" : "0 10px")};
+ padding: 0 10px;
`;
const StyledImageWrapper = styled.div`
@@ -46,37 +26,11 @@ const StyledImage = styled.img`
background: ${({ theme }) => theme.BACKGROUND_MODIFIER_ACCENT};
`;
-const Node = ({ node, x, y, hasCollapse = false }: CustomNodeProps) => {
- const {
- id,
- text,
- width,
- height,
- data: { isParent, childrenCount, type },
- } = node;
- const { validateHiddenNodes } = useToggleHide();
- const collapseButtonVisible = useConfig(state => state.collapseButtonVisible);
- const childrenCountVisible = useConfig(state => state.childrenCountVisible);
+const Node = ({ node, x, y }: CustomNodeProps) => {
+ const { text, width, height } = node;
const imagePreviewEnabled = useConfig(state => state.imagePreviewEnabled);
- const expandNodes = useGraph(state => state.expandNodes);
- const collapseNodes = useGraph(state => state.collapseNodes);
- const isExpanded = useGraph(state => state.collapsedParents.includes(id));
- const isImage = imagePreviewEnabled && isContentImage(text as string);
- const value = JSON.stringify(text).replaceAll('"', "");
-
- const handleExpand = (e: React.MouseEvent<HTMLButtonElement>) => {
- e.stopPropagation();
-
- if (!isExpanded) collapseNodes(id);
- else expandNodes(id);
- validateHiddenNodes();
- };
-
- const childrenCountText = useMemo(() => {
- if (type === "object") return `{${childrenCount}}`;
- if (type === "array") return `[${childrenCount}]`;
- return "";
- }, [childrenCount, type]);
+ const isImage = imagePreviewEnabled && isContentImage(JSON.stringify(text[0].value));
+ const value = text[0].value;
return (
<Styled.StyledForeignObject
@@ -88,27 +42,18 @@ const Node = ({ node, x, y, hasCollapse = false }: CustomNodeProps) => {
>
{isImage ? (
<StyledImageWrapper>
- <StyledImage src={text as string} width="70" height="70" loading="lazy" />
+ <StyledImage src={JSON.stringify(text[0].value)} width="70" height="70" loading="lazy" />
</StyledImageWrapper>
) : (
<StyledTextNodeWrapper
data-x={x}
data-y={y}
data-key={JSON.stringify(text)}
- $hasCollapse={isParent && collapseButtonVisible}
- $isParent={isParent}
+ $isParent={false}
>
- <Styled.StyledKey $value={value} $parent={isParent} $type={type}>
+ <Styled.StyledKey $value={value} $type={typeof text[0].value}>
<TextRenderer>{value}</TextRenderer>
</Styled.StyledKey>
- {isParent && childrenCount > 0 && childrenCountVisible && (
- <Styled.StyledChildrenCount>{childrenCountText}</Styled.StyledChildrenCount>
- )}
- {isParent && hasCollapse && collapseButtonVisible && (
- <StyledExpand aria-label="Expand" onClick={handleExpand}>
- {isExpanded ? <MdLinkOff size={18} /> : <MdLink size={18} />}
- </StyledExpand>
- )}
</StyledTextNodeWrapper>
)}
</Styled.StyledForeignObject>
@@ -116,11 +61,7 @@ const Node = ({ node, x, y, hasCollapse = false }: CustomNodeProps) => {
};
function propsAreEqual(prev: CustomNodeProps, next: CustomNodeProps) {
- return (
- prev.node.text === next.node.text &&
- prev.node.width === next.node.width &&
- prev.node.data.childrenCount === next.node.data.childrenCount
- );
+ return prev.node.text === next.node.text && prev.node.width === next.node.width;
}
export const TextNode = React.memo(Node, propsAreEqual);
diff --git a/src/features/editor/views/GraphView/CustomNode/TextRenderer.tsx b/src/features/editor/views/GraphView/CustomNode/TextRenderer.tsx
index 8ecb58e0..bff74ea8 100644
--- a/src/features/editor/views/GraphView/CustomNode/TextRenderer.tsx
+++ b/src/features/editor/views/GraphView/CustomNode/TextRenderer.tsx
@@ -14,7 +14,7 @@ const isURL = (word: string) => {
const urlPattern =
/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;
- return word.match(urlPattern);
+ return word?.match(urlPattern);
};
const Linkify = (text: string) => {
@@ -30,24 +30,19 @@ const Linkify = (text: string) => {
return <span dangerouslySetInnerHTML={{ __html: html }} />;
};
-interface TextRendererProps {
- children: string;
-}
-
-export const TextRenderer = ({ children }: TextRendererProps) => {
- const text = children?.replaceAll('"', "");
+export const TextRenderer = ({ children }: React.PropsWithChildren) => {
+ if (typeof children === "string" && isURL(children)) return Linkify(children);
- if (isURL(text)) return Linkify(text);
-
- if (isColorFormat(text)) {
+ if (typeof children === "string" && isColorFormat(children)) {
return (
<StyledRow>
- <ColorSwatch size={12} radius={4} mr={4} color={text} />
- {text}
+ <ColorSwatch size={12} radius={4} mr={4} color={children} />
+ {children}
</StyledRow>
);
}
- return <>{children}</>;
+
+ return <>{`${children}`}</>;
};
function isColorFormat(colorString: string) {
diff --git a/src/features/editor/views/GraphView/CustomNode/index.tsx b/src/features/editor/views/GraphView/CustomNode/index.tsx
index d91da4b4..ea3ac6be 100644
--- a/src/features/editor/views/GraphView/CustomNode/index.tsx
+++ b/src/features/editor/views/GraphView/CustomNode/index.tsx
@@ -15,13 +15,7 @@ export interface CustomNodeProps {
hasCollapse?: boolean;
}
-const rootProps = {
- rx: 50,
- ry: 50,
-};
-
-const CustomNodeWrapper = (nodeProps: NodeProps<NodeData["data"]>) => {
- const data = nodeProps.properties.data;
+const CustomNodeWrapper = (nodeProps: NodeProps<NodeData>) => {
const setSelectedNode = useGraph(state => state.setSelectedNode);
const setVisible = useModal(state => state.setVisible);
const colorScheme = useComputedColorScheme();
@@ -37,7 +31,6 @@ const CustomNodeWrapper = (nodeProps: NodeProps<NodeData["data"]>) => {
return (
<Node
{...nodeProps}
- {...(data?.isEmpty && rootProps)}
onClick={handleNodeClick as any}
animated={false}
label={null as any}
@@ -54,12 +47,10 @@ const CustomNodeWrapper = (nodeProps: NodeProps<NodeData["data"]>) => {
}}
>
{({ node, x, y }) => {
- if (Array.isArray(nodeProps.properties.text)) {
- if (data?.isEmpty) return null;
- return <ObjectNode node={node as NodeData} x={x} y={y} />;
- }
+ const hasKey = nodeProps.properties.text[0].key;
+ if (!hasKey) return <TextNode node={nodeProps.properties as NodeData} x={x} y={y} />;
- return <TextNode node={node as NodeData} hasCollapse={!!data?.childrenCount} x={x} y={y} />;
+ return <ObjectNode node={node as NodeData} x={x} y={y} />;
}}
</Node>
);
diff --git a/src/features/editor/views/GraphView/CustomNode/styles.tsx b/src/features/editor/views/GraphView/CustomNode/styles.tsx
index d4a012b6..4ae64f51 100644
--- a/src/features/editor/views/GraphView/CustomNode/styles.tsx
+++ b/src/features/editor/views/GraphView/CustomNode/styles.tsx
@@ -6,24 +6,15 @@ import { NODE_DIMENSIONS } from "../../../../../constants/graph";
type TextColorFn = {
theme: DefaultTheme;
$type?: string;
- $value?: string;
- $parent?: boolean;
+ $value?: string | number | null | boolean;
};
-function getTextColor({ $value, $type, $parent, theme }: TextColorFn) {
- // per type
- if ($parent && $type === "array") return theme.NODE_COLORS.PARENT_ARR;
- if ($parent && $type === "object") return theme.NODE_COLORS.PARENT_OBJ;
+function getTextColor({ $value, $type, theme }: TextColorFn) {
+ if ($value === null) return theme.NODE_COLORS.NULL;
if ($type === "object") return theme.NODE_COLORS.NODE_KEY;
- if ($type === "array") return theme.NODE_COLORS.NODE_VALUE;
-
- // per value
- if ($value && !Number.isNaN(+$value)) return theme.NODE_COLORS.INTEGER;
- if ($value === "true") return theme.NODE_COLORS.BOOL.TRUE;
- if ($value === "false") return theme.NODE_COLORS.BOOL.FALSE;
- if ($value === "null") return theme.NODE_COLORS.NULL;
-
- // default
+ if ($type === "number") return theme.NODE_COLORS.INTEGER;
+ if ($value === true) return theme.NODE_COLORS.BOOL.TRUE;
+ if ($value === false) return theme.NODE_COLORS.BOOL.FALSE;
return theme.NODE_COLORS.NODE_VALUE;
}
@@ -43,7 +34,7 @@ export const StyledForeignObject = styled.foreignObject<{ $isObject?: boolean }>
&.searched {
background: rgba(27, 255, 0, 0.1);
- border: 2px solid ${({ theme }) => theme.TEXT_POSITIVE};
+ border: 1px solid ${({ theme }) => theme.TEXT_POSITIVE};
border-radius: 2px;
box-sizing: border-box;
}
@@ -64,27 +55,29 @@ export const StyledForeignObject = styled.foreignObject<{ $isObject?: boolean }>
}
`;
-export const StyledKey = styled.span<{ $parent?: boolean; $type: string; $value?: string }>`
- display: ${({ $parent }) => ($parent ? "flex" : "inline")};
+export const StyledKey = styled.span<{
+ $type: TextColorFn["$type"];
+ $value?: TextColorFn["$value"];
+}>`
+ display: inline;
align-items: center;
- justify-content: center; // Always center for parent nodes
+ justify-content: center;
flex: 1;
min-width: 0;
- height: ${({ $parent }) => ($parent ? `${NODE_DIMENSIONS.PARENT_HEIGHT}px` : "auto")};
- line-height: ${({ $parent }) => ($parent ? `${NODE_DIMENSIONS.PARENT_HEIGHT}px` : "inherit")};
+ height: auto;
+ line-height: inherit;
padding: 0; // Remove padding
- color: ${({ theme, $type, $parent = false, $value = "" }) =>
- getTextColor({ $parent, $type, $value, theme })};
+ color: ${({ theme, $type, $value = "" }) => getTextColor({ $value, $type, theme })};
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
-export const StyledRow = styled.span<{ $value: string }>`
+export const StyledRow = styled.span<{ $value: TextColorFn["$value"] }>`
padding: 3px 10px;
height: ${NODE_DIMENSIONS.ROW_HEIGHT}px;
line-height: 18px;
- color: ${({ theme, $value }) => getTextColor({ $value, theme })};
+ color: ${({ theme, $value }) => getTextColor({ $value, theme, $type: typeof $value })};
display: block;
overflow: hidden;
text-overflow: ellipsis;
diff --git a/src/features/editor/views/GraphView/OptionsMenu.tsx b/src/features/editor/views/GraphView/OptionsMenu.tsx
index 1db75768..96171d2e 100644
--- a/src/features/editor/views/GraphView/OptionsMenu.tsx
+++ b/src/features/editor/views/GraphView/OptionsMenu.tsx
@@ -6,8 +6,6 @@ import { event as gaEvent } from "nextjs-google-analytics";
import { BsCheck2 } from "react-icons/bs";
import { LuChevronRight, LuImageDown, LuMenu } from "react-icons/lu";
import { TiFlowMerge } from "react-icons/ti";
-import { VscExpandAll, VscCollapseAll } from "react-icons/vsc";
-import useToggleHide from "../../../../hooks/useToggleHide";
import useConfig from "../../../../store/useConfig";
import { useModal } from "../../../../store/useModal";
import type { LayoutDirection } from "../../../../types/graph";
@@ -33,21 +31,13 @@ const rotateLayout = (direction: LayoutDirection) => {
export const OptionsMenu = () => {
const toggleGestures = useConfig(state => state.toggleGestures);
- const toggleChildrenCount = useConfig(state => state.toggleChildrenCount);
const toggleRulers = useConfig(state => state.toggleRulers);
- const toggleCollapseButton = useConfig(state => state.toggleCollapseButton);
const toggleImagePreview = useConfig(state => state.toggleImagePreview);
const gesturesEnabled = useConfig(state => state.gesturesEnabled);
- const childrenCountVisible = useConfig(state => state.childrenCountVisible);
const rulersEnabled = useConfig(state => state.rulersEnabled);
- const collapseButtonVisible = useConfig(state => state.collapseButtonVisible);
const imagePreviewEnabled = useConfig(state => state.imagePreviewEnabled);
- const { validateHiddenNodes } = useToggleHide();
const setDirection = useGraph(state => state.setDirection);
const direction = useGraph(state => state.direction);
- const expandGraph = useGraph(state => state.expandGraph);
- const collapseGraph = useGraph(state => state.collapseGraph);
- const graphCollapsed = useGraph(state => state.graphCollapsed);
const setVisible = useModal(state => state.setVisible);
const [coreKey, setCoreKey] = React.useState("CTRL");
@@ -56,17 +46,9 @@ export const OptionsMenu = () => {
if (setDirection) setDirection(nextDirection);
};
- const toggleExpandCollapseGraph = () => {
- if (graphCollapsed) expandGraph();
- else collapseGraph();
-
- validateHiddenNodes();
- };
-
useHotkeys(
[
["mod+shift+d", toggleDirection],
- ["mod+shift+c", toggleExpandCollapseGraph],
[
"mod+f",
() => {
@@ -129,21 +111,6 @@ export const OptionsMenu = () => {
>
Rotate Layout
</Menu.Item>
- <Menu.Item
- fz={12}
- onClick={() => {
- toggleExpandCollapseGraph();
- gaEvent("expand_collapse_graph", { label: graphCollapsed ? "expand" : "collapse" });
- }}
- leftSection={graphCollapsed ? <VscExpandAll /> : <VscCollapseAll />}
- rightSection={
- <Text ml="md" fz={10} c="dimmed">
- {coreKey} Shift C
- </Text>
- }
- >
- {graphCollapsed ? "Expand" : "Collapse"} Graph
- </Menu.Item>
<Menu.Divider />
<Menu position="right" trigger="hover" offset={0}>
<Menu.Target>
@@ -178,15 +145,6 @@ export const OptionsMenu = () => {
>
<Text size="xs">Trackpad Gestures</Text>
</Menu.Item>
- <Menu.Item
- leftSection={<BsCheck2 opacity={childrenCountVisible ? 100 : 0} />}
- onClick={() => {
- toggleChildrenCount(!childrenCountVisible);
- gaEvent("toggle_children_count", { label: childrenCountVisible ? "on" : "off" });
- }}
- >
- <Text size="xs">Item Count</Text>
- </Menu.Item>
<Menu.Item
leftSection={<BsCheck2 opacity={imagePreviewEnabled ? 100 : 0} />}
onClick={() => {
@@ -196,17 +154,6 @@ export const OptionsMenu = () => {
>
<Text size="xs">Image Link Preview</Text>
</Menu.Item>
- <Menu.Item
- leftSection={<BsCheck2 opacity={collapseButtonVisible ? 100 : 0} />}
- onClick={() => {
- toggleCollapseButton(!collapseButtonVisible);
- gaEvent("toggle_expand_collapse", {
- label: collapseButtonVisible ? "on" : "off",
- });
- }}
- >
- <Text size="xs">Show Expand/Collapse</Text>
- </Menu.Item>
</Menu.Dropdown>
</Menu>
</Menu.Dropdown>
diff --git a/src/features/editor/views/GraphView/ZoomControl.tsx b/src/features/editor/views/GraphView/ZoomControl.tsx
index 47eea3d7..12e34f7f 100644
--- a/src/features/editor/views/GraphView/ZoomControl.tsx
+++ b/src/features/editor/views/GraphView/ZoomControl.tsx
@@ -1,5 +1,5 @@
import React from "react";
-import { ActionIcon, Flex } from "@mantine/core";
+import { ActionIcon, Flex, Tooltip, Text } from "@mantine/core";
import { useHotkeys } from "@mantine/hooks";
import { event as gaEvent } from "nextjs-google-analytics";
import { LuFocus, LuMaximize, LuMinus, LuPlus } from "react-icons/lu";
@@ -14,9 +14,10 @@ export const ZoomControl = () => {
useHotkeys(
[
- ["mod+[plus]", () => zoomIn],
- ["mod+[minus]", () => zoomOut],
- ["shift+Digit1", centerView],
+ ["mod+[plus]", () => zoomIn, { usePhysicalKeys: true }],
+ ["mod+[minus]", () => zoomOut, { usePhysicalKeys: true }],
+ ["shift+Digit1", centerView, { usePhysicalKeys: true }],
+ ["shift+Digit2", focusFirstNode, { usePhysicalKeys: true }],
],
[]
);
@@ -34,28 +35,52 @@ export const ZoomControl = () => {
}}
>
<ActionIcon.Group borderWidth={0}>
- <ActionIcon
- size="lg"
- variant="light"
- color="gray"
- onClick={() => {
- focusFirstNode();
- gaEvent("focus_first_node");
- }}
+ <Tooltip
+ label={
+ <Flex fz="xs" gap="md">
+ <Text fz="xs">Center first item</Text>
+ <Text fz="xs" c="dimmed">
+ ⇧ 2
+ </Text>
+ </Flex>
+ }
+ withArrow
>
- <LuFocus />
- </ActionIcon>
- <ActionIcon
- size="lg"
- variant="light"
- color="gray"
- onClick={() => {
- centerView();
- gaEvent("center_view");
- }}
+ <ActionIcon
+ size="lg"
+ variant="light"
+ color="gray"
+ onClick={() => {
+ focusFirstNode();
+ gaEvent("focus_first_node");
+ }}
+ >
+ <LuFocus />
+ </ActionIcon>
+ </Tooltip>
+ <Tooltip
+ label={
+ <Flex fz="xs" gap="md">
+ <Text fz="xs">Fit to center</Text>
+ <Text fz="xs" c="dimmed">
+ ⇧ 1
+ </Text>
+ </Flex>
+ }
+ withArrow
>
- <LuMaximize />
- </ActionIcon>
+ <ActionIcon
+ size="lg"
+ variant="light"
+ color="gray"
+ onClick={() => {
+ centerView();
+ gaEvent("center_view");
+ }}
+ >
+ <LuMaximize />
+ </ActionIcon>
+ </Tooltip>
<ActionIcon
size="lg"
variant="light"
diff --git a/src/features/editor/views/GraphView/index.tsx b/src/features/editor/views/GraphView/index.tsx
index d2a65bf9..3bcf8fdd 100644
--- a/src/features/editor/views/GraphView/index.tsx
+++ b/src/features/editor/views/GraphView/index.tsx
@@ -7,7 +7,6 @@ import { Space } from "react-zoomable-ui";
import { Canvas } from "reaflow";
import type { ElkRoot } from "reaflow/dist/layout/useLayout";
import { useLongPress } from "use-long-press";
-import useToggleHide from "../../../../hooks/useToggleHide";
import useConfig from "../../../../store/useConfig";
import { CustomEdge } from "./CustomEdge";
import { CustomNode } from "./CustomNode";
@@ -20,7 +19,7 @@ import useGraph from "./stores/useGraph";
const StyledEditorWrapper = styled.div<{ $widget: boolean; $showRulers: boolean }>`
position: absolute;
width: 100%;
- height: ${({ $widget }) => ($widget ? "100vh" : "calc(100vh - 67px)")};
+ height: ${({ $widget }) => ($widget ? "100vh" : "calc(100vh - 40px)")};
--bg-color: ${({ theme }) => theme.GRID_BG_COLOR};
--line-color-1: ${({ theme }) => theme.GRID_COLOR_PRIMARY};
@@ -59,6 +58,10 @@ const StyledEditorWrapper = styled.div<{ $widget: boolean; $showRulers: boolean
pointer-events: none;
}
+ text {
+ fill: ${({ theme }) => theme.INTERACTIVE_NORMAL} !important;
+ }
+
rect {
fill: ${({ theme }) => theme.BACKGROUND_NODE};
}
@@ -78,13 +81,12 @@ interface GraphProps {
}
const GraphCanvas = ({ isWidget }: GraphProps) => {
- const { validateHiddenNodes } = useToggleHide();
const setLoading = useGraph(state => state.setLoading);
const centerView = useGraph(state => state.centerView);
const direction = useGraph(state => state.direction);
const nodes = useGraph(state => state.nodes);
- const colorScheme = useComputedColorScheme();
const edges = useGraph(state => state.edges);
+ const colorScheme = useComputedColorScheme();
const [paneWidth, setPaneWidth] = React.useState(2000);
const [paneHeight, setPaneHeight] = React.useState(2000);
@@ -98,7 +100,6 @@ const GraphCanvas = ({ isWidget }: GraphProps) => {
setPaneHeight((layout.height as number) + 50);
setTimeout(() => {
- validateHiddenNodes();
window.requestAnimationFrame(() => {
if (changeRatio > 70 || isWidget) centerView();
setLoading(false);
@@ -106,7 +107,7 @@ const GraphCanvas = ({ isWidget }: GraphProps) => {
});
}
},
- [isWidget, paneHeight, paneWidth, centerView, setLoading, validateHiddenNodes]
+ [isWidget, paneHeight, paneWidth, centerView, setLoading]
);
return (
diff --git a/src/features/editor/views/GraphView/lib/jsonParser.ts b/src/features/editor/views/GraphView/lib/jsonParser.ts
index a1baf0e0..8c397983 100644
--- a/src/features/editor/views/GraphView/lib/jsonParser.ts
+++ b/src/features/editor/views/GraphView/lib/jsonParser.ts
@@ -1,102 +1,207 @@
-import { parseTree } from "jsonc-parser";
-import type { EdgeData, NodeData } from "../../../../../types/graph";
-import { addEdgeToGraph } from "./utils/addEdgeToGraph";
-import { addNodeToGraph } from "./utils/addNodeToGraph";
-import { getNodePath } from "./utils/getNodePath";
-import { traverse } from "./utils/traverse";
+/**
+ * Copyright (c) JSON Crack
+ * This source code is licensed under the Apache 2.0 license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+import { parseTree, getNodePath, type Node } from "jsonc-parser";
+import type { EdgeData, NodeData, NodeRow } from "../../../../../types/graph";
+import { calculateNodeSize } from "./utils/calculateNodeSize";
export type Graph = {
nodes: NodeData[];
edges: EdgeData[];
};
-export type States = {
- parentName: string;
- bracketOpen: { id: string; type: string }[];
- objectsFromArray: number[];
- objectsFromArrayId: number;
- notHaveParent: string[];
- brothersNode: [string, string][] | string;
- brothersParentId: string | undefined;
- brotherKey: string;
- brothersNodeProps: {
- id: string;
- parentId: string | undefined;
- objectsFromArrayId: number | undefined;
- }[];
- graph: Graph;
-};
+export const parser = (json: string): Graph => {
+ const jsonTree = parseTree(json);
+ if (!jsonTree) return { nodes: [], edges: [] };
-function initializeStates(): States {
- return {
- parentName: "",
- bracketOpen: [],
- objectsFromArray: [],
- objectsFromArrayId: 0,
- notHaveParent: [],
- brothersNode: [],
- brothersParentId: undefined,
- brotherKey: "",
- brothersNodeProps: [],
- graph: {
- nodes: [],
- edges: [],
- },
- };
-}
-
-export function parser(jsonStr: string): Graph {
- try {
- const states = initializeStates();
- const parsedJsonTree = parseTree(jsonStr);
-
- if (!parsedJsonTree) {
- throw new Error("Invalid document");
- }
+ const nodes: NodeData[] = [];
+ const edges: EdgeData[] = [];
+ let nodeId = 1;
+ let edgeId = 1;
- traverse({ states, objectToTraverse: parsedJsonTree });
+ function traverse(node: Node, parentId?: string) {
+ const id = String(nodeId++);
+ const text: NodeRow[] = [];
+
+ // If parentId is provided, create an edge from parentId to the current node id
+ if (parentId !== undefined && node.parent?.type === "array") {
+ edges.push({
+ id: String(edgeId++),
+ from: parentId,
+ to: id,
+ text: "",
+ });
+ }
- const { notHaveParent, graph } = states;
+ const isArray = node.type === "array";
+ const isRootArray = !node.parent || node.parent.type === "array";
+ if (isArray && isRootArray) {
+ const { width, height } = calculateNodeSize(`[${node.children?.length ?? "0"} items]`);
+ nodes.push({
+ id,
+ text: [
+ {
+ key: null,
+ value: `[${node.children?.length ?? 0} items]`,
+ type: "array",
+ childrenCount: node.children?.length,
+ },
+ ],
+ width,
+ height,
+ path: [],
+ });
- if (notHaveParent.length > 1 && parsedJsonTree.type !== "array") {
- const emptyNode = { id: null, text: "", isEmpty: true, data: {} };
- const emptyId = addNodeToGraph({ graph, ...emptyNode });
+ node.children?.forEach(child => {
+ traverse(child, id);
+ });
- notHaveParent.forEach(childId => addEdgeToGraph(graph, emptyId, childId));
+ return id;
}
- if (states.graph.nodes.length === 0) {
- if (parsedJsonTree.type === "array") {
- addNodeToGraph({ graph: states.graph, text: "[]" });
+ node.children?.forEach(child => {
+ if (!child.children || !child.children[1]) return traverse(child, id);
+
+ const key = child.children[0].value ?? null;
+ const valueNode = child.children[1];
+ const type = valueNode.type;
+
+ if (type === "array") {
+ const targetIds: string[] = [];
+
+ valueNode.children?.forEach(arrayChild => {
+ const arrayChildId = traverse(arrayChild, undefined);
+ if (arrayChildId) targetIds.push(arrayChildId);
+ });
+
+ text.push({
+ key,
+ value: valueNode.value,
+ type,
+ to: targetIds.length > 0 ? targetIds : undefined,
+ childrenCount: valueNode.children?.length,
+ });
+
+ targetIds.forEach(targetId => {
+ edges.push({
+ id: String(edgeId++),
+ from: id,
+ to: targetId,
+ text: key ?? null,
+ });
+ });
+ } else if (type === "object") {
+ const objectNodeId = traverse(valueNode, id);
+ text.push({
+ key,
+ value: valueNode.value,
+ type,
+ childrenCount: Object.keys(valueNode.children ?? {}).length,
+ ...(objectNodeId && { to: [objectNodeId] }),
+ });
+
+ if (objectNodeId) {
+ edges.push({
+ id: String(edgeId++),
+ from: id,
+ to: objectNodeId,
+ text: key ?? null,
+ });
+ }
} else {
- addNodeToGraph({ graph: states.graph, text: "{}" });
+ text.push({
+ key,
+ value: valueNode.value,
+ type,
+ });
}
+ });
+
+ // to handle case where empty object inside array [{}]
+ if (node.parent?.type === "array" && node.type === "object" && node.children?.length === 0) {
+ text.push({
+ key: null,
+ value: "{0 keys}",
+ type: "object",
+ childrenCount: 0,
+ });
}
- // filter parent nodes that have no children
- // not the best way to do this, but it works
- const filteredNodes = states.graph.nodes.filter(node => {
- return !(node.data.isParent && node.data.childrenCount === 0);
- });
+ const appendParentKey = () => {
+ const getParentKey = (targetNode: any) => {
+ const path = getNodePath(targetNode);
+ return path?.pop()?.toString();
+ };
+
+ if (!node.parent) {
+ return { parentKey: getParentKey(node), parentType: node.type };
+ }
- // add path to nodes
- states.graph.nodes = filteredNodes.map(node => ({
- ...node,
- path: getNodePath(states.graph.nodes, states.graph.edges, node.id),
- }));
+ if (node.parent.type === "array") {
+ return { parentKey: getParentKey(node.parent), parentType: "array" };
+ }
- // filter edges that have no from or to node (since we filtered empty parent nodes)
- states.graph.edges = states.graph.edges.filter(edge => {
- const fromNode = states.graph.nodes.find(node => node.id === edge.from);
- const toNode = states.graph.nodes.find(node => node.id === edge.to);
+ if (node.parent.type === "property") {
+ return { parentKey: getParentKey(node), parentType: "object" };
+ }
- if (!fromNode || !toNode) return false;
- return true;
- });
+ return {
+ parentKey: getParentKey(node),
+ parentType: node.parent.type.replace("property", "object"),
+ };
+ };
+
+ // its for singular text like string, number, boolean, null
+ if (text.length === 0) {
+ if (typeof node.value === "undefined") return;
+ const { width, height } = calculateNodeSize(node.value);
+
+ nodes.push({
+ id,
+ text: [
+ {
+ key: null,
+ value: node.value,
+ type: node.type,
+ },
+ ],
+ width,
+ height,
+ path: getNodePath(node),
+ ...appendParentKey(),
+ });
+ } else {
+ let t: string | [string, string][] = "";
+
+ if (text.some(t => t.key !== null)) {
+ t = text.map(t => {
+ const keyStr = t.key === null ? "" : t.key;
+ if (t.type === "object") return [keyStr, `{${t.childrenCount ?? 0} keys}`];
+ if (t.type === "array") return [keyStr, `[${t.childrenCount ?? 0} items]`];
+ if (t.value === null) return [keyStr, "null"];
- return states.graph;
- } catch (error) {
- console.error(error);
- return { nodes: [], edges: [] };
+ return [keyStr, `${t.value}`];
+ });
+ } else {
+ t = `${text[0].value}`;
+ }
+
+ const { width, height } = calculateNodeSize(t);
+ nodes.push({
+ id,
+ text,
+ width,
+ height,
+ path: getNodePath(node),
+ ...appendParentKey(),
+ });
+ }
+
+ return id; // Return the current id for referencing in the parent node
}
-}
+
+ traverse(jsonTree);
+ return { nodes, edges };
+};
diff --git a/src/features/editor/views/GraphView/lib/utils/addEdgeToGraph.ts b/src/features/editor/views/GraphView/lib/utils/addEdgeToGraph.ts
deleted file mode 100644
index a54e909b..00000000
--- a/src/features/editor/views/GraphView/lib/utils/addEdgeToGraph.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { Graph } from "../jsonParser";
-
-export const addEdgeToGraph = (graph: Graph, from: string, to: string) => {
- const newEdge = {
- id: `e${from}-${to}`,
- from: from,
- to: to,
- };
-
- graph.edges.push(newEdge);
-};
diff --git a/src/features/editor/views/GraphView/lib/utils/addNodeToGraph.ts b/src/features/editor/views/GraphView/lib/utils/addNodeToGraph.ts
deleted file mode 100644
index 896c4684..00000000
--- a/src/features/editor/views/GraphView/lib/utils/addNodeToGraph.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import type { NodeType } from "jsonc-parser";
-import type { Graph } from "../jsonParser";
-import { calculateNodeSize } from "./calculateNodeSize";
-
-type Props = {
- graph: Graph;
- text: string | [string, string][];
- isEmpty?: boolean;
- type?: NodeType;
-};
-
-export const addNodeToGraph = ({ graph, text, type = "null", isEmpty = false }: Props) => {
- const id = String(graph.nodes.length + 1);
- const isParent = type === "array" || type === "object";
- const { width, height } = calculateNodeSize(text, isParent);
-
- const node = {
- id,
- text,
- width,
- height,
- data: {
- type,
- isParent,
- isEmpty,
- childrenCount: isParent ? 1 : 0,
- },
- };
-
- graph.nodes.push(node);
-
- return id;
-};
diff --git a/src/features/editor/views/GraphView/lib/utils/calculateNodeSize.ts b/src/features/editor/views/GraphView/lib/utils/calculateNodeSize.ts
index 026971d8..81f69e03 100644
--- a/src/features/editor/views/GraphView/lib/utils/calculateNodeSize.ts
+++ b/src/features/editor/views/GraphView/lib/utils/calculateNodeSize.ts
@@ -1,7 +1,7 @@
import { NODE_DIMENSIONS } from "../../../../../../constants/graph";
import useConfig from "../../../../../../store/useConfig";
-type Text = string | [string, string][];
+type Text = number | string | [string, string][];
type Size = { width: number; height: number };
export const isContentImage = (value: Text) => {
@@ -14,11 +14,11 @@ export const isContentImage = (value: Text) => {
};
const calculateLines = (text: Text): string => {
- if (typeof text === "string") {
- return text;
- } else {
+ if (Array.isArray(text)) {
return text.map(([k, v]) => `${k}: ${JSON.stringify(v).slice(0, 80)}`).join("\n");
}
+
+ return `${text}`;
};
const calculateWidthAndHeight = (str: string, single = false) => {
diff --git a/src/features/editor/views/GraphView/lib/utils/getNodePath.ts b/src/features/editor/views/GraphView/lib/utils/getNodePath.ts
deleted file mode 100644
index cd3993b9..00000000
--- a/src/features/editor/views/GraphView/lib/utils/getNodePath.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { NodeData, EdgeData } from "../../../../../../types/graph";
-
-export function getNodePath(nodes: NodeData[], edges: EdgeData[], nodeId: string) {
- // eslint-disable-next-line @typescript-eslint/no-var-requires
- const { getParentsForNodeId } = require("reaflow");
-
- let resolvedPath = "";
- const parentIds = getParentsForNodeId(nodes, edges, nodeId).map(n => n.id);
- const path = parentIds.reverse().concat(nodeId);
- const rootArrayElementIds = ["1"];
- const edgesMap = new Map();
-
- for (const edge of edges) {
- if (!edgesMap.has(edge.from!)) {
- edgesMap.set(edge.from!, []);
- }
- edgesMap.get(edge.from!).push(edge.to);
- }
-
- for (let i = 1; i < edges.length; i++) {
- const curNodeId = edges[i].from!;
-
- if (rootArrayElementIds.includes(curNodeId)) continue;
- if (!edgesMap.has(curNodeId)) {
- rootArrayElementIds.push(curNodeId);
- }
- }
-
- if (rootArrayElementIds.length > 1) {
- resolvedPath += `Root[${rootArrayElementIds.findIndex(id => id === path[0])}]`;
- } else {
- resolvedPath += "{Root}";
- }
-
- for (let i = 1; i < path.length; i++) {
- const curId = path[i];
- const curNode = nodes[+curId - 1];
-
- if (!curNode) break;
- if (curNode.data?.type === "array") {
- resolvedPath += `.${curNode.text}`;
-
- if (i !== path.length - 1) {
- const toNodeId = path[i + 1];
- const idx = edgesMap.get(curId).indexOf(toNodeId);
-
- resolvedPath += `[${idx}]`;
- }
- }
-
- if (curNode.data?.type === "object") {
- resolvedPath += `.${curNode.text}`;
- }
- }
-
- return resolvedPath;
-}
diff --git a/src/features/editor/views/GraphView/lib/utils/traverse.ts b/src/features/editor/views/GraphView/lib/utils/traverse.ts
deleted file mode 100644
index de16de40..00000000
--- a/src/features/editor/views/GraphView/lib/utils/traverse.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-import type { Node, NodeType } from "jsonc-parser";
-import type { States, Graph } from "../jsonParser";
-import { addEdgeToGraph } from "./addEdgeToGraph";
-import { addNodeToGraph } from "./addNodeToGraph";
-import { calculateNodeSize } from "./calculateNodeSize";
-
-type PrimitiveOrNullType = "boolean" | "string" | "number" | "null";
-
-type Traverse = {
- states: States;
- objectToTraverse: Node;
- parentType?: string;
- myParentId?: string;
- nextType?: string;
-};
-
-const isPrimitiveOrNullType = (type: unknown): type is PrimitiveOrNullType => {
- return ["boolean", "string", "number", "null"].includes(type as string);
-};
-
-const alignChildren = (nodeA: Node, nodeB: Node): number => {
- const aChildType = nodeA?.children?.[1]?.type;
- const bChildType = nodeB?.children?.[1]?.type;
-
- if (isPrimitiveOrNullType(aChildType) && !isPrimitiveOrNullType(bChildType)) {
- return -1;
- }
-
- return 0;
-};
-
-function handleNoChildren(
- value: string | undefined,
- states: States,
- graph: Graph,
- myParentId?: string,
- parentType?: string,
- nextType?: string
-) {
- if (value === undefined) return;
-
- if (parentType === "property" && nextType !== "object" && nextType !== "array") {
- states.brothersParentId = myParentId;
- if (nextType === undefined && Array.isArray(states.brothersNode)) {
- states.brothersNode.push([states.brotherKey, value]);
- } else {
- states.brotherKey = value;
- }
- } else if (parentType === "array") {
- const nodeFromArrayId = addNodeToGraph({ graph, text: String(value) });
-
- if (myParentId) {
- addEdgeToGraph(graph, myParentId, nodeFromArrayId);
- }
- }
-
- if (nextType && parentType !== "array" && (nextType === "object" || nextType === "array")) {
- states.parentName = value;
- }
-}
-
-function handleHasChildren(
- type: NodeType,
- states: States,
- graph: Graph,
- children: Node[],
- myParentId?: string,
- parentType?: string
-) {
- let parentId: string | undefined;
-
- if (type !== "property" && states.parentName !== "") {
- // add last brothers node and add parent node
-
- if (states.brothersNode.length > 0) {
- const findBrothersNode = states.brothersNodeProps.find(
- e =>
- e.parentId === states.brothersParentId &&
- e.objectsFromArrayId === states.objectsFromArray[states.objectsFromArray.length - 1]
- );
-
- if (findBrothersNode) {
- const findNodeIndex = graph.nodes.findIndex(e => e.id === findBrothersNode?.id);
-
- if (findNodeIndex !== -1) {
- const modifyNodes = [...graph.nodes];
- const foundNode = modifyNodes[findNodeIndex];
-
- foundNode.text = foundNode.text.concat(states.brothersNode as any);
- const { width, height } = calculateNodeSize(foundNode.text, false);
-
- foundNode.width = width;
- foundNode.height = height;
-
- graph.nodes = modifyNodes;
- states.brothersNode = [];
- }
- } else {
- const brothersNodeId = addNodeToGraph({ graph, text: states.brothersNode });
-
- states.brothersNode = [];
-
- if (states.brothersParentId) {
- addEdgeToGraph(graph, states.brothersParentId, brothersNodeId);
- } else {
- states.notHaveParent.push(brothersNodeId);
- }
-
- states.brothersNodeProps.push({
- id: brothersNodeId,
- parentId: states.brothersParentId,
- objectsFromArrayId: states.objectsFromArray[states.objectsFromArray.length - 1],
- });
- }
- }
-
- // Add parent node
- parentId = addNodeToGraph({ graph, type, text: states.parentName });
- states.bracketOpen.push({ id: parentId, type });
- states.parentName = "";
-
- // Add edges from parent node
- const brothersProps = states.brothersNodeProps.filter(
- e =>
- e.parentId === myParentId &&
- e.objectsFromArrayId === states.objectsFromArray[states.objectsFromArray.length - 1]
- );
-
- if (
- (brothersProps.length > 0 &&
- states.bracketOpen[states.bracketOpen.length - 2]?.type !== "object") ||
- (brothersProps.length > 0 && states.bracketOpen.length === 1)
- ) {
- addEdgeToGraph(graph, brothersProps[brothersProps.length - 1].id, parentId);
- } else if (myParentId) {
- addEdgeToGraph(graph, myParentId, parentId);
- } else {
- states.notHaveParent.push(parentId);
- }
- } else if (parentType === "array") {
- states.objectsFromArray = [...states.objectsFromArray, states.objectsFromArrayId++];
- }
- const traverseObject = (objectToTraverse: Node, nextType: string) => {
- traverse({
- states,
- objectToTraverse,
- parentType: type,
- myParentId: states.bracketOpen[states.bracketOpen.length - 1]?.id,
- nextType,
- });
- };
-
- const traverseArray = () => {
- children.forEach((objectToTraverse, index, array) => {
- const nextType = array[index + 1]?.type;
-
- traverseObject(objectToTraverse, nextType);
- });
- };
-
- if (type === "object") {
- children.sort(alignChildren);
- traverseArray();
- } else {
- traverseArray();
- }
-
- if (type !== "property") {
- // Add or concatenate brothers node when it is the last parent node
- if (states.brothersNode.length > 0) {
- const findBrothersNode = states.brothersNodeProps.find(
- e =>
- e.parentId === states.brothersParentId &&
- e.objectsFromArrayId === states.objectsFromArray[states.objectsFromArray.length - 1]
- );
-
- if (findBrothersNode) {
- const modifyNodes = [...graph.nodes];
- const findNodeIndex = modifyNodes.findIndex(e => e.id === findBrothersNode?.id);
-
- if (modifyNodes[findNodeIndex] && typeof states.brothersNode === "string") {
- modifyNodes[findNodeIndex].text += states.brothersNode;
-
- const { width, height } = calculateNodeSize(modifyNodes[findNodeIndex].text, false);
-
- modifyNodes[findNodeIndex].width = width;
- modifyNodes[findNodeIndex].height = height;
-
- graph.nodes = modifyNodes;
- states.brothersNode = [];
- }
- } else {
- const brothersNodeId = addNodeToGraph({ graph, text: states.brothersNode });
-
- states.brothersNode = [];
-
- if (states.brothersParentId) {
- addEdgeToGraph(graph, states.brothersParentId, brothersNodeId);
- } else {
- states.notHaveParent = [...states.notHaveParent, brothersNodeId];
- }
-
- const brothersNodeProps = {
- id: brothersNodeId,
- parentId: states.brothersParentId,
- objectsFromArrayId: states.objectsFromArray[states.objectsFromArray.length - 1],
- };
-
- states.brothersNodeProps = [...states.brothersNodeProps, brothersNodeProps];
- }
- }
-
- // Close brackets
- if (parentType === "array") {
- if (states.objectsFromArray.length > 0) {
- states.objectsFromArray.pop();
- }
- } else {
- if (states.bracketOpen.length > 0) {
- states.bracketOpen.pop();
- }
- }
-
- if (parentId) {
- const myChildren = graph.edges.filter(edge => edge.from === parentId);
- const parentIndex = graph.nodes.findIndex(node => node.id === parentId);
-
- graph.nodes = graph.nodes.map((node, index) => {
- if (index === parentIndex) {
- const childrenCount = myChildren.length;
-
- return { ...node, data: { ...node.data, childrenCount } };
- }
- return node;
- });
- }
- }
-}
-
-export const traverse = ({
- objectToTraverse,
- states,
- myParentId,
- nextType,
- parentType,
-}: Traverse) => {
- const graph = states.graph;
- const { type, children, value } = objectToTraverse;
-
- if (!children) {
- handleNoChildren(value, states, graph, myParentId, parentType, nextType);
- } else if (children) {
- handleHasChildren(type, states, graph, children, myParentId, parentType);
- }
-};
diff --git a/src/features/editor/views/GraphView/stores/useGraph.ts b/src/features/editor/views/GraphView/stores/useGraph.ts
index 7f56fb1a..6e067c3c 100644
--- a/src/features/editor/views/GraphView/stores/useGraph.ts
+++ b/src/features/editor/views/GraphView/stores/useGraph.ts
@@ -5,21 +5,14 @@ import { SUPPORTED_LIMIT } from "../../../../../constants/graph";
import useJson from "../../../../../store/useJson";
import type { EdgeData, NodeData } from "../../../../../types/graph";
import { parser } from "../lib/jsonParser";
-import { getChildrenEdges } from "../lib/utils/getChildrenEdges";
-import { getOutgoers } from "../lib/utils/getOutgoers";
export interface Graph {
viewPort: ViewPort | null;
direction: CanvasDirection;
loading: boolean;
- graphCollapsed: boolean;
fullscreen: boolean;
- collapseAll: boolean;
nodes: NodeData[];
edges: EdgeData[];
- collapsedNodes: string[];
- collapsedEdges: string[];
- collapsedParents: string[];
selectedNode: NodeData | null;
path: string;
aboveSupportedLimit: boolean;
@@ -29,14 +22,9 @@ const initialStates: Graph = {
viewPort: null,
direction: "RIGHT",
loading: true,
- graphCollapsed: false,
fullscreen: false,
- collapseAll: false,
nodes: [],
edges: [],
- collapsedNodes: [],
- collapsedEdges: [],
- collapsedParents: [],
selectedNode: null,
path: "",
aboveSupportedLimit: false,
@@ -49,14 +37,7 @@ interface GraphActions {
setViewPort: (ref: ViewPort) => void;
setSelectedNode: (nodeData: NodeData) => void;
focusFirstNode: () => void;
- expandNodes: (nodeId: string) => void;
- expandGraph: () => void;
- collapseNodes: (nodeId: string) => void;
- collapseGraph: () => void;
- getCollapsedNodeIds: () => string[];
- getCollapsedEdgeIds: () => string[];
toggleFullscreen: (value: boolean) => void;
- toggleCollapseAll: (value: boolean) => void;
zoomIn: () => void;
zoomOut: () => void;
centerView: () => void;
@@ -66,146 +47,33 @@ interface GraphActions {
const useGraph = create<Graph & GraphActions>((set, get) => ({
...initialStates,
- toggleCollapseAll: collapseAll => {
- set({ collapseAll });
- get().collapseGraph();
- },
clearGraph: () => set({ nodes: [], edges: [], loading: false }),
- getCollapsedNodeIds: () => get().collapsedNodes,
- getCollapsedEdgeIds: () => get().collapsedEdges,
setSelectedNode: nodeData => set({ selectedNode: nodeData }),
setGraph: (data, options) => {
const { nodes, edges } = parser(data ?? useJson.getState().json);
- if (get().collapseAll) {
- if (nodes.length > SUPPORTED_LIMIT) {
- return set({ aboveSupportedLimit: true, ...options, loading: false });
- }
-
- set({ nodes, edges, aboveSupportedLimit: false, ...options });
- get().collapseGraph();
- } else {
- if (nodes.length > SUPPORTED_LIMIT) {
- return set({
- aboveSupportedLimit: true,
- collapsedParents: [],
- collapsedNodes: [],
- collapsedEdges: [],
- ...options,
- loading: false,
- });
- }
-
- set({
- nodes,
- edges,
- collapsedParents: [],
- collapsedNodes: [],
- collapsedEdges: [],
- graphCollapsed: false,
- aboveSupportedLimit: false,
+ if (nodes.length > SUPPORTED_LIMIT) {
+ return set({
+ aboveSupportedLimit: true,
...options,
+ loading: false,
});
}
+
+ set({
+ nodes,
+ edges,
+ aboveSupportedLimit: false,
+ ...options,
+ });
},
setDirection: (direction = "RIGHT") => {
set({ direction });
setTimeout(() => get().centerView(), 200);
},
setLoading: loading => set({ loading }),
- expandNodes: nodeId => {
- const [childrenNodes, matchingNodes] = getOutgoers(
- nodeId,
- get().nodes,
- get().edges,
- get().collapsedParents
- );
- const childrenEdges = getChildrenEdges(childrenNodes, get().edges);
-
- const nodesConnectedToParent = childrenEdges.reduce((nodes: string[], edge) => {
- edge.from && !nodes.includes(edge.from) && nodes.push(edge.from);
- edge.to && !nodes.includes(edge.to) && nodes.push(edge.to);
- return nodes;
- }, []);
- const matchingNodesConnectedToParent = matchingNodes.filter(node =>
- nodesConnectedToParent.includes(node)
- );
- const nodeIds = childrenNodes.map(node => node.id).concat(matchingNodesConnectedToParent);
- const edgeIds = childrenEdges.map(edge => edge.id);
-
- const collapsedParents = get().collapsedParents.filter(cp => cp !== nodeId);
- const collapsedNodes = get().collapsedNodes.filter(nodeId => !nodeIds.includes(nodeId));
- const collapsedEdges = get().collapsedEdges.filter(edgeId => !edgeIds.includes(edgeId));
-
- set({
- collapsedParents,
- collapsedNodes,
- collapsedEdges,
- graphCollapsed: !!collapsedNodes.length,
- });
- },
- collapseNodes: nodeId => {
- const [childrenNodes] = getOutgoers(nodeId, get().nodes, get().edges);
- const childrenEdges = getChildrenEdges(childrenNodes, get().edges);
-
- const nodeIds = childrenNodes.map(node => node.id);
- const edgeIds = childrenEdges.map(edge => edge.id);
-
- set({
- collapsedParents: get().collapsedParents.concat(nodeId),
- collapsedNodes: get().collapsedNodes.concat(nodeIds),
- collapsedEdges: get().collapsedEdges.concat(edgeIds),
- graphCollapsed: !!get().collapsedNodes.concat(nodeIds).length,
- });
- },
- collapseGraph: () => {
- const edges = get().edges;
- const tos = edges.map(edge => edge.to);
- const froms = edges.map(edge => edge.from);
- const parentNodesIds = froms.filter(id => !tos.includes(id));
- const secondDegreeNodesIds = edges
- .filter(edge => parentNodesIds.includes(edge.from))
- .map(edge => edge.to);
-
- const collapsedParents = get()
- .nodes.filter(node => !parentNodesIds.includes(node.id) && node.data?.isParent)
- .map(node => node.id);
-
- const collapsedNodes = get()
- .nodes.filter(
- node => !parentNodesIds.includes(node.id) && !secondDegreeNodesIds.includes(node.id)
- )
- .map(node => node.id);
-
- const closestParentToRoot = Math.min(...collapsedParents.map(n => +n));
- const focusNodeId = `g[id*='node-${closestParentToRoot}']`;
- const rootNode = document.querySelector(focusNodeId);
-
- set({
- collapsedParents,
- collapsedNodes,
- collapsedEdges: get()
- .edges.filter(edge => !parentNodesIds.includes(edge.from))
- .map(edge => edge.id),
- graphCollapsed: true,
- });
-
- if (rootNode) {
- get().viewPort?.camera?.centerFitElementIntoView(rootNode as HTMLElement, {
- elementExtraMarginForZoom: 300,
- });
- }
- },
- expandGraph: () => {
- set({
- collapsedNodes: [],
- collapsedEdges: [],
- collapsedParents: [],
- graphCollapsed: false,
- });
- },
focusFirstNode: () => {
- const rootNode = document.querySelector("g[id*='node-1']");
+ const rootNode = document.querySelector("g[id$='node-1']");
get().viewPort?.camera?.centerFitElementIntoView(rootNode as HTMLElement, {
elementExtraMarginForZoom: 100,
});
diff --git a/src/features/modals/ImportModal/index.tsx b/src/features/modals/ImportModal/index.tsx
index 9e44fc6a..ab47a5fa 100644
--- a/src/features/modals/ImportModal/index.tsx
+++ b/src/features/modals/ImportModal/index.tsx
@@ -69,7 +69,6 @@ export const ImportModal = ({ opened, onClose }: ModalProps) => {
<Dropzone
onDrop={files => setFile(files[0])}
onReject={files => toast.error(`Unable to load file ${files[0].file.name}`)}
- maxSize={500 * 1024}
maxFiles={1}
p="md"
accept={[
@@ -83,9 +82,6 @@ export const ImportModal = ({ opened, onClose }: ModalProps) => {
<Stack justify="center" align="center" gap="sm" mih={220}>
<AiOutlineUpload size={48} />
<Text fw="bold">Drop here or click to upload files</Text>
- <Text c="dimmed" fz="xs">
- (Max 500 KB)
- </Text>
<Text c="dimmed" fz="sm">
{file?.name ?? "None"}
</Text>
diff --git a/src/features/modals/NodeModal/index.tsx b/src/features/modals/NodeModal/index.tsx
index 49a263a4..996da1e6 100644
--- a/src/features/modals/NodeModal/index.tsx
+++ b/src/features/modals/NodeModal/index.tsx
@@ -1,32 +1,51 @@
import React from "react";
import type { ModalProps } from "@mantine/core";
-import { Modal, Stack, Text, ScrollArea } from "@mantine/core";
+import { Modal, Stack, Text, ScrollArea, Flex, CloseButton } from "@mantine/core";
import { CodeHighlight } from "@mantine/code-highlight";
+import type { NodeData } from "../../../types/graph";
import useGraph from "../../editor/views/GraphView/stores/useGraph";
-const dataToString = (data: any) => {
- const text = Array.isArray(data) ? Object.fromEntries(data) : data;
- const replacer = (_: string, v: string) => {
- if (typeof v === "string") return v.replaceAll('"', "");
- return v;
- };
+// return object from json removing array and object fields
+const normalizeNodeData = (nodeRows: NodeData["text"]) => {
+ if (!nodeRows || nodeRows.length === 0) return "{}";
+ if (nodeRows.length === 1 && !nodeRows[0].key) return `${nodeRows[0].value}`;
- return JSON.stringify(text, replacer, 2);
+ const obj = {};
+ nodeRows?.forEach(row => {
+ if (row.type !== "array" && row.type !== "object") {
+ if (row.key) obj[row.key] = row.value;
+ }
+ });
+ return JSON.stringify(obj, null, 2);
+};
+
+// return json path in the format $["customer"]
+const jsonPathToString = (path?: NodeData["path"]) => {
+ if (!path || path.length === 0) return "$";
+ return `$["${path.join('"]["')}"]`;
};
export const NodeModal = ({ opened, onClose }: ModalProps) => {
- const nodeData = useGraph(state => dataToString(state.selectedNode?.text));
- const path = useGraph(state => state.selectedNode?.path || "");
+ const nodeData = useGraph(state => state.selectedNode);
return (
- <Modal title="Node Content" size="auto" opened={opened} onClose={onClose} centered>
- <Stack py="sm" gap="sm">
+ <Modal size="auto" opened={opened} onClose={onClose} centered withCloseButton={false}>
+ <Stack pb="sm" gap="sm">
<Stack gap="xs">
- <Text fz="xs" fw={500}>
- Content
- </Text>
+ <Flex justify="space-between" align="center">
+ <Text fz="xs" fw={500}>
+ Content
+ </Text>
+ <CloseButton onClick={onClose} />
+ </Flex>
<ScrollArea.Autosize mah={250} maw={600}>
- <CodeHighlight code={nodeData} miw={350} maw={600} language="json" withCopyButton />
+ <CodeHighlight
+ code={normalizeNodeData(nodeData?.text ?? [])}
+ miw={350}
+ maw={600}
+ language="json"
+ withCopyButton
+ />
</ScrollArea.Autosize>
</Stack>
<Text fz="xs" fw={500}>
@@ -34,7 +53,7 @@ export const NodeModal = ({ opened, onClose }: ModalProps) => {
</Text>
<ScrollArea.Autosize maw={600}>
<CodeHighlight
- code={path}
+ code={jsonPathToString(nodeData?.path)}
miw={350}
mah={250}
language="json"
diff --git a/src/features/modals/SchemaModal/index.tsx b/src/features/modals/SchemaModal/index.tsx
index f3f87736..a886c545 100644
--- a/src/features/modals/SchemaModal/index.tsx
+++ b/src/features/modals/SchemaModal/index.tsx
@@ -5,14 +5,17 @@ import Editor from "@monaco-editor/react";
import { event as gaEvent } from "nextjs-google-analytics";
import { toast } from "react-hot-toast";
import { FaChevronDown } from "react-icons/fa";
+import { FaCrown } from "react-icons/fa6";
import { VscLinkExternal } from "react-icons/vsc";
import { FileFormat } from "../../../enums/file.enum";
import useConfig from "../../../store/useConfig";
import useFile from "../../../store/useFile";
+import { useModal } from "../../../store/useModal";
export const SchemaModal = ({ opened, onClose }: ModalProps) => {
const setContents = useFile(state => state.setContents);
const setJsonSchema = useFile(state => state.setJsonSchema);
+ const setVisible = useModal(state => state.setVisible);
const darkmodeEnabled = useConfig(state => (state.darkmodeEnabled ? "vs-dark" : "light"));
const [schema, setSchema] = React.useState(
JSON.stringify(
@@ -113,6 +116,12 @@ export const SchemaModal = ({ opened, onClose }: ModalProps) => {
</Menu.Target>
<Menu.Dropdown>
<Menu.Item onClick={generateMockData}>Generate Mock Data</Menu.Item>
+ <Menu.Item
+ onClick={() => setVisible("UpgradeModal", true)}
+ rightSection={<FaCrown />}
+ >
+ Validate on Diagrams
+ </Menu.Item>
</Menu.Dropdown>
</Menu>
</Button.Group>
diff --git a/src/hooks/useToggleHide.ts b/src/hooks/useToggleHide.ts
deleted file mode 100644
index 04beb581..00000000
--- a/src/hooks/useToggleHide.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import React from "react";
-import useGraph from "../features/editor/views/GraphView/stores/useGraph";
-
-const useToggleHide = () => {
- const getCollapsedNodeIds = useGraph(state => state.getCollapsedNodeIds);
- const getCollapsedEdgeIds = useGraph(state => state.getCollapsedEdgeIds);
-
- React.useEffect(() => {
- validateHiddenNodes(getCollapsedNodeIds(), getCollapsedEdgeIds());
- }, [getCollapsedEdgeIds, getCollapsedNodeIds]);
-
- return {
- validateHiddenNodes: () => validateHiddenNodes(getCollapsedNodeIds(), getCollapsedEdgeIds()),
- };
-};
-
-function validateHiddenNodes(collapsedNodeIs: string[], collapsedEdgeIds: string[]) {
- const nodeList = collapsedNodeIs.map(id => `[id$="node-${id}"]`);
- const edgeList = collapsedEdgeIds.map(id => `[class$="edge-${id}"]`);
- const hiddenItems = document.body.querySelectorAll(".hide");
-
- hiddenItems.forEach(item => item.classList.remove("hide"));
-
- if (nodeList.length) {
- const selectedNodes = document.body.querySelectorAll(nodeList.join(","));
-
- selectedNodes.forEach(node => node.classList.add("hide"));
- }
-
- if (edgeList.length) {
- const selectedEdges = document.body.querySelectorAll(edgeList.join(","));
-
- selectedEdges.forEach(edge => edge.classList.add("hide"));
- }
-}
-
-export default useToggleHide;
diff --git a/src/layout/PageLayout/index.tsx b/src/layout/PageLayout/index.tsx
index 9d76b2d5..f700b760 100644
--- a/src/layout/PageLayout/index.tsx
+++ b/src/layout/PageLayout/index.tsx
@@ -1,6 +1,9 @@
import React from "react";
import { Inter } from "next/font/google";
+import Link from "next/link";
+import { Button, Flex, Text } from "@mantine/core";
import styled, { ThemeProvider } from "styled-components";
+import { FaChevronRight } from "react-icons/fa6";
import { lightTheme } from "../../constants/theme";
import { Footer } from "./Footer";
import { Navbar } from "./Navbar";
@@ -25,6 +28,20 @@ const PageLayout = ({ children }: React.PropsWithChildren) => {
return (
<ThemeProvider theme={lightTheme}>
<StyledLayoutWrapper>
+ <Link
+ href="https://todiagram.com/blog/todiagram-github-education?utm_source=jsoncrack&utm_medium=hero_badge&utm_campaign=github_education"
+ target="_blank"
+ rel="noopener"
+ >
+ <Flex gap="xs" justify="center" align="center" bg="indigo" py="xs">
+ <Text fz="sm" fw="500" c="gray.2">
+ ToDiagram joins GitHub Student Developer Pack!
+ </Text>
+ <Button size="compact-xs" variant="default" color="gray">
+ Learn More <FaChevronRight />
+ </Button>
+ </Flex>
+ </Link>
<Navbar />
<ContentWrapper>{children}</ContentWrapper>
<Footer />
diff --git a/src/lib/utils/search.ts b/src/lib/utils/search.ts
index e8d536fc..58f54c71 100644
--- a/src/lib/utils/search.ts
+++ b/src/lib/utils/search.ts
@@ -4,20 +4,18 @@ export const searchQuery = (param: string) => {
export const cleanupHighlight = () => {
const nodes = document.querySelectorAll("foreignObject.searched, .highlight");
-
- nodes.forEach(node => {
- node.classList.remove("highlight", "searched");
- });
+ for (let i = 0; i < nodes.length; i++) {
+ const node = nodes[i];
+ node.classList.remove("searched", "highlight");
+ }
};
export const highlightMatchedNodes = (nodes: NodeListOf<Element>, selectedNode: number) => {
- nodes.forEach(node => {
+ for (let i = 0; i < nodes.length; i++) {
+ const node = nodes[i];
const foreignObject = node.parentElement?.closest("foreignObject");
-
- if (foreignObject) {
- foreignObject.classList.add("searched");
- }
- });
+ if (foreignObject) foreignObject.classList.add("searched");
+ }
nodes[selectedNode].classList.add("highlight");
};
diff --git a/src/pages/editor.tsx b/src/pages/editor.tsx
index 2c5db70e..6612cf71 100644
--- a/src/pages/editor.tsx
+++ b/src/pages/editor.tsx
@@ -31,7 +31,7 @@ const queryClient = new QueryClient({
});
export const StyledPageWrapper = styled.div`
- height: calc(100vh - 27px);
+ height: 100vh;
width: 100%;
@media only screen and (max-width: 320px) {
@@ -49,13 +49,20 @@ export const StyledEditor = styled(Allotment)`
position: relative !important;
display: flex;
background: ${({ theme }) => theme.BACKGROUND_SECONDARY};
- height: calc(100vh - 67px);
+ height: calc(100vh - 40px);
@media only screen and (max-width: 320px) {
height: 100vh;
}
`;
+const StyledTextEditor = styled.div`
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ height: 100%;
+`;
+
const TextEditor = dynamic(() => import("../features/editor/TextEditor"), {
ssr: false,
});
@@ -102,7 +109,10 @@ const EditorPage = () => {
maxSize={800}
visible={!fullscreen}
>
- <TextEditor />
+ <StyledTextEditor>
+ <TextEditor />
+ <BottomBar />
+ </StyledTextEditor>
</Allotment.Pane>
<Allotment.Pane minSize={0}>
<LiveEditor />
@@ -111,7 +121,6 @@ const EditorPage = () => {
<FullscreenDropzone />
</StyledEditorWrapper>
</StyledPageWrapper>
- <BottomBar />
</StyledEditorWrapper>
</QueryClientProvider>
</ThemeProvider>
diff --git a/src/store/useConfig.ts b/src/store/useConfig.ts
index 7904f6f4..2764c03d 100644
--- a/src/store/useConfig.ts
+++ b/src/store/useConfig.ts
@@ -4,8 +4,6 @@ import useGraph from "../features/editor/views/GraphView/stores/useGraph";
const initialStates = {
darkmodeEnabled: true,
- collapseButtonVisible: true,
- childrenCountVisible: true,
imagePreviewEnabled: true,
liveTransformEnabled: true,
gesturesEnabled: false,
@@ -14,8 +12,6 @@ const initialStates = {
export interface ConfigActions {
toggleDarkMode: (value: boolean) => void;
- toggleCollapseButton: (value: boolean) => void;
- toggleChildrenCount: (value: boolean) => void;
toggleImagePreview: (value: boolean) => void;
toggleLiveTransform: (value: boolean) => void;
toggleGestures: (value: boolean) => void;
@@ -30,8 +26,6 @@ const useConfig = create(
toggleGestures: gesturesEnabled => set({ gesturesEnabled }),
toggleLiveTransform: liveTransformEnabled => set({ liveTransformEnabled }),
toggleDarkMode: darkmodeEnabled => set({ darkmodeEnabled }),
- toggleCollapseButton: collapseButtonVisible => set({ collapseButtonVisible }),
- toggleChildrenCount: childrenCountVisible => set({ childrenCountVisible }),
toggleImagePreview: imagePreviewEnabled => {
set({ imagePreviewEnabled });
useGraph.getState().setGraph();
diff --git a/src/store/useFile.ts b/src/store/useFile.ts
index 19311819..21e2a230 100644
--- a/src/store/useFile.ts
+++ b/src/store/useFile.ts
@@ -2,6 +2,7 @@ import debounce from "lodash.debounce";
import { event as gaEvent } from "nextjs-google-analytics";
import { toast } from "react-hot-toast";
import { create } from "zustand";
+import exampleJson from "../data/example.json";
import { FileFormat } from "../enums/file.enum";
import useGraph from "../features/editor/views/GraphView/stores/useGraph";
import { isIframe } from "../lib/utils/helpers";
@@ -9,41 +10,7 @@ import { contentToJson, jsonToContent } from "../lib/utils/jsonAdapter";
import useConfig from "./useConfig";
import useJson from "./useJson";
-const defaultJson = JSON.stringify(
- {
- fruits: [
- {
- name: "Apple",
- color: "Red",
- nutrients: {
- calories: 52,
- fiber: "2.4g",
- vitaminC: "4.6mg",
- },
- },
- {
- name: "Banana",
- color: "Yellow",
- nutrients: {
- calories: 89,
- fiber: "2.6g",
- potassium: "358mg",
- },
- },
- {
- name: "Orange",
- color: "Orange",
- nutrients: {
- calories: 47,
- fiber: "2.4g",
- vitaminC: "53.2mg",
- },
- },
- ],
- },
- null,
- 2
-);
+const defaultJson = JSON.stringify(exampleJson, null, 2);
type SetContents = {
contents?: string;
@@ -101,7 +68,7 @@ const isURL = (value: string) => {
const debouncedUpdateJson = debounce((value: unknown) => {
useGraph.getState().setLoading(true);
useJson.getState().setJson(JSON.stringify(value, null, 2));
-}, 800);
+}, 400);
const useFile = create<FileStates & JsonActions>()((set, get) => ({
...initialStates,
diff --git a/src/types/graph.ts b/src/types/graph.ts
index 870207d8..428dd646 100644
--- a/src/types/graph.ts
+++ b/src/types/graph.ts
@@ -1,23 +1,26 @@
-import type { NodeType } from "jsonc-parser";
+import type { JSONPath, Node } from "jsonc-parser";
+
+export interface NodeRow {
+ key: string | null;
+ value: string | number | null;
+ type: Node["type"];
+ childrenCount?: number;
+ to?: string[];
+}
export interface NodeData {
id: string;
- text: string | [string, string][];
+ text: Array<NodeRow>;
width: number;
height: number;
- path?: string;
- data: {
- type: NodeType;
- isParent: boolean;
- isEmpty: boolean;
- childrenCount: number;
- };
+ path?: JSONPath;
}
export interface EdgeData {
id: string;
from: string;
to: string;
+ text: string | null;
}
export type LayoutDirection = "LEFT" | "RIGHT" | "DOWN" | "UP";