cleaned up

This commit is contained in:
ari committed 2022-05-05 15:20:08 -04:00
1 parent c256400518
commit 6821bb8714
25 files changed
+23 -1837

No files matched your search

@@ -1,5 +1,5 @@
import "./AutoInfoBox.css";
import { AutomationData, AutomationMetadata } from "types/automations";
import { AutomationMetadata } from "types/automations";
import InputList from "components/Inputs/InputList";
import InputText from "components/Inputs/InputText";
import InputTextArea from "components/Inputs/InputTextArea";
@@ -41,6 +41,7 @@ export const AutoInfoBox: FC<Props> = ({
if (newName.length <= 0) {
return "Name must be at least 1 character long"
}
// eslint-disable-next-line
for (const [name, _] of tags) {
if (name.trim() === newName.trim()) {
return `The tag '${name}' already exists`
@@ -1,10 +1,8 @@
import "./index.css";
import { ArrowIcon, CheckMarkIcon, ZoomIcon } from "components/Icons";
import { ArrowIcon, CheckMarkIcon } from "components/Icons";
import { FC, useState } from "react";
import { AutomationData } from "types/automations";
import useWindowSize from "utils/useWindowSize";
import { AutoInfoBox } from "./AutoInfoBox";
import { useEditorStyles } from "./styles";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { Button } from "components/Inputs/Button";
import { useAutomatioEditorState } from "./state";
@@ -1,78 +0,0 @@
import { DAGElement } from "components/DAGSvgs/DAGBoard";
import { Point } from "types/graphs";
import { AutomationTrigger } from 'types/automations/triggers';
import { avgPoints } from "utils/graph";
export function* computeTriggerPos(
startPoint: Point,
triggers: AutomationTrigger[],
toPath: Point,
onUpdate: (ts: AutomationTrigger[]) => void,
onAdd: () => void,
onEdit: (nt: AutomationTrigger, onSave: (ts: AutomationTrigger) => void) => void,
): Generator<DAGElement> {
// functions
const makeRemoveNode = (i: number) => () => onUpdate([
...triggers.slice(0, i),
...triggers.slice(i + 1),
]);
const updateNode = (n: AutomationTrigger, i: number) => onUpdate([
...triggers.slice(0, i),
n,
...triggers.slice(i + 1),
])
// main loop
for (let i = 0; i < triggers.length; i++) {
const node = triggers[i];
const nodeLoc: Point = [startPoint[0], startPoint[1] + i];
yield {
type: "node",
node,
loc: nodeLoc,
onRemove: makeRemoveNode(i),
onOpen: () => onEdit(node, up => updateNode(up, i))
}
yield {
type: "edge",
p1: nodeLoc,
p2: toPath,
direction: "1->2",
}
}
// if we had nothing to loop on
if (triggers.length === 0) {
yield {
type: "edge",
p1: [startPoint[0] - 0.25, startPoint[1] + triggers.length],
p2: toPath,
direction: "1->2",
}
}
// add circle
yield {
type: 'circle',
icon: 'add',
loc: [startPoint[0] + 0.25, startPoint[1] + triggers.length],
onAdd
}
}
export function* computeExtraField(
triggerEndPos: Point,
sequenceStartPos: Point,
): Generator<DAGElement> {
yield {
type: 'circle',
loc: avgPoints(triggerEndPos, sequenceStartPos),
icon: 'color',
color: 'blue',
}
yield {
type: 'edge',
p1: triggerEndPos,
p2: sequenceStartPos,
direction: '1->2',
}
}
@@ -1,8 +1,8 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { ConnectedAutomationList } from ".";
import { NODE_HEIGHT, NODE_WIDTH, ADD_HEIGHT, ADD_WIDTH, CIRCLE_SIZE, DISTANCE_FACTOR } from 'components/DAGSvgs/constants';
import { createMockAuto } from "utils/mocks";
import { useMockApiService } from "apiService";
import * as dgconst from 'components/DAGSvgs/constants';
export default {
title: 'App/AutomationList/Connected',
@@ -10,12 +10,14 @@ export default {
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
dims: {
nodeHeight: NODE_HEIGHT,
nodeWidth: NODE_WIDTH,
addHeight: ADD_HEIGHT,
addWidth: ADD_WIDTH,
circleSize: CIRCLE_SIZE,
distanceFactor: DISTANCE_FACTOR,
nodeHeight: dgconst.NODE_HEIGHT,
nodeWidth: dgconst.NODE_WIDTH,
distanceFactor: dgconst.DISTANCE_FACTOR,
circleSize: dgconst.CIRCLE_SIZE,
padding: {
x: dgconst.PADDING,
y: dgconst.PADDING,
},
},
initialAutomations: [],
}
@@ -2,13 +2,12 @@ import "./index.css";
import { AutomationEditor } from "components/AutomationEditor";
import { FC, useState } from "react";
import { AutomationData } from "types/automations";
import { DAGBoardElmDims } from 'components/DAGSvgs/DAGBoard';
import { defaultAutomation } from '../../utils/defaults';
import { defaultAutomation } from 'utils/defaults';
import { ArrowIcon } from "components/Icons";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { ApiService } from "apiService/core";
import { AutomationListBox } from "./AutomationListBox";
import { DAGAutomationFlowDims } from 'DAGFlow/types';
import { DAGAutomationFlowDims } from 'components/DAGFlow/types';
interface AutomationListParams {
@@ -64,7 +63,7 @@ export const AutomationList: FC<AutomationListParams> = ({
}
interface ConnectedAutomationListParams {
dims: DAGBoardElmDims;
dims: DAGAutomationFlowDims;
api: ApiService;
}
export const ConnectedAutomationList: FC<ConnectedAutomationListParams> = ({
@@ -2,7 +2,6 @@ import { FC } from "react";
import { AddIcon, PencilIcon, TrashIcon } from '../Icons/index';
import { useCircleStyles } from './styles';
import { Handle, Position, XYPosition } from 'react-flow-renderer';
import { FlowData } from "./types";
+1 -1
View File
@@ -5,7 +5,7 @@ import { AutomationSequenceNode } from "types/automations";
import { AutomationTrigger } from 'types/automations/triggers';
import { triggerToFlow } from "./triggerConvertor";
import { DAGNode } from "./DAGNode";
import { DAGAutomationFlowDims, TriggerMakerOptions, FlowData, ModalState } from './types';
import { DAGAutomationFlowDims, FlowData, ModalState } from './types';
import { DAGCircle } from './DAGCircle';
import { sequenceToFlow } from "./sequenceConvertor";
import { makeSequenceUpdater } from "./updater";
@@ -1,11 +0,0 @@
.dag-svg--add-btn > a {
height: 100%;
width: 100%;
}
.dag-svg--add-btn > a:hover > svg {
fill: rgb(48, 189, 59);
}
.dag-svg--add-btn:hover {
cursor: pointer;
}
@@ -1,24 +0,0 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { SVGBoard } from './Board';
import { AddButton } from "./AddButton";
export default {
title: 'DAGSvgs/AddButton',
component: AddButton,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
height: 10,
width: 10,
loc: [50, 50]
}
} as ComponentMeta<typeof AddButton>
export const Basic: ComponentStory<typeof AddButton> = args => {
return <SVGBoard>
<AddButton
{...args}
/>
</SVGBoard>
}
@@ -1,24 +0,0 @@
import "./AddButton.css";
import { Point } from "types/graphs";
import { AddIcon } from '../Icons/index';
export interface AddProps {
onClick?: () => void;
loc: Point,
height: number,
width: number,
}
export const AddButton = ({
loc: [x, y],
height,
width,
onClick = () => { },
}: AddProps) => {
return <>
<foreignObject className="dag-svg--add-btn" x={x} y={y} width={width} height={height}>
<AddIcon onClick={onClick} />
</foreignObject>
</>
}
-51
View File
@@ -1,51 +0,0 @@
import { FC } from 'react';
import useWindowSize from "utils/useWindowSize";
import { useBoardStyles } from "./styles";
import { NODE_HEIGHT, NODE_WIDTH } from './constants';
export const SVGBoard: FC<{
graphHeight?: number,
minGraphWidth?: number,
nodeHeight?: number,
nodeWidth?: number,
zoomLevel?: number,
}> = ({
children,
graphHeight = 300,
minGraphWidth = 300,
nodeHeight = NODE_HEIGHT,
nodeWidth = NODE_WIDTH,
zoomLevel = 100,
}) => {
// state
const { ratioWbh } = useWindowSize();
// alias
const paddedZoomLevel = zoomLevel / 100;
const graphWidth = Math.max(
Math.round(graphHeight * ratioWbh),
minGraphWidth
);
const { classes, theme } = useBoardStyles({
boardHeight: Math.max(nodeHeight, graphHeight) * paddedZoomLevel,
boardWidth: Math.max(4 * nodeWidth, graphWidth) * paddedZoomLevel,
});
// render
return <div className={classes.dag} >
<svg
className={classes.svg}
viewBox={[0, 0, graphWidth / paddedZoomLevel, graphHeight / paddedZoomLevel].join(" ")}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
<marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5"
markerWidth="6" markerHeight="6"
orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill={theme.secondaryAccent} />
</marker>
</defs>
{children}
</svg>
</div>
}
@@ -1,160 +0,0 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { DAGBoard, DAGElement, DAGNodeElm } from "./DAGBoard";
import { NODE_HEIGHT, NODE_WIDTH, ADD_HEIGHT, ADD_WIDTH, DISTANCE_FACTOR, CIRCLE_SIZE } from './constants';
import { AutomationAction } from 'types/automations/actions';
export default {
title: 'DAGSvgs/DAGBoard',
component: DAGBoard,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
zoomLevel: 100,
settings: {
nodeHeight: NODE_HEIGHT,
nodeWidth: NODE_WIDTH,
addHeight: ADD_HEIGHT,
addWidth: ADD_WIDTH,
circleSize: CIRCLE_SIZE,
distanceFactor: DISTANCE_FACTOR,
edgeChildColor: 'blue',
edgeNextColor: 'white',
},
}
} as ComponentMeta<typeof DAGBoard>;
const nodeFromPoint = ([x, y, add = true]: any): DAGNodeElm => ({
type: 'node',
loc: [x, y],
onRemove() { },
onAdd: add ? () => { } : undefined,
node: ({
alias: `${x},${y}`,
"$smType": "action",
"action": "wait",
"action_data": {
"wait_template": "",
}
} as AutomationAction)
});
function* makeDummyData(pts: Array<any>, extras: DAGElement[]): Generator<DAGElement> {
for (const p of pts) {
yield nodeFromPoint(p);
};
for (const e of extras) {
yield e;
}
}
export const Simple: ComponentStory<typeof DAGBoard> = args => {
return <div className="page">
<DAGBoard {...args} />
</div>
}
Simple.args = {
...Simple.args,
elements: Array.from(makeDummyData(
[
[0, 0, false],
[1, 0, false],
[2, 1, false],
],
[
{
type: 'edge',
p1: [0, 0],
p2: [1, 0],
direction: '1->2'
},
{
type: 'edge',
p1: [2, 1],
p2: [2, 3],
direction: '1->2'
},
{
type: 'circle',
icon: 'blank',
loc: [2, 3]
},
{
type: 'edge',
p1: [2, 1],
p2: [2, 2],
direction: '1->2'
},
{
type: 'circle',
loc: [2, 2],
icon: 'color',
color: 'red',
}
]))
}
export const Complex: ComponentStory<typeof DAGBoard> = args => {
return <div className="page">
<DAGBoard {...args} />
</div>
}
Complex.args = {
...Complex.args,
elements: Array.from(makeDummyData(
[
[0, 0, false],
[1, 0, false],
[2, 1, false],
[4, 1],
[3, 2],
[2, 3],
[5, 0, false],
[6, 0],
[0, 6],
],
[
{
type: 'edge',
p1: [0, 0],
p2: [1, 0],
direction: '1->2'
},
{
type: 'edge',
p1: [2, 1],
p2: [4, 1],
direction: '1->2',
},
{
type: 'edge',
p1: [1, 0],
p2: [2, 1],
direction: '1->2',
},
{
type: 'edge',
p1: [2, 1],
p2: [3, 2],
direction: '1->2',
},
{
type: 'edge',
p1: [1, 0],
p2: [2, 3],
direction: '1->2',
},
{
type: 'edge',
p1: [1, 0],
p2: [5, 0],
direction: '1->2'
},
]
))
}
-205
View File
@@ -1,205 +0,0 @@
import { FC, useRef } from "react";
import { SVGBoard } from "./Board";
import { AutomationNode } from '../../types/automations/index';
import { Point, EdgeDirection, BBox } from 'types/graphs';
import { DAGNode } from "./DAGNode";
import { DAGEdge } from "./DAGEdge";
import { AddButton } from "./AddButton";
import { IteratorWrap } from "utils/iter";
import { DAGCircle, AddProps } from "./DAGCircle";
import { getDescriptionFromAutomationNode } from "utils/formatting";
import { minPoints } from "utils/graph";
import { maxPoints } from '../../utils/graph';
export type DAGCircleElm = {
type: 'circle';
loc: Point;
} & (
{
icon: 'add',
onAdd: () => void;
} |
{
icon: 'edit',
onEdit: () => void;
onRemove?: () => void;
} |
{
icon: 'blank',
onRemove?: () => void;
} |
{
icon: 'color',
color: string,
}
)
export interface DAGNodeElm {
type: 'node';
loc: Point;
node: AutomationNode;
onRemove: () => void;
onAdd?: () => void;
onOpen?: () => void;
}
export interface DAGEdgeElm {
type: 'edge';
p1: Point;
p2: Point;
direction: EdgeDirection;
fromCircle?: boolean;
onAdd?: () => void;
}
export type DAGElement = DAGEdgeElm | DAGNodeElm | DAGCircleElm;
export interface DAGBoardSettings extends DAGBoardElmDims {
edgeChildColor: string;
edgeNextColor: string;
}
export interface DAGBoardElmDims {
nodeHeight: number;
nodeWidth: number;
addHeight: number;
addWidth: number;
circleSize: number;
distanceFactor: number;
}
export interface Props {
elements: Generator<DAGElement> | Array<DAGElement>;
settings: DAGBoardSettings;
}
export function* mapDataToElements({
elements,
settings: st,
}: Props) {
let bbox: BBox = [[0, 0], [0, 0]];
const updateBBox = (p: Point) => {
bbox = [
[Math.min(bbox[0][0], p[0]), Math.min(bbox[0][1], p[1])],
[Math.max(bbox[1][0], p[0] + st.nodeWidth), Math.max(bbox[1][1], p[1] + st.nodeHeight)],
]
return p;
}
const offsetPoint = (
[x, y]: Point,
[ox, oy]: Point = [0, 0]
): Point => updateBBox([x + ox, y + oy]);
const mapWithNode = (
[x, y]: Point,
[ox, oy]: Point = [0, 0],
): Point => updateBBox([
x * st.nodeWidth * st.distanceFactor + ox,
y * st.nodeHeight * st.distanceFactor + oy,
])
for (let elm of elements) {
switch (elm.type) {
case 'node':
const nodeLoc = mapWithNode(elm.loc);
const addLoc = mapWithNode(elm.loc, [
st.nodeWidth * st.distanceFactor,
st.addHeight + st.addHeight / 2
])
yield <DAGNode
key={`(${elm.loc})-*`}
height={st.nodeHeight}
width={st.nodeWidth}
loc={nodeLoc}
text={getDescriptionFromAutomationNode(elm.node)}
color={elm.node.$smType === 'action' ? 'green' : 'blue'}
onXClick={elm.onRemove}
onOpenClick={elm.onOpen}
/>
if (elm.onAdd) {
yield <DAGEdge
key={`(${elm.loc})->+`}
p1={offsetPoint(nodeLoc, [st.nodeWidth, st.nodeHeight / 2])}
p2={offsetPoint(addLoc, [0, st.addHeight / 2])}
direction="1->2"
color={st.edgeNextColor}
/>
yield <AddButton
key={`(${elm.loc})-+`}
loc={addLoc}
height={st.addHeight}
width={st.addWidth}
onClick={elm.onAdd}
/>
}
break
case 'edge':
const p2 = mapWithNode(elm.p2, [0, st.nodeHeight / 2]);
let p1: Point;
if (elm.fromCircle) {
p1 = mapWithNode(elm.p1, [st.circleSize * 0.95, 1.3 * st.circleSize / 2])
} else {
p1 = mapWithNode(elm.p1, [st.nodeWidth, st.nodeHeight / 2])
}
yield <DAGEdge
key={`(${elm.p1})->(${elm.p2})`}
p1={p1}
p2={p2}
direction={elm.direction}
color={st.edgeNextColor}
/>
if (elm.onAdd) {
yield <AddButton
key={`(${elm.p2})-+`}
loc={offsetPoint(p2, [0, -st.addHeight / 2])}
height={st.addHeight}
width={st.addWidth}
onClick={elm.onAdd}
/>
}
break
case 'circle':
const loc = mapWithNode(elm.loc, [0, st.nodeHeight / 2 - st.circleSize / 2]);
const clickProps: Partial<AddProps> = {}
if (elm.icon === 'add') {
clickProps.onAdd = elm.onAdd;
} else if (elm.icon === 'edit') {
clickProps.onEdit = elm.onEdit
clickProps.onRemove = elm.onRemove
} else if (elm.icon === 'blank') {
clickProps.onRemove = elm.onRemove
} else {
clickProps.backgroundColor = elm.color
}
yield <DAGCircle
key={`(${elm.loc})-o`}
loc={loc}
size={st.circleSize}
{...clickProps}
/>
break
default:
break
}
}
return bbox;
}
export const DAGBoard: FC<Props & { zoomLevel: number }> = props => {
const graphDims = useRef<BBox>([[0, 0], [0, 0]]);
const it = new IteratorWrap(mapDataToElements(props));
const el = it.toArray();
const [p0, p1] = it.returnValue as BBox;
const [[x0, y0], [x1, y1]] = graphDims.current = [
minPoints(p0, graphDims.current[0]),
maxPoints(p1, graphDims.current[1])
];
return <SVGBoard
graphHeight={y1 - y0}
minGraphWidth={Math.max(x1 - x0, props.settings.nodeWidth * 8)}
nodeHeight={props.settings.nodeHeight}
nodeWidth={props.settings.nodeWidth}
zoomLevel={props.zoomLevel}
>
{el}
{props.children}
</SVGBoard>
}
@@ -1,46 +0,0 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { SVGBoard } from './Board';
import { DAGCircle } from "./DAGCircle";
export default {
title: 'DAGSvgs/DAGCircle',
component: DAGCircle,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
size: 20,
loc: [50, 50]
}
} as ComponentMeta<typeof DAGCircle>
export const Basic: ComponentStory<typeof DAGCircle> = args => {
return <SVGBoard>
<DAGCircle
size={args.size}
loc={args.loc}
/>
<DAGCircle
size={args.size}
loc={[args.loc[0] + args.size, args.loc[1]]}
onAdd={args.onAdd}
/>
<DAGCircle
size={args.size}
loc={[args.loc[0] + 2 * args.size, args.loc[1]]}
onEdit={args.onEdit}
/>
<DAGCircle
size={args.size}
loc={[args.loc[0] + 3 * args.size, args.loc[1]]}
onEdit={args.onEdit}
onRemove={args.onRemove}
/>
<DAGCircle
size={args.size}
loc={[args.loc[0] + 4 * args.size, args.loc[1]]}
onRemove={args.onRemove}
/>
</SVGBoard>
}
@@ -1,51 +0,0 @@
// import "./DAGCircle.css";
import { Point } from "types/graphs";
import { AddIcon, PencilIcon, TrashIcon } from '../Icons/index';
import { useCircleStyles } from './styles';
export interface AddProps {
onEdit?: () => void;
onAdd?: () => void;
onRemove?: () => void;
loc: Point,
size: number,
backgroundColor?: string;
}
export const DAGCircle = ({
loc: [x, y],
size,
onEdit,
onAdd,
onRemove,
backgroundColor,
}: AddProps) => {
const { classes } = useCircleStyles({
size: size * 0.9,
hasOnFunction: !!onEdit || !!onAdd,
hasRemoveFunction: !!onRemove,
backgroundColor,
});
return <>
<foreignObject x={x} y={y} width={size} height={size}>
<div className={classes.root}>
{
onEdit ?
<PencilIcon
size={70} units="%"
className={classes.icon}
onClick={onEdit}
/> : onAdd ?
<AddIcon
size={70} units="%"
className={classes.icon}
onClick={onAdd}
/>
: backgroundColor ? "" : "else"
}
{onRemove ? <TrashIcon className={classes.trashIcon} onClick={onRemove} /> : <></>}
</div>
</foreignObject>
</>
}
-59
View File
@@ -1,59 +0,0 @@
import { EdgeDirection, Point } from "types/graphs"
export interface EdgeProp {
p1: Point,
p2: Point,
direction: EdgeDirection,
color: string,
debug?: boolean,
}
export const DAGEdge = ({
p1: [x1, y1],
p2: [x2, y2],
direction,
color,
debug = false,
}: EdgeProp) => {
const [mx, my] = [(x1 + x2) / 2, (y1 + y2) / 2]
let [cx1, cy1] = [(x1 + mx) / 2, (y1 + my) / 2]
let [cx2, cy2] = [(x2 + mx) / 2, (y2 + my) / 2]
const l1 = Math.sqrt((cy1 - y1) ** 2 + (cx1 - x1) ** 2)
const l2 = Math.sqrt((cy2 - y2) ** 2 + (cx2 - x2) ** 2)
const theta = Math.atan2(y2 - y1, x2 - x1)
if ((theta < Math.PI / 2) && (theta > -Math.PI / 2)) {
cy1 = y1 - 0.5 * l1 * Math.sin(theta)
cx1 = x1 + 2 * l1 * Math.cos(theta)
cy2 = y2
cx2 = x2 - 3 * l2 * Math.cos(theta)
} else if ((theta > Math.PI / 2) && (theta < Math.PI)) {
cy2 += l2 * Math.sin(theta)
cx2 += 10 * l2 * Math.cos(theta)
cx1 -= 10 * l1 * Math.cos(theta)
}
return <>
{debug && <>
<circle cx={cx1} cy={cy1} r="5" fill="yellow" />
<line x1={cx1} y1={cy1} x2={x1} y2={y1} stroke="yellow" />
<line x1={cx1} y1={cy1} x2={x2} y2={y2} stroke="yellow" />
<circle cx={cx2} cy={cy2} r="5" fill="green" />
<line x1={cx2} y1={cy2} x2={x1} y2={y1} stroke="green" />
<line x1={cx2} y1={cy2} x2={x2} y2={y2} stroke="green" />
<text x={mx} y={my} stroke="white">{theta}</text>
</>}
<path stroke={color}
d={`M${x1} ${y1} C${cx1} ${cy1}, ${cx2} ${cy2}, ${x2} ${y2}`}
fill="none"
markerStart={
(direction === '1<-2' || direction === '1<->2') ?
"url(#arrow)" : ''
}
markerEnd={
(direction === '1->2' || direction === '1<->2') ?
"url(#arrow)" : ''
}
/>
</>
}
@@ -1,75 +0,0 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { DAGNode } from "./DAGNode";
import { SVGBoard } from './Board';
import { NODE_HEIGHT, NODE_WIDTH } from './constants';
import { DAGEdge } from "./DAGEdge";
const GRAPH_HEIGHT = 300;
export default {
title: 'DAGSvgs/DAGNode',
component: DAGNode,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
height: NODE_HEIGHT,
width: NODE_WIDTH,
text: "Test",
loc: [NODE_WIDTH * 2,GRAPH_HEIGHT / 2]
}
} as ComponentMeta<typeof DAGNode>;
export const Basic: ComponentStory<typeof DAGNode> = args => <SVGBoard
graphHeight={GRAPH_HEIGHT}
>
<DAGNode {...args}/>
</SVGBoard>
export const WithFromEdge: ComponentStory<typeof DAGNode> = args => <SVGBoard
graphHeight={GRAPH_HEIGHT}
>
<DAGNode {...args} />
</SVGBoard>
WithFromEdge.args = {
...(WithFromEdge.args ?? {}),
edge: {
color: 'white',
loc: [NODE_WIDTH * 4, NODE_HEIGHT * 2],
direction: '1->2',
}
}
export const WithToEdge: ComponentStory<typeof DAGNode> = args => <SVGBoard
graphHeight={GRAPH_HEIGHT}
>
<DAGNode {...args} edge={{
color: 'white',
loc: [args.loc[0] - args.width, args.loc[1] + args.height / 2],
direction: '1<-2',
}}/>
</SVGBoard>
export const WithManyEdges: ComponentStory<typeof DAGNode> = args => <SVGBoard
graphHeight={GRAPH_HEIGHT}
>
<DAGNode {...args} />
{[
// TODO: make it nicer to view when from behind
// [0, 0],
// [args.loc[0] - args.width, args.loc[1] + args.height / 2], // behind
// [args.loc[0] - 0.5*args.width, args.loc[1] + args.height ], // behind
// [args.loc[0], args.loc[1] + args.height ], // behind
// [args.loc[0], args.loc[1] + 2 * args.height ], // behind
[args.loc[0] + args.width / 2, args.loc[1] + 2 * args.height ], // below
[args.loc[0] + args.width, args.loc[1] + args.height * 2], // down
[args.loc[0] + args.width, args.loc[1] - args.height * 2], // up
[args.loc[0] + 2*args.width, args.loc[1] + args.height * 2], // down right
[args.loc[0] + 2*args.width, args.loc[1] + args.height / 2], // forward
[args.loc[0] + 2*args.width, args.loc[1] - args.height * 2], // up right
].map((p: any) => <DAGEdge
p1={[args.loc[0] + args.width, args.loc[1] + args.height / 2]}
p2={p}
direction="1->2"
color="white"
// debug
/>)}
</SVGBoard>
-75
View File
@@ -1,75 +0,0 @@
import Color from "chroma-js";
import { PencilIcon } from "components/Icons"
import { useNodeStyles } from "./styles"
import { EdgeDirection, Node, Point } from "types/graphs";
import { DAGEdge } from "./DAGEdge";
export interface NodeProp extends Node {
height: number;
width: number;
onXClick?: () => void;
onOpenClick?: () => void;
debug?: boolean;
edge?: {
color: string;
loc: Point;
direction: EdgeDirection;
}
}
export const DAGNode = ({
loc: [x, y],
text,
height,
width,
onXClick = () => { },
onOpenClick = () => { },
color,
edge,
debug = false,
}: NodeProp) => {
const { classes, theme } = useNodeStyles({
color,
nodeHeight: height,
nodeWidth: width,
});
return <>
<foreignObject x={x} y={y} width={width} height={height}>
<div className={classes.root}>
<div className={classes.inner}>
<div className={classes.leftEdge} onClick={onXClick}>
<button className={classes.buttonDelete}>X</button>
</div>
<div className={classes.textWrap}>
<span className={classes.text} title={text}>
{text}
</span>
</div>
<div className={classes.rightEdge} onClick={onOpenClick}>
<button className={classes.buttonEdit}>
<PencilIcon size={1.1} color={Color(theme.primary).set('rgb.g', 200).hex()} />
</button>
</div>
</div>
</div>
</foreignObject>
{
edge && (edge.direction === '1->2' ?
<DAGEdge
p1={[x + width, y + height / 2]}
p2={edge.loc}
direction={edge.direction}
color={edge.color}
debug={debug}
/> :
<DAGEdge
p1={[x, y + height / 2]}
p2={edge.loc}
direction={edge.direction}
color={edge.color}
debug={debug}
/>)
}
</>
}
+7 -9
View File
@@ -1,7 +1,3 @@
import { DAGBoardElmDims } from 'components/DAGSvgs/DAGBoard';
export const NODE_WIDTH = 150 as const;
export const NODE_HEIGHT = 60 as const;
export const ADD_HEIGHT = 10 as const;
@@ -10,11 +6,13 @@ export const CIRCLE_SIZE = 30 as const;
export const DISTANCE_FACTOR = 1.5 as const;
export const PADDING = 50 as const;
export const DEFAULT_DIMS: DAGBoardElmDims = {
export const DEFAULT_DIMS = {
nodeHeight: NODE_HEIGHT,
nodeWidth: NODE_WIDTH,
addHeight: ADD_HEIGHT,
addWidth: ADD_WIDTH,
circleSize: CIRCLE_SIZE,
distanceFactor: DISTANCE_FACTOR,
};
circleSize: CIRCLE_SIZE,
padding: {
x: PADDING,
y: PADDING,
},
}
-183
View File
@@ -1,183 +0,0 @@
import { Styles } from "jss";
import Color from 'chroma-js';
import { createAppUseStyles } from "styles/theme";
import { Node } from "types/graphs";
export const useBoardStyles = createAppUseStyles<{
boardHeight: number,
boardWidth: number,
}>(theme => ({
dag: {
borderWidth: 1,
borderStyle: 'solid',
borderColor: theme.secondaryAccent,
color: theme.primaryAccent,
background: theme.primary,
width: '100%',
height: '100%',
overflow: 'scroll'
},
svg: ({ boardHeight, boardWidth }) => ({
minHeight: `${boardHeight}px`,
minWidth: `${boardWidth}px`,
padding: 0,
margin: 0,
}),
circle: {
fill: Color(theme.secondary).set('rgb.b', 125).hex(),
},
infoBox: {
paddingLeft: '10px',
paddingRight: '10px',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
overflow: 'auto',
},
dagEdge: {
stroke: theme.secondaryAccent,
},
}))
export const useNodeStyles = createAppUseStyles<{
color: Node['color'],
nodeHeight: number,
nodeWidth: number,
}>(theme => {
const edgeStyle: Styles = {
flex: '1',
display: 'flex',
flexDirection: 'column',
flexWrap: 'nowrap',
borderRadius: '1em',
justifyContent: 'space-around',
alignItems: 'center',
'&:hover': {
backgroundColor: theme.primaryAccent,
cursor: 'pointer',
}
}
const buttonStyle: Styles = {
fontSize: '8px',
backgroundColor: "rgba(0,0,0,0)",
color: theme.primaryAccent,
borderStyle: 'none',
height: '15px',
width: '15px',
cursor: 'pointer',
}
return {
root: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
height: `100%`,
maxHeight: `100%`,
maxWidth: '100%',
width: '100%',
fontSize: 10,
},
inner: ({ color }) => ({
position: 'relative',
display: 'flex',
flexDirection: 'row',
backgroundColor: theme.secondary,
borderRadius: '1em',
flex: 1,
height: `100%`,
maxHeight: `100%`,
maxWidth: '100%',
marginTop: '2.5px',
marginBottom: '2.5px',
borderTopWidth: '1px',
borderTopStyle: 'solid',
borderTopLeftRadius: '10px',
borderTopRightRadius: '10px',
borderTopColor: color === 'red' ? Color(theme.secondary).set('rgb.r', 125).hex() :
color === 'blue' ? Color(theme.secondary).set('rgb.b', 125).hex() :
color === 'green' ? Color(theme.secondary).set('rgb.g', 125).hex() :
'none'
}),
textWrap: {
display: 'flex',
flex: 4,
textAlign: 'center',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
maxHeight: '100%',
maxWidth: "50%",
},
text: {
textOverflow: 'ellipsis',
overflow: "hidden",
whiteSpace: "break-spaces",
cursor: 'default',
},
buttonDelete: {
...buttonStyle,
"&:hover": {
color: theme.primary,
}
},
buttonEdit: {
...buttonStyle,
"&:hover": {
transform: "rotate(45deg)"
}
},
leftEdge: {
...edgeStyle,
borderLef: `1px ${theme.secondaryAccent} solid`,
borderTopRightRadius: 0,
borderBottomRightRadius: 0,
},
rightEdge: {
...edgeStyle,
borderRight: `1px ${theme.secondaryAccent} solid`,
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0,
},
}
})
export const useCircleStyles = createAppUseStyles<{
size: number,
hasOnFunction: boolean,
hasRemoveFunction: boolean,
backgroundColor?: string,
}>(theme => ({
root: ({ size, hasOnFunction, hasRemoveFunction, backgroundColor }) => {
const baseColor = backgroundColor ? backgroundColor : Color(theme.primary).set('rgb.g', 100).hex();
const hoverColor = (hasOnFunction && !hasRemoveFunction) ? Color(theme.primary).set('rgb.g', 150).hex() : baseColor
return {
backgroundColor: baseColor,
borderRadius: hasRemoveFunction ? 10 : 500,
height: size,
width: size,
cursor: hasOnFunction ? "pointer" : 'default',
"&:hover": {
backgroundColor: hoverColor,
},
fontSize: `${size * 0.4}px`,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}
},
icon: {
"&:hover": {
borderRadius: 500,
background: Color(theme.primary).set('rgb.g', 150).hex(),
}
},
trashIcon: {
padding: 1,
"&:hover": {
borderRadius: 500,
background: Color(theme.primary).set('rgb.g', 150).hex(),
cursor: 'pointer',
}
}
}))
@@ -1,328 +0,0 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { SequenceNodes } from './index';
import { NODE_HEIGHT, NODE_WIDTH, DISTANCE_FACTOR, ADD_HEIGHT, ADD_WIDTH, CIRCLE_SIZE } from '../DAGSvgs/constants';
import { useState } from 'react';
import { DAGElement } from "components/DAGSvgs/DAGBoard";
export default {
title: 'DAGSvgs/SequenceNodes',
component: SequenceNodes,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
zoomLevel: 100,
startPoint: [0.5, 0.5],
dims: {
nodeHeight: NODE_HEIGHT,
nodeWidth: NODE_WIDTH,
addHeight: ADD_HEIGHT,
addWidth: ADD_WIDTH,
circleSize: CIRCLE_SIZE,
distanceFactor: DISTANCE_FACTOR,
}
}
} as ComponentMeta<typeof SequenceNodes>
const Template: ComponentStory<typeof SequenceNodes> = args => {
const [state, setState] = useState(args.sequence)
return <SequenceNodes
{...args}
sequence={state}
onChange={setState}
/>
}
export const Simple = Template.bind({})
Simple.args = {
...Simple.args,
sequence: [
{
$smType: "condition",
condition: 'and',
condition_data: {
conditions: [
{
$smType: 'condition',
condition: 'numeric_state',
condition_data: {
entity_id: 'sensor.temperature_kitchen',
below: '15',
}
},
{
$smType: "condition",
condition: 'template',
condition_data: {
value_template: 'states(switch.kitchen_light) == "on"'
}
}
]
}
},
{
$smType: "action",
action: "service",
action_data: {
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
}
]
}
export const EmptyStart = Template.bind({})
EmptyStart.args = {
...EmptyStart.args,
sequence: [
]
}
export const AdditionalElemets = Template.bind({})
AdditionalElemets.args = {
...Simple.args,
additionalElements: function* (): Generator<DAGElement> {
yield {
type: 'circle',
loc: [1, 0],
icon: "blank"
}
yield {
type: 'edge',
p1: [0, 0],
p2: [1, 0],
direction: '1->2'
}
},
}
export const Multinode = Template.bind({})
Multinode.args = {
...Multinode.args,
sequence: [
{
$smType: "condition",
condition: 'and',
condition_data: {
conditions: [
{
$smType: 'condition',
condition: 'numeric_state',
condition_data: {
entity_id: 'sensor.temperature_kitchen',
below: '15',
}
},
{
$smType: "condition",
condition: 'template',
condition_data: {
value_template: 'states(switch.kitchen_light) == "on"'
}
}
]
}
},
{
$smType: "action",
action: "choose",
action_data: {
choose: [
{
conditions: [],
sequence: []
},
{
conditions: [
{
$smType: "condition",
condition: 'time',
condition_data: {
after: {
hours: 16,
minutes: 30
}
}
}
],
sequence: [
{
$smType: 'action',
action: 'event',
action_data: {
event: "superImportant_time",
event_data: {
time: '4:30PM'
}
}
}
]
},
{
conditions: [
{
$smType: "condition",
condition: 'time',
condition_data: {
after: {
hours: 18,
minutes: 45
}
}
}
],
sequence: [
{
$smType: 'action',
action: 'event',
action_data: {
event: "superImportant_time",
event_data: {
time: '6:45PM'
}
}
}
]
}
],
default: [],
}
},
{
$smType: 'action',
action: "service",
action_data: {
service: "light.turn_on",
data: {
entity_id: "light.kitchen"
}
}
} as any
]
}
export const DeepNested = Template.bind({})
DeepNested.args = {
...DeepNested.args,
sequence: [
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [{
"sequence": [{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": []
}
}],
"conditions": [],
}],
"default": [
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [
{
"sequence": [{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": []
}
}],
"conditions": [],
}
],
"default": [
]
}
},
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": []
}
}
]
}
},
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": []
}
}
]
}
export const SubsequentIssue = Template.bind({})
SubsequentIssue.args = {
...SubsequentIssue.args,
sequence: [{ "$smType": "condition", "condition": "and", "condition_data": { "conditions": [{ "$smType": "condition", "condition": "numeric_state", "condition_data": { "entity_id": "sensor.temperature_kitchen", "below": "15" } }, { "$smType": "condition", "condition": "template", "condition_data": { "value_template": "states(switch.kitchen_light) == \"on\"" } }] } }, { "$smType": "action", "action": "service", "action_data": { "alias": "Start Music In Kitchen", "service": "media_player.play_media", "target": { "entity_id": "media_player.kitchen_dot" }, "data": { "media_content_id": "Good Morning", "media_content_type": "SPOTIFY" } } }, { "$smType": "action", "action": "choose", "action_data": { "choose": [], "default": [{ "$smType": "action", "action": "choose", "action_data": { "choose": [], "default": [] } }] } }, { "$smType": "action", "action": "choose", "action_data": { "choose": [], "default": [] } }, { "$smType": "action", "action": "choose", "action_data": { "choose": [], "default": [] } }]
}
export const ChooseNestingIssue = Template.bind({})
ChooseNestingIssue.args = {
...ChooseNestingIssue.args,
sequence: [
{
"$smType": "condition",
"condition": "and",
"condition_data": {
"conditions": [
{
"$smType": "condition",
"condition": "numeric_state",
"condition_data": {
"entity_id": "sensor.temperature_kitchen",
"below": "15"
}
},
{
"$smType": "condition",
"condition": "template",
"condition_data": {
"value_template": "states(switch.kitchen_light) == \"on\""
}
}
]
}
},
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": [
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": []
}
}
]
}
}
]
}
@@ -1,82 +0,0 @@
import { DAGBoard } from "components/DAGSvgs/DAGBoard";
import { FC, useState } from "react";
import { useTheme } from "styles/theme";
import { SequenceNodeProps, ModalState } from './types';
import Color from 'chroma-js';
import { computeNodesEdgesPos } from './positions';
import { Modal } from 'components/Modal';
import { NodeEditor } from 'components/NodeEditor';
import { MultiNodeEditor } from "components/MultiNodeEditors";
import { chain } from "utils/iter";
export const SequenceNodes: FC<SequenceNodeProps & { zoomLevel: number }> = (props) => {
// state
const theme = useTheme();
const [modalState, setModalState] = useState<ModalState | null>(null);
// modal
let modalBody = <></>
if (modalState) {
if (modalState.single) {
modalBody = <NodeEditor
node={modalState.node}
onClose={() => setModalState(null)}
onSave={n => { modalState.update(n as any); setModalState(null) }}
allowedTypes={modalState.onlyConditions ? ['condition'] : ['action', 'condition']}
saveBtnCreateText={modalState.saveBtnCreateText}
/>
} else {
modalBody = <MultiNodeEditor
sequence={modalState.node}
onClose={() => setModalState(null)}
onSave={(i, n) => {
modalState.update([
...modalState.node.slice(0, i),
n as any,
...modalState.node.slice(i + 1),
]); setModalState(null)
}}
onAdd={(n, slide) => {
modalState.update([...modalState.node, n as any]);
slide(modalState.node.length)
}}
onRemove={(i, slide) => {
modalState.update([
...modalState.node.slice(0, i),
...modalState.node.slice(i + 1),
]);
slide(modalState.node.length - 2);
}}
allowedTypes={modalState.onlyConditions ? ['condition'] : ['action', 'condition']}
/>
}
}
// compute elemets
let elmIter = computeNodesEdgesPos(
props.startPoint,
props.sequence,
props.onChange,
s => setModalState(s)
);
if (props.additionalElements) {
elmIter = chain([elmIter, props.additionalElements()]);
}
// render
return <>
<DAGBoard
zoomLevel={props.zoomLevel}
elements={elmIter}
settings={{
...props.dims,
edgeNextColor: theme.secondaryAccent,
edgeChildColor: Color(theme.secondaryAccent).set('rgb.b', 200).hex(),
}}
children={props.children}
/>
<Modal open={!!modalState}>
{modalBody}
</Modal>
</>
}
@@ -1,240 +0,0 @@
import { DAGElement } from "components/DAGSvgs/DAGBoard";
import { AutomationSequenceNode } from "types/automations";
import { Point } from "types/graphs";
import { makeUpdater, Updater } from './updater';
import { ChooseAction } from 'types/automations/actions';
import { AutomationCondition } from "types/automations/conditions";
import { UpdateModalState } from "./types";
import { offsetPoint, makeOffsetMaintainer} from "utils/graph";
function* dealWithNested(
nodeLoc: Point,
innerStartLoc: Point,
updater: Updater,
sequence: AutomationSequenceNode[],
openModal: UpdateModalState,
onEdit?: () => void,
onRemove?: () => void,
): Generator<DAGElement> {
const np = offsetPoint(innerStartLoc, [0.5, 0]);
yield {
type: 'edge',
p1: nodeLoc,
p2: innerStartLoc,
direction: '1->2',
}
if (onEdit) {
yield {
type: 'circle',
loc: innerStartLoc,
icon: 'edit',
onEdit,
onRemove,
}
} else {
yield {
type: 'circle',
loc: innerStartLoc,
icon: 'blank',
onRemove,
}
}
yield {
type: 'edge',
p1: innerStartLoc,
p2: np,
direction: '1->2',
onAdd: sequence.length === 0 ? updater.addNode : undefined,
fromCircle: true,
}
for (let childNode of computeNodesEdgesPos(
np,
sequence,
updater.onChange,
openModal,
)) {
yield childNode
}
}
function* dealWithChoose(
node: ChooseAction,
nodeLoc: Point,
makeUpdater: (j: number | null) => Updater,
updateData: (data: ChooseAction['action_data']) => void,
openModal: UpdateModalState,
offset: ReturnType<typeof makeOffsetMaintainer>,
): Generator<DAGElement> {
offset.resetY()
// conditions
for (let j = 0; j < node.action_data.choose.length; j++) {
const innerStartLoc = offsetPoint(nodeLoc, [1, j + 1 + offset.y]);
const updater = makeUpdater(j);
for (let elm of dealWithNested(
nodeLoc,
innerStartLoc ,
updater,
node.action_data.choose[j].sequence,
openModal,
onModalOpenForConditions(
openModal, j,
node.action_data,
updateData,
),
createOnRemoveForChooseNode(node.action_data, updateData, j)
)) {
yield elm
if (elm.type === 'node') {
offset.update(elm.loc, innerStartLoc)
}
if (elm.type === 'circle') {
offset.update(offsetPoint(elm.loc, [0, -1]), innerStartLoc)
}
}
}
// default
const innerStartLoc = offsetPoint(
nodeLoc,
[1, node.action_data.choose.length + 2 + offset.y],
);
for (let elm of dealWithNested(
nodeLoc,
innerStartLoc,
makeUpdater(null),
node.action_data.default,
openModal
)) {
yield elm
if (elm.type === 'node') {
offset.update(elm.loc, innerStartLoc)
}
}
// add new conditions
const newCondLoc = offsetPoint(
nodeLoc,
[1, node.action_data.choose.length + 2.5 + offset.y],
);
yield {
type: 'circle',
loc: newCondLoc,
icon: 'add',
onAdd: () => updateData({
...node.action_data,
choose: [
...node.action_data.choose,
{
conditions: [],
sequence: [],
}
]
}),
}
}
export function* computeNodesEdgesPos(
startPoint: Point,
sequence: AutomationSequenceNode[],
onChange: (s: AutomationSequenceNode[]) => void,
openModal: UpdateModalState,
): Generator<DAGElement> {
const rootUpdater = makeUpdater(sequence, onChange, openModal);
const offset = makeOffsetMaintainer(startPoint);
if (sequence.length === 0) {
yield {
type: "circle",
icon: 'add',
loc: offsetPoint(startPoint, [offset.x, 0]),
onAdd: rootUpdater.addNode,
}
return
}
let lastNodeLoc: Point | null = null;
for (let i = 0; i < sequence.length; i++) {
offset.setI(i)
const node = sequence[i];
const nodeLoc = offsetPoint(startPoint, [i + offset.x, 0]);
yield {
type: 'node',
loc: nodeLoc,
node,
onOpen: onModalOpenForNode(openModal, i, node, rootUpdater),
onRemove: () => rootUpdater.removeNode(i),
onAdd: i === sequence.length - 1 ? rootUpdater.addNode : undefined,
}
if (lastNodeLoc) {
yield {
type: 'edge',
p1: lastNodeLoc,
p2: nodeLoc,
direction: '1->2',
}
}
lastNodeLoc = [...nodeLoc];
if (
(node.$smType === 'action') && (node.action === 'choose')
) {
yield* dealWithChoose(
node,
nodeLoc,
j => rootUpdater.makeChildUpdaterForChooseAction(i, j),
actionData => rootUpdater.updateChooseActionData(i, actionData),
openModal,
offset,
)
}
}
}
export const onModalOpenForNode = (
openModal: UpdateModalState,
i: number,
node: AutomationSequenceNode,
rootUpdater: Updater,
) => () => openModal({
single: true,
node,
onlyConditions: false,
update: n => rootUpdater.updateNode(i, n),
})
export const onModalOpenForConditions = (
openModal: UpdateModalState,
j: number,
data: ChooseAction['action_data'],
updateData: (data: ChooseAction['action_data']) => void,
) => () => openModal({
single: false,
node: data.choose[j].conditions,
onlyConditions: true,
update: conditions => updateData({
...data,
choose: [
...data.choose.slice(0, j),
{
sequence: data.choose[j].sequence,
conditions: conditions as AutomationCondition[],
},
...data.choose.slice(j+1),
]
}),
})
const createOnRemoveForChooseNode = (
data: ChooseAction['action_data'],
updateData: (data: ChooseAction['action_data']) => void,
j: number
) => () => updateData({
...data,
choose: [
...data.choose.slice(0, j),
...data.choose.slice(j+1),
]
})
@@ -1,28 +0,0 @@
import { DAGBoardElmDims, DAGElement } from "components/DAGSvgs/DAGBoard";
import { AutomationSequenceNode } from "types/automations";
import { Point } from "types/graphs";
export type UpdateModalState = (
s: ModalState
) => void;
export interface SequenceNodeProps {
startPoint: Point;
dims: DAGBoardElmDims;
sequence: AutomationSequenceNode[],
onChange: (s: AutomationSequenceNode[]) => void;
additionalElements?: () => Generator<DAGElement>;
}
export type ModalState = {
single: true,
node: AutomationSequenceNode
update: (n: AutomationSequenceNode) => void;
saveBtnCreateText?: boolean;
onlyConditions: boolean;
} | {
single: false,
node: AutomationSequenceNode[]
update: (n: AutomationSequenceNode[]) => void;
onlyConditions: boolean;
}
@@ -1,91 +0,0 @@
import { AutomationSequenceNode } from "types/automations";
import { ChooseAction } from "types/automations/actions";
import { UpdateModalState } from "./types";
export type Updater = ReturnType<typeof makeUpdater>;
export const makeUpdater = (
sequence: AutomationSequenceNode[],
onChange: (s: AutomationSequenceNode[]) => void,
openModal: UpdateModalState,
) => ({
sequence,
onChange,
removeNode(i: number) {
return onChange([
...sequence.slice(0, i),
...sequence.slice(i + 1),
])
},
addNode() {
return openModal({
single: true,
saveBtnCreateText: true,
node: {
$smType: 'action',
action: 'choose',
action_data: {
choose: [],
default: [],
}
},
update: n => onChange([
...sequence,
n,
]),
onlyConditions: false,
})
},
updateNode(i: number, node: AutomationSequenceNode) {
return onChange([
...sequence.slice(0, i),
node,
...sequence.slice(i + 1),
])
},
updateChooseActionData(i: number, data: ChooseAction['action_data']) {
const node = sequence[i] as ChooseAction;
return this.updateNode(i, {
...node,
action_data: data,
})
},
makeChildUpdaterForChooseAction(i: number, j: number | null) {
const node = sequence[i];
if ((node.$smType === 'action') && (node.action === 'choose')) {
if (j !== null) {
return makeUpdater(
node.action_data.choose[j].sequence,
seq => this.updateNode(i, {
...node,
action_data: {
...node.action_data,
choose: [
...node.action_data.choose.slice(0, j),
{
...node.action_data.choose[j],
sequence: seq,
},
...node.action_data.choose.slice(j + 1),
]
}
}),
openModal,
)
} else {
return makeUpdater(
node.action_data.default,
seq => this.updateNode(i, {
...node,
action_data: {
...node.action_data,
default: seq
}
}),
openModal,
)
}
}
throw new Error(`Cannot create sub-updater for ${node}`)
}
});