Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Collapse Nodes #96

Merged
merged 5 commits into from
Aug 27, 2022
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
46 changes: 44 additions & 2 deletions src/components/CustomNode/TextNode.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
import React from "react";
import { BiChevronLeft, BiChevronRight } from "react-icons/bi";
import { ConditionalWrapper, CustomNodeProps } from "src/components/CustomNode";
import useConfig from "src/hooks/store/useConfig";
import styled from "styled-components";
import * as Styled from "./styles";

const StyledExpand = styled.button`
pointer-events: all;
position: absolute;
display: flex;
align-items: center;
justify-content: center;
top: 0;
right: 0;
padding: 0;
color: ${({ theme }) => theme.TEXT_NORMAL};
background: rgba(0, 0, 0, 0.1);
min-height: 0;
height: 100%;
width: 40px;
border-radius: 0;
border-left: 1px solid ${({ theme }) => theme.BACKGROUND_MODIFIER_ACCENT};
`;

const TextNode: React.FC<CustomNodeProps<string>> = ({
width,
height,
Expand All @@ -12,21 +32,43 @@ const TextNode: React.FC<CustomNodeProps<string>> = ({
y,
}) => {
const performanceMode = useConfig((state) => state.performanceMode);
const expand = useConfig((state) => state.expand);
const [isExpanded, setIsExpanded] = React.useState(!expand);

React.useEffect(() => {
setIsExpanded(expand);
}, [expand]);

const handleExpand = (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
setIsExpanded(!isExpanded);
};

return (
<Styled.StyledForeignObject width={width} height={height} x={0} y={0}>
<ConditionalWrapper condition={performanceMode}>
<Styled.StyledText width={width} height={height}>
<Styled.StyledText parent={isParent} width={width} height={height}>
<Styled.StyledKey
data-x={x}
data-y={y}
data-key={JSON.stringify(value)}
parent={isParent}
>
<Styled.StyledLinkItUrl>{JSON.stringify(value).replaceAll('"', "")}</Styled.StyledLinkItUrl>
<Styled.StyledLinkItUrl>
{JSON.stringify(value).replaceAll('"', "")}
</Styled.StyledLinkItUrl>
</Styled.StyledKey>
</Styled.StyledText>
</ConditionalWrapper>
{isParent && (
<StyledExpand onClick={handleExpand}>
{isExpanded ? (
<BiChevronRight size={20} />
) : (
<BiChevronLeft size={20} />
)}
</StyledExpand>
)}
</Styled.StyledForeignObject>
);
};
Expand Down
7 changes: 6 additions & 1 deletion src/components/CustomNode/styles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,19 @@ export const StyledTextWrapper = styled.div`
cursor: pointer;
`;

export const StyledText = styled.pre<{ width: number; height: number }>`
export const StyledText = styled.pre<{
width: number;
height: number;
parent: boolean;
}>`
display: flex;
justify-content: center;
flex-direction: column;
width: ${({ width }) => width};
height: ${({ height }) => height};
min-height: 50;
color: ${({ theme }) => theme.TEXT_NORMAL};
padding-right: ${({ parent }) => parent && "20px"};
`;

export const StyledForeignObject = styled.foreignObject`
Expand Down
97 changes: 51 additions & 46 deletions src/components/Graph/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@ import {
TransformComponent,
TransformWrapper,
} from "react-zoom-pan-pinch";
import { Canvas, EdgeData, ElkRoot, NodeData, NodeProps } from "reaflow";
import { Canvas, Edge, ElkRoot, useSelection } from "reaflow";
import { CustomNode } from "src/components/CustomNode";
import { NodeModal } from "src/containers/Modals/NodeModal";
import { getEdgeNodes } from "src/containers/Editor/LiveEditor/helpers";
import useConfig from "src/hooks/store/useConfig";
import styled from "styled-components";
import shallow from "zustand/shallow";
import useNodeTools from "src/hooks/store/useNodeTools";

interface LayoutProps {
isWidget: boolean;
openModal: () => void;
setSelectedNode: (node: object) => void;
}

const StyledEditorWrapper = styled.div<{ isWidget: boolean }>`
Expand All @@ -33,14 +32,21 @@ const StyledEditorWrapper = styled.div<{ isWidget: boolean }>`
}
`;

const MemoizedGraph = React.memo(function Layout({
isWidget,
openModal,
setSelectedNode,
}: LayoutProps) {
const MemoizedGraph = React.memo(function Layout({ isWidget }: LayoutProps) {
const json = useConfig((state) => state.json);
const [nodes, setNodes] = React.useState<NodeData[]>([]);
const [edges, setEdges] = React.useState<EdgeData[]>([]);

const [nodes, edges, newNodes, newEdges, selectedNode] = useNodeTools(
(state) => [
state.nodes,
state.edges,
state.newNodes,
state.newEdges,
state.selectedNode,
],
shallow
);
const setNodeTools = useNodeTools((state) => state.setNodeTools);

const [size, setSize] = React.useState({
width: 2000,
height: 2000,
Expand All @@ -55,38 +61,34 @@ const MemoizedGraph = React.memo(function Layout({
React.useEffect(() => {
const { nodes, edges } = getEdgeNodes(json, expand);

setNodes(nodes);
setEdges(edges);
}, [json, expand]);
setNodeTools("nodes", nodes);
setNodeTools("edges", edges);
setNodeTools("newNodes", nodes);
setNodeTools("newEdges", edges);
}, [json, expand, setNodeTools]);

const onInit = (ref: ReactZoomPanPinchRef) => {
setConfig("zoomPanPinch", ref);
};

const onCanvasClick = () => {
const input = document.querySelector("input:focus") as HTMLInputElement;
if (input) input.blur();
};

const onLayoutChange = (layout: ElkRoot) => {
if (layout.width && layout.height)
setSize({ width: layout.width, height: layout.height });
};

const handleNodeClick = React.useCallback(
(e: React.MouseEvent<SVGElement>, props: NodeProps) => {
setSelectedNode(props.properties.text);
openModal();
const { selections, onClick, removeSelection } = useSelection({
nodes,
edges,
onSelection: (s) => {
if (!isWidget) {
if (s[0] === selectedNode) {
removeSelection(selectedNode);
} else {
setNodeTools("selectedNode", s[0]);
}
}
},
[openModal, setSelectedNode]
);

const node = React.useCallback(
(props) => (
<CustomNode onClick={(e) => handleNodeClick(e, props)} {...props} />
),
[handleNodeClick]
);
});

return (
<StyledEditorWrapper isWidget={isWidget}>
Expand All @@ -98,6 +100,9 @@ const MemoizedGraph = React.memo(function Layout({
wheel={{
step: 0.05,
}}
doubleClick={{
disabled: true,
}}
>
<TransformComponent
wrapperStyle={{
Expand All @@ -114,8 +119,11 @@ const MemoizedGraph = React.memo(function Layout({
direction={layout}
key={layout}
onLayoutChange={onLayoutChange}
onCanvasClick={onCanvasClick}
node={node}
selections={selections}
node={(props) => <CustomNode {...props} />}
edge={(props) =>
newEdges.find((e) => e.id === props.id) ? <Edge /> : <></>
}
zoomable={false}
readonly
/>
Expand All @@ -126,23 +134,20 @@ const MemoizedGraph = React.memo(function Layout({
});

export const Graph = ({ isWidget = false }: { isWidget?: boolean }) => {
const [isModalVisible, setModalVisible] = React.useState(false);
const [selectedNode, setSelectedNode] = React.useState<object>({});

const openModal = React.useCallback(() => setModalVisible(true), []);

const [newNodes, selectedNode, copySelectedNode] = useNodeTools(
(state) => [state.nodes, state.selectedNode, state.copySelectedNode],
shallow
);
const setNodeTools = useNodeTools((state) => state.setNodeTools);
const selectedNodeObject = newNodes.find((n) => n.id === selectedNode);
return (
<>
<MemoizedGraph
openModal={openModal}
setSelectedNode={setSelectedNode}
isWidget={isWidget}
/>
<MemoizedGraph isWidget={isWidget} />
{!isWidget && (
<NodeModal
selectedNode={selectedNode}
visible={isModalVisible}
closeModal={() => setModalVisible(false)}
selectedNode={selectedNodeObject?.text}
visible={copySelectedNode}
closeModal={() => setNodeTools("copySelectedNode", false)}
/>
)}
</>
Expand Down
2 changes: 1 addition & 1 deletion src/containers/Editor/LiveEditor/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function getEdgeNodes(
data: {
isParent: el.parent,
},
width: isExpanded ? 35 + longestLine * (el.parent ? 9 : 8) : 180,
width: isExpanded ? 35 + longestLine * 8 + (el.parent && 60) : 180,
height,
});
} else {
Expand Down
85 changes: 85 additions & 0 deletions src/containers/Editor/NodeTools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { NodeData, EdgeData, removeAndUpsertNodes } from "reaflow";
import { findNodeChildren } from "src/utils/findNodeChildren";
import toast from "react-hot-toast";
import { NodeTools } from "src/hooks/store/useNodeTools";
import { findEdgeChildren } from "src/utils/findEdgeChildren";

export const collapseNodes = (
selectedNode: string,
nodes: NodeData[],
edges: EdgeData[],
collapsedNodes: { [key: string]: NodeData[] },
collapsedEdges: { [key: string]: EdgeData[] },
setNodeTools: (key: keyof NodeTools, value: unknown) => void
) => {
if (selectedNode) {
const childrenOfNode = findNodeChildren(selectedNode, nodes, edges);
const childrenOfEdge = findEdgeChildren(
selectedNode,
childrenOfNode,
edges
);

const newCollapsedEdges = {};
newCollapsedEdges[selectedNode] = childrenOfEdge;
setNodeTools("collapsedEdges", {
...collapsedEdges,
...newCollapsedEdges,
});

const newCollapsedNodes = {};
newCollapsedNodes[selectedNode] = childrenOfNode;
setNodeTools("collapsedNodes", {
...collapsedNodes,
...newCollapsedNodes,
});

const resultOfRemovedNodes = removeAndUpsertNodes(
nodes,
edges,
childrenOfNode
);

const edgesResult = resultOfRemovedNodes.edges.filter((e) =>
e.id.startsWith("e")
);
setNodeTools("newNodes", resultOfRemovedNodes.nodes);
setNodeTools("newEdges", edgesResult);
setTimeout(() => toast.dismiss("restartToast"), 230);
} else {
toast("Please select a node to collapse!");
}
};

export const expandNodes = (
selectedNode: string,
nodes: NodeData[],
edges: EdgeData[],
collapsedNodes: { [key: string]: NodeData[] },
collapsedEdges: { [key: string]: EdgeData[] },
setNodeTools: (nodeTools: keyof NodeTools, value: unknown) => void
) => {
if (selectedNode) {
const concatEdges = edges.concat(collapsedEdges[selectedNode]);
const concatNodes = nodes.concat(collapsedNodes[selectedNode]);

setNodeTools("newNodes", concatNodes);
setNodeTools("newEdges", concatEdges);
} else {
toast("Please select a node to expand!");
}
};

export const restartNodes = (
initialNodes: NodeData[],
initialEdges: EdgeData[],
nodes: NodeData[],
setNodeTools: (nodeTools: keyof NodeTools, value: unknown) => void
) => {
if (nodes !== initialNodes) {
setNodeTools("newNodes", initialNodes);
setNodeTools("newEdges", initialEdges);
} else {
toast("Collapse at last once the node to restart!", { id: "restartToast" });
}
};
Loading