repeat node initial support

This commit is contained in:
ari committed 2022-07-13 10:52:56 -04:00
1 parent f392cf17fd
commit de2307901b
13 files changed
+301 -77

No files matched your search

@@ -14,6 +14,10 @@
} }
.dag-graphboard .react-flow__handle {
opacity: 0;
}
.dag-graphboard rect.react-flow__edge-textbg { .dag-graphboard rect.react-flow__edge-textbg {
fill: var(--mui-background-paper); fill: var(--mui-background-paper);
stroke: var(--mui-text-primary); stroke: var(--mui-text-primary);
@@ -2,7 +2,6 @@ import { DAGDims } from "./types";
export const NODE_WIDTH = 200 as const; export const NODE_WIDTH = 200 as const;
export const NODE_HEIGHT = 80 as const; export const NODE_HEIGHT = 80 as const;
export const CIRCLE_SIZE = 40 as const;
export const DEFAULT_DIMS: DAGDims = { export const DEFAULT_DIMS: DAGDims = {
trigger: { trigger: {
@@ -17,10 +16,6 @@ export const DEFAULT_DIMS: DAGDims = {
height: NODE_HEIGHT * 3, height: NODE_HEIGHT * 3,
width: NODE_WIDTH * 1.5, width: NODE_WIDTH * 1.5,
}, },
circle: {
height: CIRCLE_SIZE,
width: CIRCLE_SIZE,
},
distanceFactor: { distanceFactor: {
node: 1.5, node: 1.5,
collection: 1, collection: 1,
@@ -1,4 +1,4 @@
import { DAGDims, DAGEntities, Size } from "./types"; import { DAGDims, DAGEntities } from "./types";
import { XYPosition } from "react-flow-renderer"; import { XYPosition } from "react-flow-renderer";
export const moveAlong = ( export const moveAlong = (
@@ -22,26 +22,6 @@ export const moveAlong = (
return !dims.flipped ? moveOnX : moveOnY; return !dims.flipped ? moveOnX : moveOnY;
}; };
export const moveAlongOnce = (
by: keyof DAGEntities,
startPoint: XYPosition,
dims: DAGDims,
reversed: boolean = false
): XYPosition => {
const moveOnY = {
y: startPoint.y + dims[by].height * (dims.distanceFactor.node - 1),
x: startPoint.x,
};
const moveOnX = {
x: startPoint.x + dims[by].width * (dims.distanceFactor.node - 1),
y: startPoint.y,
};
if (reversed) {
return dims.flipped ? moveOnX : moveOnY;
}
return !dims.flipped ? moveOnX : moveOnY;
};
export const moveAlongRelativeTo = ( export const moveAlongRelativeTo = (
offsetPos: XYPosition, offsetPos: XYPosition,
relatedPos: XYPosition, relatedPos: XYPosition,
+101 -19
View File
@@ -14,7 +14,7 @@ import {
} from "types/automations"; } from "types/automations";
import { AutomationCondition } from "types/automations/conditions"; import { AutomationCondition } from "types/automations/conditions";
import { CollectionNodeMaker } from "../nodes/CollectionNode"; import { CollectionNodeMaker } from "../nodes/CollectionNode";
import { ChooseAction } from "types/automations/actions"; import { ChooseAction, RepeatAction } from "types/automations/actions";
import { XYPosition } from "react-flow-renderer"; import { XYPosition } from "react-flow-renderer";
import { DAGElementsOutputState } from "./outputState"; import { DAGElementsOutputState } from "./outputState";
import { SequenceNodeMaker } from "../nodes/SequenceNode"; import { SequenceNodeMaker } from "../nodes/SequenceNode";
@@ -31,7 +31,7 @@ export const useAutomationNodes = (
...args.dims, ...args.dims,
}; };
const state = useDAGElementsState(); const state = useDAGElementsState();
const outputState = new DAGElementsOutputState(); const outputState = new DAGElementsOutputState(dims.position, dims);
outputState.extend( outputState.extend(
makeTriggerNodes(automation.trigger, { makeTriggerNodes(automation.trigger, {
...args, ...args,
@@ -51,7 +51,7 @@ export const useAutomationNodes = (
position: distance.moveFromTo( position: distance.moveFromTo(
"trigger", "trigger",
"condition", "condition",
outputState.lastNodePos, outputState.getLastNodePos(),
dims dims
), ),
nodeId: `${dims.flipped}-condition`, nodeId: `${dims.flipped}-condition`,
@@ -68,7 +68,7 @@ export const useAutomationNodes = (
position: distance.moveFromTo( position: distance.moveFromTo(
"condition", "condition",
"node", "node",
outputState.lastNodePos, outputState.getLastNodePos(),
dims dims
), ),
nodeId: `${dims.flipped}-sequence`, nodeId: `${dims.flipped}-sequence`,
@@ -84,7 +84,7 @@ export const makeTriggerNodes: ElementMaker<AutomationTrigger> = (
nodes, nodes,
{ dims, namer, stateUpdater, nodeId, position } { dims, namer, stateUpdater, nodeId, position }
) => { ) => {
const outputState = new DAGElementsOutputState(); const outputState = new DAGElementsOutputState(position, dims);
outputState.addNode( outputState.addNode(
CollectionNodeMaker.makeElement({ id: nodeId, position }, dims, { CollectionNodeMaker.makeElement({ id: nodeId, position }, dims, {
...dims.trigger, ...dims.trigger,
@@ -104,7 +104,7 @@ export const makeConditionNodes: ElementMaker<AutomationCondition> = (
nodes, nodes,
{ nodeId, stateUpdater, position, dims, namer, lastNodeId } { nodeId, stateUpdater, position, dims, namer, lastNodeId }
) => { ) => {
const outputState = new DAGElementsOutputState(); const outputState = new DAGElementsOutputState(position, dims);
outputState.addNode( outputState.addNode(
CollectionNodeMaker.makeElement({ id: nodeId, position }, dims, { CollectionNodeMaker.makeElement({ id: nodeId, position }, dims, {
...dims.condition, ...dims.condition,
@@ -119,7 +119,7 @@ export const makeConditionNodes: ElementMaker<AutomationCondition> = (
}) })
); );
if (lastNodeId && outputState.lastNodeId) { if (lastNodeId && outputState.lastNodeId) {
outputState.addEdge(lastNodeId, outputState.lastNodeId, true); outputState.addEdge(lastNodeId, outputState.lastNodeId, { animated: true });
} }
return outputState; return outputState;
}; };
@@ -128,18 +128,19 @@ export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
nodes, nodes,
args args
) => { ) => {
const outputState = new DAGElementsOutputState();
const { lastNodeId, position, dims, namer, stateUpdater, state } = args; const { lastNodeId, position, dims, namer, stateUpdater, state } = args;
const outputState = new DAGElementsOutputState(position, dims);
nodes.forEach((node, nodeIndex) => { nodes.forEach((node, nodeIndex) => {
// the JSON.stringify is hack to make the edges render nicely // the JSON.stringify is hack to make the edges render nicely
const nodeId = `${args.nodeId}-${ const nodeId = `${args.nodeId}-${
args.nodeIndex args.nodeIndex
}-${nodeIndex}-${JSON.stringify(node)}`; }-${nodeIndex}-${JSON.stringify(node)}`;
outputState.incNextPos("node");
const element = outputState.addNode( const element = outputState.addNode(
SequenceNodeMaker.makeElement( SequenceNodeMaker.makeElement(
{ {
id: nodeId, id: nodeId,
position: distance.moveAlong("node", position, nodeIndex, dims), position: outputState.nextPos,
}, },
dims, dims,
{ {
@@ -163,8 +164,20 @@ export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
outputState.extend( outputState.extend(
makeChooseeNodes([node], { makeChooseeNodes([node], {
...args, ...args,
nodeId,
lastNodeId: element.id, lastNodeId: element.id,
position: outputState.lastNodePos, position: outputState.getLastNodePos(),
nodeIndex,
}),
true
);
} else if ("repeat" in node) {
outputState.extend(
makeRepeatNodes([node], {
...args,
nodeId,
lastNodeId: element.id,
position: outputState.getLastNodePos(),
nodeIndex, nodeIndex,
}), }),
true true
@@ -176,7 +189,12 @@ export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
ButtonNodeMaker.makeElement( ButtonNodeMaker.makeElement(
{ {
id: `${args.nodeId}-add-new`, id: `${args.nodeId}-add-new`,
position: distance.moveAlong("node", position, nodes.length, dims), position: distance.moveAlong(
"node",
outputState.getLastNodePos(position),
1,
dims
),
}, },
dims, dims,
{ {
@@ -195,7 +213,7 @@ export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
}; };
export const makeChooseeNodes: ElementMaker<ChooseAction> = (nodes, args) => { export const makeChooseeNodes: ElementMaker<ChooseAction> = (nodes, args) => {
const outputState = new DAGElementsOutputState(); const outputState = new DAGElementsOutputState(args.position, args.dims);
if (nodes.length !== 1) { if (nodes.length !== 1) {
throw new Error("makeChooseNodes only access a list of 1"); throw new Error("makeChooseNodes only access a list of 1");
} }
@@ -227,7 +245,7 @@ export const makeChooseeNodes: ElementMaker<ChooseAction> = (nodes, args) => {
nodeIndex: j, nodeIndex: j,
nodeId: `${args.nodeId}-choose-${j}-condition`, nodeId: `${args.nodeId}-choose-${j}-condition`,
}); });
conditionState.data.edges[0].label = `Condition #${j}`; conditionState.data.edges[0].label = `Condition #${j + 1}`;
outputState.extend(conditionState); outputState.extend(conditionState);
pos = distance.moveFromTo("condition", "node", pos, args.dims); pos = distance.moveFromTo("condition", "node", pos, args.dims);
lastNodeId = conditionState.lastNodeId; lastNodeId = conditionState.lastNodeId;
@@ -243,12 +261,10 @@ export const makeChooseeNodes: ElementMaker<ChooseAction> = (nodes, args) => {
nodeId: `${args.nodeId}-choose-${j}-sequence`, nodeId: `${args.nodeId}-choose-${j}-sequence`,
}); });
if (lastNodeId && output.data.nodes.length > 0) { if (lastNodeId && output.data.nodes.length > 0) {
outputState.addEdge( outputState.addEdge(lastNodeId, output.data.nodes[0].id, {
lastNodeId, animated: true,
output.data.nodes[0].id, label: j === "else" ? "else" : undefined,
true, });
j === "else" ? "else" : undefined
);
} }
offsetPos = distance.moveAlongRelativeTo( offsetPos = distance.moveAlongRelativeTo(
offsetPos, offsetPos,
@@ -269,3 +285,69 @@ export const makeChooseeNodes: ElementMaker<ChooseAction> = (nodes, args) => {
return outputState; return outputState;
}; };
export const makeRepeatNodes: ElementMaker<RepeatAction> = (nodes, args) => {
const outputState = new DAGElementsOutputState(args.position, args.dims);
if (nodes.length !== 1) {
throw new Error("makeChooseNodes only access a list of 1");
}
const node = nodes[0];
if (
(node.enabled ?? true) &&
!args.state.get(args.lastNodeId ?? "").isClosed
) {
// offset position
let offsetPos: XYPosition = {
x: args.position.x + args.dims.distanceFactor.node * args.dims.node.width,
y:
args.position.y + args.dims.distanceFactor.node * args.dims.node.height,
};
const stateUpdater = args.stateUpdater.createRepeatNodeUpdater(
args.nodeIndex
);
let pos = offsetPos;
let lastNodeId = args.lastNodeId;
const conditionState = makeConditionNodes(node.repeat.while, {
...args,
stateUpdater,
position: pos,
lastNodeId,
nodeIndex: 0,
nodeId: `${args.nodeId}-repeat-while`,
});
conditionState.data.edges[0].label = `While`;
outputState.extend(conditionState);
pos = distance.moveFromTo("condition", "node", pos, args.dims);
lastNodeId = conditionState.lastNodeId;
const sequenceState = makeSequenceNodes(node.repeat.sequence, {
...args,
stateUpdater,
position: pos,
lastNodeId: undefined,
nodeIndex: 0,
nodeId: `${args.nodeId}-repeat-sequence`,
});
if (lastNodeId && sequenceState.data.nodes.length > 0) {
outputState.addEdge(lastNodeId, sequenceState.data.nodes[0].id, {
animated: true,
label: "do",
});
}
offsetPos = distance.moveAlongRelativeTo(
offsetPos,
sequenceState.bbox[1],
args.dims,
"condition"
);
if (sequenceState.lastNodeId && conditionState.lastNodeId) {
outputState.addEdge(sequenceState.lastNodeId, conditionState.lastNodeId, {
animated: true,
label: "repeat",
targetHandle: "return",
});
}
outputState.extend(sequenceState);
}
return outputState;
};
@@ -1,6 +1,8 @@
import { MarkerType, Edge, XYPosition } from "react-flow-renderer";
import { DAGAutomationFlowNode } from "../nodes"; import { DAGAutomationFlowNode } from "../nodes";
import { addSize, pointApply } from "./math"; import { addSize, pointApply } from "./math";
import { Bbox, ElementData, LastNode } from "./types"; import { Bbox, DAGDims, DAGEntities, ElementData, LastNode } from "./types";
import { moveAlong } from "./distance";
export class DAGElementsOutputState { export class DAGElementsOutputState {
public data: ElementData = { public data: ElementData = {
@@ -13,6 +15,8 @@ export class DAGElementsOutputState {
{ x: 0, y: 0 }, { x: 0, y: 0 },
]; ];
constructor(public nextPos: XYPosition, public dims: DAGDims) {}
public extend( public extend(
other: DAGElementsOutputState, other: DAGElementsOutputState,
ignoreLastNode: boolean = false ignoreLastNode: boolean = false
@@ -23,6 +27,18 @@ export class DAGElementsOutputState {
this.bbox[1] = pointApply(this.bbox[1], other.bbox[1], Math.max); this.bbox[1] = pointApply(this.bbox[1], other.bbox[1], Math.max);
if (!ignoreLastNode) { if (!ignoreLastNode) {
this.lastNode = other.lastNode; this.lastNode = other.lastNode;
this.nextPos = (this.lastNode as any).pos;
}
if (this.dims.flipped) {
this.nextPos = {
y: Math.max(this.nextPos.y, other.bbox[1].y),
x: this.nextPos.x,
};
} else {
this.nextPos = {
x: Math.max(this.nextPos.x, other.bbox[1].x),
y: this.nextPos.y,
};
} }
} }
@@ -32,7 +48,9 @@ export class DAGElementsOutputState {
animatedEdge: boolean = false animatedEdge: boolean = false
) { ) {
if (addEdge && this.lastNodeId) { if (addEdge && this.lastNodeId) {
this.addEdge(this.lastNodeId, node.id, animatedEdge); this.addEdge(this.lastNodeId, node.id, {
animated: animatedEdge,
});
} }
this.data.nodes.push(node); this.data.nodes.push(node);
this.bbox[0] = pointApply(this.bbox[0], node.position, Math.min); this.bbox[0] = pointApply(this.bbox[0], node.position, Math.min);
@@ -52,18 +70,17 @@ export class DAGElementsOutputState {
return node; return node;
} }
public addEdge( public addEdge(from: string, to: string, edgeProps: Partial<Edge> = {}) {
from: string,
to: string,
animated: boolean = false,
label: string | undefined = undefined
) {
this.data.edges.push({ this.data.edges.push({
markerEnd: {
type: MarkerType.ArrowClosed,
width: 25,
height: 25,
},
...edgeProps,
id: `${from}->${to}`, id: `${from}->${to}`,
source: from, source: from,
target: to, target: to,
label,
animated,
}); });
} }
@@ -74,10 +91,20 @@ export class DAGElementsOutputState {
return undefined; return undefined;
} }
public get lastNodePos() { public getLastNodePos(orThis: XYPosition | undefined = undefined) {
if (this.lastNode) { if (this.lastNode) {
return this.lastNode.pos; return this.lastNode.pos;
} }
if (orThis) {
return orThis;
}
throw Error("missing lastnode"); throw Error("missing lastnode");
} }
public incNextPos(by: keyof DAGEntities) {
if (!this.lastNode) {
return;
}
this.nextPos = moveAlong(by, this.nextPos, 1, this.dims);
}
} }
@@ -7,7 +7,6 @@ export type DAGNodeState = Partial<{
export type DAGElementsState = ReturnType<typeof useDAGElementsState>; export type DAGElementsState = ReturnType<typeof useDAGElementsState>;
export const useDAGElementsState = () => { export const useDAGElementsState = () => {
const [data, setData] = useState<Record<string, DAGNodeState>>({}); const [data, setData] = useState<Record<string, DAGNodeState>>({});
console.log(data);
return { return {
get(nodeId: string): DAGNodeState { get(nodeId: string): DAGNodeState {
return data[nodeId] ?? {}; return data[nodeId] ?? {};
@@ -28,7 +27,7 @@ export const useDAGElementsState = () => {
}, },
getIsClosedActions(nodeId: string, node: AutomationNode) { getIsClosedActions(nodeId: string, node: AutomationNode) {
if ("choose" in node) { if ("choose" in node || "repeat" in node) {
return { return {
isClosed: this.get(nodeId).isClosed ?? false, isClosed: this.get(nodeId).isClosed ?? false,
setIsClosed: (v: boolean) => this.set(nodeId, "isClosed", v), setIsClosed: (v: boolean) => this.set(nodeId, "isClosed", v),
@@ -16,7 +16,6 @@ export type ElementData = {
export type DAGEntityDim = Size; export type DAGEntityDim = Size;
export type DAGEntities = { export type DAGEntities = {
node: DAGEntityDim; node: DAGEntityDim;
circle: DAGEntityDim;
condition: DAGEntityDim; condition: DAGEntityDim;
trigger: DAGEntityDim; trigger: DAGEntityDim;
}; };
@@ -30,6 +30,10 @@ export const ButtonNode: FC<ButtonNodeProps> = ({
position={flipped ? Position.Top : Position.Left} position={flipped ? Position.Top : Position.Left}
/> />
{icon} {icon}
<Handle
type="source"
position={!flipped ? Position.Bottom : Position.Right}
/>
</> </>
} }
onClick={onClick} onClick={onClick}
@@ -51,9 +51,6 @@
overflow: auto; overflow: auto;
} }
.collection-nodes .react-flow__handle {
opacity: 0;
}
.collection-nodes--total { .collection-nodes--total {
position: absolute; position: absolute;
@@ -17,7 +17,6 @@ export const CollectionNode: FC<CollectionNodeProps> = ({
width, width,
flipped, flipped,
color, color,
hasInput = false,
collectionType, collectionType,
}) => { }) => {
const nodeColor = useSequenceNodeColor(color); const nodeColor = useSequenceNodeColor(color);
@@ -54,13 +53,20 @@ export const CollectionNode: FC<CollectionNodeProps> = ({
type="source" type="source"
position={flipped ? Position.Bottom : Position.Right} position={flipped ? Position.Bottom : Position.Right}
/> />
{hasInput && ( <>
<Handle <Handle
id="default"
key="target" key="target"
type="target" type="target"
position={flipped ? Position.Top : Position.Left} position={flipped ? Position.Top : Position.Left}
/> />
)} <Handle
id="return"
key="target-return"
type="target"
position={!flipped ? Position.Top : Position.Right}
/>
</>
<span className="collection-nodes--total"> <span className="collection-nodes--total">
{nodes.length} node{nodes.length !== 1 ? "s" : ""} {nodes.length} node{nodes.length !== 1 ? "s" : ""}
</span> </span>
@@ -5,14 +5,18 @@ import { CollectionNode } from "./CollectionNode";
import { DAGGraphBoard } from "components/DAGGraph/board"; import { DAGGraphBoard } from "components/DAGGraph/board";
import { CollectionNodeMaker } from "./index"; import { CollectionNodeMaker } from "./index";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants"; import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { ButtonNodeMaker } from "../ButtonNode";
import { AddCircle } from "@mui/icons-material";
import { MarkerType } from "react-flow-renderer";
const Demo: FC<{ type DemoProps = {
height: number; height: number;
width: number; width: number;
totalChildNodes: number; totalChildNodes: number;
onAddNode: () => void; onAddNode: () => void;
enabledChild: boolean; enabledChild: boolean;
}> = (args) => { };
const Demo: FC<DemoProps> = (args) => {
return ( return (
<Page> <Page>
<DAGGraphBoard <DAGGraphBoard
@@ -124,3 +128,95 @@ Empty.args = {
...Empty.args, ...Empty.args,
totalChildNodes: 0, totalChildNodes: 0,
}; };
export const ReturnTarget: ComponentStory<typeof Demo> = (args) => {
return (
<Page>
<DAGGraphBoard
closeModal={() => {}}
state={{
ready: true,
data: {
elements: {
edges: [
{
id: "1",
source: "root",
target: "btn",
label: "1",
},
{
id: "2",
target: "root",
source: "btn",
animated: true,
targetHandle: "return",
label: "2",
markerEnd: {
type: MarkerType.ArrowClosed,
width: 25,
height: 25,
},
},
{
id: "3",
target: "root",
source: "btn",
label: "3",
},
],
nodes: [
ButtonNodeMaker.makeElement(
{
id: "btn",
position: {
x: 50 + (args.width - DEFAULT_DIMS.node.width) / 2,
y:
50 +
args.height *
2 *
DEFAULT_DIMS.distanceFactor.collection,
},
},
DEFAULT_DIMS,
{
icon: <AddCircle />,
onClick: () => {},
}
),
CollectionNodeMaker.makeElement(
{
id: "root",
position: {
x: 50,
y: 50,
},
},
DEFAULT_DIMS,
{
onAddNode: args.onAddNode,
width: args.width,
height: args.height,
nodes: [
{
enabled: args.enabledChild,
label: "condition",
},
...Array.from(Array(args.totalChildNodes)).map(
(_, i) => ({
enabled: true,
label: `Dummy Node #${i + 1}`,
})
),
],
collectionType: "condition",
}
),
],
},
},
}}
/>
</Page>
);
};
@@ -93,15 +93,15 @@ export const OnMoveAllDirections = Template.bind({});
OnMoveAllDirections.args = { OnMoveAllDirections.args = {
...OnMoveAllDirections.args, ...OnMoveAllDirections.args,
onMove: { onMove: {
up: console.log, up: console.info,
down: console.log, down: console.info,
left: console.log, left: console.info,
right: console.log, right: console.info,
}, },
onAdd: { onAdd: {
up: console.log, up: console.info,
down: console.log, down: console.info,
left: console.log, left: console.info,
right: console.log, right: console.info,
}, },
}; };
@@ -6,8 +6,7 @@ import { ModalState } from "../board/types";
import { SequenceNodeActions } from "../nodes/SequenceNode/types"; import { SequenceNodeActions } from "../nodes/SequenceNode/types";
import { DAGUpdaterArgs } from "./types"; import { DAGUpdaterArgs } from "./types";
import { mapAutoActionKeyToNodeType } from "./util"; import { mapAutoActionKeyToNodeType } from "./util";
import { ChooseAction } from "types/automations/actions"; import { ChooseAction, RepeatAction } from "types/automations/actions";
import { AutomationCondition } from "types/automations/conditions";
export const createBasicUpdater = export const createBasicUpdater =
<K extends keyof AutomationActionData, N extends AutomationActionData[K][0]>( <K extends keyof AutomationActionData, N extends AutomationActionData[K][0]>(
@@ -228,6 +227,42 @@ export const createUpdater = (
}); });
} }
}, },
createRepeatNodeUpdater(i: number) {
const { repeat } = args.sequence.data[i] as RepeatAction;
return createUpdater({
openModal: args.openModal,
condition: {
data: repeat.while ?? [],
onUpdate: (upd: any) =>
basic.sequence.updateNode(
{
repeat: {
...repeat,
while: upd,
},
},
i
),
},
sequence: {
data: repeat.sequence ?? [],
onUpdate: (upd) =>
basic.sequence.updateNode(
{
repeat: {
...repeat,
sequence: upd,
},
},
i
),
},
trigger: {
data: [],
onUpdate: console.warn,
},
});
},
}; };
}; };