stable editor

This commit is contained in:
ari committed 2022-05-05 13:48:51 -04:00
1 parent b29596fe78
commit a56c7ff964
18 files changed
+832 -433

No files matched your search

+3 -1
View File
@@ -44,7 +44,9 @@ export const DAGNode: FC<{ data: DAGNodeProps }> = ({
{label}
</span>
</div>
<div className={classes.rightEdge} onClick={onEditClick}>
<div className={classes.rightEdge} onClick={() => {
console.log('editing me', label, onEditClick, onEditClick())
}}>
<button className={classes.buttonEdit}>
<PencilIcon size={1.1} color={Color(theme.primary).set('rgb.g', 200).hex()} />
</button>
+233 -283
View File
@@ -2,15 +2,14 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { DAGFlow } from '.';
import { DAGAutomationFlow } from '.';
import { useState } from 'react';
import * as dgconst from "components/DAGSvgs/constants";
import { makeAumationStateEditor } from '../../utils/AutomationState';
export default {
title: 'DAGFlow/Viewer',
component: DAGFlow,
title: 'DAGAutomationFlow/Viewer',
component: DAGAutomationFlow,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
dims: {
@@ -24,26 +23,23 @@ export default {
},
}
}
} as ComponentMeta<typeof DAGFlow>
} as ComponentMeta<typeof DAGAutomationFlow>
const Template: ComponentStory<typeof DAGFlow> = args => {
const [state, setState] = useState(args.automation)
const triggerEditor = makeAumationStateEditor(state, setState).triggers;
const Template: ComponentStory<typeof DAGAutomationFlow> = args => {
const [state, setState] = useState({
trigger: args.trigger,
sequence: args.sequence,
})
console.log(state)
return <div className="page">
<DAGFlow
<DAGAutomationFlow
{...args}
automation={state}
opts={{
triggers: {
onAdd: () => triggerEditor.add({
platform: 'event',
$smType: 'trigger',
event_type: 'test',
}),
onDelete: triggerEditor.delete,
onEdit: () => { },
}
{...state}
onTriggerUpdate={trigger => {
console.log({ trigger })
setState({ ...state, trigger })
}}
onSequenceUpdate={sequence => setState({ ...state, sequence })}
/>
</div>
}
@@ -51,290 +47,244 @@ const Template: ComponentStory<typeof DAGFlow> = args => {
export const Simple = Template.bind({})
Simple.args = {
...Simple.args,
automation: {
tags: {
"Room": "Bathroom",
"For": "Toliet",
"Type": "Smell",
"Use": "Flushing"
trigger: [
{
"$smType": undefined,
"platform": "numeric_state",
"entity_id": "test",
},
metadata: {
id: "random",
alias: "Random",
description: "Example Metadata",
trigger_variables: {
'wowo': '!'
},
mode: 'single',
},
trigger: [
{
"$smType": undefined,
"platform": "numeric_state",
"entity_id": "test",
},
{
"$smType": undefined,
"platform": "homeassistant",
"event": "start",
}
],
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": undefined,
"platform": "homeassistant",
"event": "start",
}
],
sequence: [
{
$smType: "condition",
condition: 'and',
condition_data: {
conditions: [
{
$smType: 'condition',
condition: 'numeric_state',
condition_data: {
entity_id: 'sensor.temperature_kitchen',
below: '15',
}
]
}
},
{
$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: "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 Complex = Template.bind({})
Complex.args = {
...Complex.args,
automation: {
tags: {
"Room": "Bathroom",
"For": "Toliet",
"Type": "Smell",
"Use": "Flushing"
trigger: [
{
"$smType": undefined,
"platform": "numeric_state",
"entity_id": "test",
},
metadata: {
id: "random",
alias: "Random",
description: "Example Metadata",
trigger_variables: {
'wowo': '!'
},
mode: 'single',
},
trigger: [
{
"$smType": undefined,
"platform": "numeric_state",
"entity_id": "test",
},
{
"$smType": undefined,
"platform": "homeassistant",
"event": "start",
}
],
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": undefined,
"platform": "homeassistant",
"event": "start",
}
],
sequence: [
{
"$smType": "condition",
"condition": "and",
"condition_data": {
"conditions": [
{
"$smType": "condition",
"condition": "numeric_state",
"condition_data": {
"entity_id": "sensor.temperature_kitchen",
"below": "15"
}
]
}
},
{
"$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": "condition",
"condition": "template",
"condition_data": {
"value_template": "states(switch.kitchen_light) == \"on\""
}
}
}
},
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [
{
"conditions": [
{
"$smType": "condition",
"condition": "state",
"condition_data": {
"entity_id": "lights.bathroom",
"state": "off",
}
}
],
"sequence": [
{
"$smType": "action",
"action": "service",
"action_data": {
"service": "light.turn_on",
"target": {
"entity_id": "lights.bathroom"
},
"data": {}
}
},
{
"$smType": "action",
"action": "service",
"action_data": {
"alias": "Turn off bedroom",
"service": "light.turn_off",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
}
}
]
},
{
"conditions": [
{
"$smType": "condition",
"condition": "state",
"condition_data": {
"entity_id": "lights.bedroom",
"state": "off",
}
}
],
"sequence": [
{
"$smType": "action",
"action": "service",
"action_data": {
"alias": "Turn on bedroom",
"service": "light.turn_on",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
}
},
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [
{
"conditions": [],
"sequence": [
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": [],
}
}
]
}
],
"default": [
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": [],
}
}
],
}
}
]
}
],
"default": [
{
"$smType": "action",
"action": "service",
"action_data": {
"service": "light.turn_off",
"target": {
"entity_id": "lights.bathroom"
},
"data": {}
}
}
]
}
},
{
"$smType": "condition",
"condition": "and",
"condition_data": {
"conditions": []
]
}
},
{
"$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": [
{
"conditions": [
{
"$smType": "condition",
"condition": "state",
"condition_data": {
"entity_id": "lights.bathroom",
"state": "off",
}
}
],
"sequence": [
{
"$smType": "action",
"action": "service",
"action_data": {
"service": "light.turn_on",
"target": {
"entity_id": "lights.bathroom"
},
"data": {}
}
},
{
"$smType": "action",
"action": "service",
"action_data": {
"alias": "Turn off bedroom",
"service": "light.turn_off",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
}
}
]
},
{
"conditions": [
{
"$smType": "condition",
"condition": "state",
"condition_data": {
"entity_id": "lights.bedroom",
"state": "off",
}
}
],
"sequence": [
{
"$smType": "action",
"action": "service",
"action_data": {
"alias": "Turn on bedroom",
"service": "light.turn_on",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
}
},
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [
{
"conditions": [],
"sequence": [
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": [],
}
}
]
}
],
"default": [
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": [],
}
}
],
}
}
]
}
],
"default": [
{
"$smType": "action",
"action": "service",
"action_data": {
"service": "light.turn_off",
"target": {
"entity_id": "lights.bathroom"
},
"data": {}
}
}
]
}
},
{
"$smType": "condition",
"condition": "and",
"condition_data": {
"conditions": []
}
}
]
}
export const EmptyStart = Template.bind({})
EmptyStart.args = {
...EmptyStart.args,
automation: {
tags: {},
metadata: {
id: "random",
alias: "Random",
description: "Example Metadata",
trigger_variables: {
'wowo': '!'
},
mode: 'single',
},
trigger: [
],
sequence: []
}
trigger: [
],
sequence: []
}
+84 -16
View File
@@ -1,12 +1,17 @@
import { FC } from "react";
import { FC, useState } from "react";
import ReactFlow, { MiniMap, Controls } from 'react-flow-renderer';
import { AutomationData } from "types/automations";
import { AutomationSequenceNode } from "types/automations";
import { AutomationTrigger } from 'types/automations/triggers';
import { triggerToFlow } from "./triggerConvertor";
import { DAGNode } from "./DAGNode";
import { DAGFlowDims, TriggerMakerOptions, FlowData } from './types';
import { DAGAutomationFlowDims, TriggerMakerOptions, FlowData, ModalState } from './types';
import { DAGCircle } from './DAGCircle';
import { sequenceToFlow } from "./sequenceConvertor";
import { makeSequenceUpdater } from "./updater";
import { NodeEditor } from "components/NodeEditor";
import { MultiNodeEditor } from "components/MultiNodeEditors";
import { Modal } from "components/Modal";
const nodeTypes = {
'dagnode': DAGNode,
@@ -14,26 +19,89 @@ const nodeTypes = {
}
interface Props {
automation: AutomationData;
dims: DAGFlowDims;
opts: {
triggers: TriggerMakerOptions;
}
sequence: AutomationSequenceNode[];
trigger: AutomationTrigger[];
dims: DAGAutomationFlowDims;
onTriggerUpdate: (t: AutomationTrigger[]) => void;
onSequenceUpdate: (s: AutomationSequenceNode[]) => void;
}
export const DAGFlow: FC<Props> = ({
automation,
opts,
export const DAGAutomationFlow: FC<Props> = ({
sequence,
trigger,
onTriggerUpdate,
onSequenceUpdate,
dims,
}) => {
// state
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.allowedTypes}
saveBtnCreateText={modalState.saveBtnCreateText}
/>
} else {
modalBody = <MultiNodeEditor
sequence={modalState.node}
onClose={() => setModalState(null)}
onSave={(n) => {
modalState.update(n as any);
setModalState(null);
}}
allowedTypes={['condition']}
/>
}
}
// convert automation to flow data
const condPoint = makeConditionPoint(dims);
const flowData: FlowData = {
nodes: [condPoint],
edges: [],
}
triggerToFlow(flowData, automation.trigger, condPoint.id, dims, opts.triggers);
sequenceToFlow(flowData, automation.sequence, condPoint.id, dims);
return (
triggerToFlow(flowData, trigger, condPoint.id, dims, {
onAdd: () => onTriggerUpdate([
...trigger, {
platform: 'event',
$smType: 'trigger',
event_type: 'test',
}
]),
onDelete: i => onTriggerUpdate([
...trigger.slice(0, i),
...trigger.slice(i + 1)
]),
onEdit: i => setModalState({
single: true,
node: trigger[i],
update: t => onTriggerUpdate([
...trigger.slice(0, i),
t,
...trigger.slice(i + 1)
]),
allowedTypes: ['trigger'],
})
});
sequenceToFlow(
flowData,
sequence,
condPoint.id,
dims,
makeSequenceUpdater(sequence, onSequenceUpdate, setModalState),
);
// render
return <>
<Modal open={!!modalState}>
{modalBody}
</Modal>
<ReactFlow
nodeTypes={nodeTypes}
snapToGrid
@@ -45,7 +113,7 @@ export const DAGFlow: FC<Props> = ({
<MiniMap />
<Controls />
</ReactFlow>
);
</>;
}
@@ -54,7 +122,7 @@ const makeConditionPoint = ({
nodeWidth,
nodeHeight,
circleSize,
}: DAGFlowDims) => ({
}: DAGAutomationFlowDims) => ({
id: `c`,
type: 'dagcircle',
position: { x: padding.x + nodeWidth * 2, y: padding.y + nodeHeight * 0.25 },
@@ -1,20 +1,23 @@
import { AutomationSequenceNode } from 'types/automations';
import { DAGFlowDims, FlowData } from './types';
import { DAGAutomationFlowDims, FlowData } from './types';
import { getDescriptionFromAutomationNode } from 'utils/formatting';
import { XYPosition } from 'react-flow-renderer';
import { ChooseAction } from 'types/automations/actions';
import { DAGCircleProps, makeFlowCircle } from './DAGCircle';
import { makeFlowCircle } from './DAGCircle';
import { createOnRemoveForChooseNode, SequenceUpdater } from './updater';
export const sequenceToFlow = (
flowData: FlowData,
sequence: AutomationSequenceNode[],
fromPoint: string,
dims: DAGFlowDims,
dims: DAGAutomationFlowDims,
updater: SequenceUpdater,
prefix: string = "",
) => {
let lastPointId = fromPoint;
let lasPos: XYPosition | null = null;
// sequence
for (let i = 0; i < sequence.length; i++) {
const node = sequence[i];
const nodeId = `${prefix}n-${i}`;
@@ -30,27 +33,35 @@ export const sequenceToFlow = (
y: dims.padding.y
};
}
// draw node
if (node.$smType === 'action') {
if (node.action === 'choose') {
position = addChooseNode(flowData, node, position, nodeId, dims)
position = addChooseNode(flowData, node, position, nodeId, dims, updater, i)
} else {
addSingleNode(flowData, node, position, nodeId, dims);
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i)
});
}
} else {
addSingleNode(flowData, node, position, nodeId, dims);
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i)
});
}
addEdge(flowData, lastPointId, nodeId, false)
lastPointId = nodeId;
lasPos = position;
}
// add button
const addCircle = makeFlowCircle(
`${prefix}-+`,
{
x: (lasPos === null ? dims.padding.x + dims.nodeWidth * dims.distanceFactor * (sequence.length + 1) : lasPos.x) + dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y + dims.circleSize / 2
},
{ onAdd: () => { }, size: dims.circleSize, disableSource: true, }
{ onAdd: updater.addNode, size: dims.circleSize, disableSource: true, }
)
flowData.nodes.push(addCircle)
addEdge(flowData, lastPointId, addCircle.id, false)
@@ -79,8 +90,11 @@ const addSingleNode = (
{
nodeHeight,
nodeWidth,
}: DAGFlowDims,
extra: Record<string, any> = {},
}: DAGAutomationFlowDims,
opts: {
onEditClick: () => void;
onXClick: () => void;
}
) => flowData.nodes.push({
id: nodeId,
type: 'dagnode',
@@ -89,12 +103,10 @@ const addSingleNode = (
height: nodeHeight,
width: nodeWidth,
color: node.$smType === 'action' ? 'green' : 'blue',
// onEdit: () => opts.onEdit(i),
// onXClick: () => opts.onDelete(i, flowId),
hasInput: true,
...opts,
},
position,
...extra
});
@@ -104,28 +116,45 @@ const addChooseNode = (
node: ChooseAction,
position: XYPosition,
nodeId: string,
dims: DAGFlowDims,
dims: DAGAutomationFlowDims,
updater: SequenceUpdater,
i: number,
) => {
addSingleNode(flowData, node, position, nodeId, dims);
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
});
let lastPos: XYPosition = position;
// conditions
node.action_data.choose.forEach(({ sequence, conditions }, j) => {
const sequenceId = `${nodeId}.${j}`;
// edit/delete circle
const circle = makeFlowCircle(`${sequenceId}>cond`, {
x: position.x + dims.nodeWidth * dims.distanceFactor,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor,
}, { size: dims.circleSize * dims.distanceFactor, onEdit: () => { }, onRemove: () => { } })
}, {
size: dims.circleSize * dims.distanceFactor,
onEdit: updater.makeOnEditConditionsForChooseNode(i, j),
onRemove: createOnRemoveForChooseNode(
node,
d => updater.updateNode(i, d),
j,
),
})
flowData.nodes.push(circle)
addEdge(flowData, nodeId, circle.id, true)
// actual sub sequence
const lastPoint = sequenceToFlow(flowData, sequence, circle.id, {
...dims,
padding: {
x: position.x - dims.nodeWidth,
y: circle.position.y,
},
}, `${sequenceId}.`);
}, updater.makeChildUpdaterForChooseAction(i, j), `${sequenceId}.`);
if (lastPoint.position) {
lastPos = xyApply(lastPos, lastPoint.position, Math.max)
} else {
lastPos = xyApply(lastPos, { x: lastPos.x, y: lastPos.y + dims.nodeHeight * dims.distanceFactor }, Math.max)
}
})
const totalChildren = node.action_data.choose.length;
@@ -138,7 +167,19 @@ const addChooseNode = (
},
{
size: dims.circleSize * dims.distanceFactor,
onAdd: () => { },
onAdd: () => updater.updateNode(i, {
...node,
action_data: {
...node.action_data,
choose: [
...node.action_data.choose,
{
sequence: [],
conditions: [],
}
]
}
}),
disableSource: true,
}
);
@@ -158,7 +199,7 @@ const addChooseNode = (
x: position.x - dims.nodeWidth,
y: elseCircle.position.y,
},
}, `${nodeId}.${totalChildren}.`)
}, updater.makeChildUpdaterForChooseAction(i, null), `${nodeId}.${totalChildren}.`)
if (lastPoint.position) {
lastPos = xyApply(lastPos, lastPoint.position, Math.max)
} else {
@@ -1,8 +1,7 @@
import { AutomationTrigger } from 'types/automations/triggers';
import { DAGFlowDims, FlowData, TriggerMakerOptions } from './types';
import { DAGAutomationFlowDims, FlowData, TriggerMakerOptions } from './types';
import { makeFlowCircle } from './DAGCircle';
export const triggerToFlow = (
flowData: FlowData,
trigger: AutomationTrigger[],
@@ -13,7 +12,7 @@ export const triggerToFlow = (
nodeWidth,
circleSize,
padding,
}: DAGFlowDims,
}: DAGAutomationFlowDims,
opts: TriggerMakerOptions,
) => {
// convert all triggers to dag nodes
@@ -27,7 +26,7 @@ export const triggerToFlow = (
height: nodeHeight,
width: nodeWidth,
color: 'red',
onEdit: () => opts.onEdit(i),
onEditClick: () => opts.onEdit(i),
onXClick: () => opts.onDelete(i),
},
position: { x: padding.x, y: padding.y + nodeHeight * distanceFactor * i }
+24 -6
View File
@@ -1,21 +1,22 @@
import { Edge, Node, XYPosition } from 'react-flow-renderer';
import { AutomationSequenceNode } from 'types/automations';
import { DAGCircleProps } from './DAGCircle';
import { DAGNodeProps } from './DAGNode';
import { AutomationTrigger } from 'types/automations/triggers';
import { MultiNodeEditorProps } from 'components/MultiNodeEditors';
export type DAGFlowDims = {
export type DAGAutomationFlowDims = {
padding: XYPosition;
nodeHeight: number;
nodeWidth: number;
// addHeight: number;
// addWidth: number;
circleSize: number;
distanceFactor: number;
}
export type DAGFlowNode = Node<DAGNodeProps | DAGCircleProps | any>;
export type DAGAutomationFlowNode = Node<DAGNodeProps | DAGCircleProps | any>;
export type FlowData = {
nodes: DAGFlowNode[],
nodes: DAGAutomationFlowNode[],
edges: Edge[],
}
@@ -23,4 +24,21 @@ export type TriggerMakerOptions = {
onAdd: () => void,
onEdit: (i: number) => void,
onDelete: (i: number) => void,
}
}
export type UpdateModalState<T extends AutomationSequenceNode | AutomationTrigger = any> = (
s: ModalState<T>
) => void;
export type ModalState<T extends AutomationSequenceNode | AutomationTrigger = any> = {
single: true,
node: T
update: (n: T) => void;
saveBtnCreateText?: boolean;
allowedTypes: MultiNodeEditorProps['allowedTypes'],
} | {
single: false,
node: AutomationSequenceNode[]
update: (n: AutomationSequenceNode[]) => void;
allowedTypes: ['condition']
}
@@ -0,0 +1,85 @@
import { AutomationSequenceNode } from "types/automations"
import { ChooseAction } from "types/automations/actions";
import { ModalState } from "./types";
import { makeSequenceUpdater } from "./updater"
const mockSequenceUpdater = (defaultState: AutomationSequenceNode[] = []) => {
let state: AutomationSequenceNode[] = [...defaultState]
const modalStates: ModalState[] = [];
const updater = makeSequenceUpdater(
state,
s => {
state = s
console.log(state, s)
},
ms => modalStates.push(ms)
);
return {
get state() {
return state
},
modalStates,
updater
};
}
test("sequence updater updates nodes", () => {
const mock = mockSequenceUpdater([
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [
{
"conditions": [],
"sequence": [],
}
],
"default": [],
}
}
]);
expect(mock.state.length).toBe(1)
expect((mock.state[0] as ChooseAction).action_data.alias).toBe(undefined)
mock.updater.updateNode(0, {
...mock.state[0],
action_data: {
...(mock.state[0] as ChooseAction).action_data,
alias: "Hello"
}
} as any)
expect((mock.state[0] as ChooseAction).action_data.alias).toBe("Hello")
})
test('update conditions for node', () => {
const mock = mockSequenceUpdater([
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [
{
"conditions": [],
"sequence": [],
}
],
"default": [],
}
}
]);
mock.updater.makeOnEditConditionsForChooseNode(0, 0)();
expect(mock.modalStates.length).toBe(1)
expect((mock.modalStates[0].node as AutomationSequenceNode[]).length).toBe(0)
mock.modalStates[0].update([
{
"$smType": "condition",
"condition": "and",
"condition_data": {
"conditions": [],
}
}
] as any)
expect((mock.state[0] as ChooseAction).action_data.choose[0].conditions.length).toBe(1)
expect((mock.state[0] as ChooseAction).action_data.choose[0].conditions[0].condition).toBe("and")
})
+146
View File
@@ -0,0 +1,146 @@
import { AutomationSequenceNode } from "types/automations";
import { ChooseAction } from "types/automations/actions";
import { AutomationCondition } from "types/automations/conditions";
import { UpdateModalState } from "./types";
export type SequenceUpdater = ReturnType<typeof makeSequenceUpdater>;
export const makeSequenceUpdater = (
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,
]),
allowedTypes: ['action', 'condition']
})
},
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 makeSequenceUpdater(
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 makeSequenceUpdater(
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}`)
},
makeOnModalOpenForNode(
i: number,
node: AutomationSequenceNode,
) {
return () => openModal({
single: true,
node,
allowedTypes: ['action', 'condition'],
update: n => this.updateNode(i, n),
})
},
makeOnEditConditionsForChooseNode(
i: number,
j: number,
) {
return () => {
const node = sequence[i] as ChooseAction;
return openModal({
single: false,
node: node.action_data.choose[j].conditions,
allowedTypes: ['condition'],
update: conditions => this.updateNode(i, {
...node,
action_data: {
...node.action_data,
choose: [
...node.action_data.choose.slice(0, j),
{
sequence: node.action_data.choose[j].sequence,
conditions: conditions as AutomationCondition[],
},
...node.action_data.choose.slice(j + 1),
]
}
}),
})
}
}
});
export const createOnRemoveForChooseNode = (
action: ChooseAction,
update: (data: ChooseAction) => void,
j: number
) => () => update({
...action,
action_data: {
...action.action_data,
choose: [
...action.action_data.choose.slice(0, j),
...action.action_data.choose.slice(j + 1),
]
}
})