From a56c7ff964e2ea5114280939e2b601f69b8ac384 Mon Sep 17 00:00:00 2001 From: Ari Date: Thu, 5 May 2022 13:48:51 -0400 Subject: [PATCH] stable editor --- .../src/components/AutomationEditor/index.tsx | 49 +- webapp/src/components/DAGFlow/DAGNode.tsx | 4 +- .../src/components/DAGFlow/index.stories.tsx | 516 ++++++++---------- webapp/src/components/DAGFlow/index.tsx | 100 +++- .../components/DAGFlow/sequenceConvertor.ts | 77 ++- .../components/DAGFlow/triggerConvertor.ts | 7 +- webapp/src/components/DAGFlow/types.ts | 30 +- webapp/src/components/DAGFlow/updater.test.ts | 85 +++ webapp/src/components/DAGFlow/updater.ts | 146 +++++ webapp/src/components/Inputs/styles.ts | 4 +- .../MultiNodeEditors/index.stories.tsx | 9 +- .../src/components/MultiNodeEditors/index.tsx | 119 ++-- .../NodeEditor/OptionManager/index.ts | 20 +- webapp/src/components/NodeEditor/index.css | 48 +- webapp/src/components/NodeEditor/index.tsx | 19 +- .../src/components/SequenceNodes/updater.ts | 8 +- webapp/src/styles/root.css | 16 + webapp/src/utils/AutomationState.ts | 8 +- 18 files changed, 832 insertions(+), 433 deletions(-) create mode 100644 webapp/src/components/DAGFlow/updater.test.ts create mode 100644 webapp/src/components/DAGFlow/updater.ts diff --git a/webapp/src/components/AutomationEditor/index.tsx b/webapp/src/components/AutomationEditor/index.tsx index 8c6fb2e..a8e113d 100644 --- a/webapp/src/components/AutomationEditor/index.tsx +++ b/webapp/src/components/AutomationEditor/index.tsx @@ -15,6 +15,8 @@ import { NodeEditor } from "components/NodeEditor"; import { ButtonIcon } from "components/Icons/ButtonIcons"; import { Button } from "components/Inputs/Button"; import { useAutomatioEditorState } from "./state"; +import { DAGAutomationFlow } from "components/DAGFlow"; +import * as dgconst from 'components/DAGSvgs/constants'; interface TriggerEditorModalState { trigger: AutomationTrigger; @@ -101,38 +103,23 @@ export const AutomationEditor: FC = ({ Save - chain([ - computeExtraField([1, 0.5], [2, 0.5]), - computeTriggerPos( - [0.5, 0.5], - state.data.trigger, - [1.5, 0.5], - updateTrigger, - () => { - setModalState({ - trigger: { - $smType: "trigger", - platform: "device", - device_id: "", - domain: "", - type: "", - subtype: "" - }, - onSave: (t) => updateTrigger([...state.data.trigger, t]) - }); - }, - (trigger, onSave) => setModalState({ - trigger, - onSave, - }) - ), - ])} + trigger={state.data.trigger} + onSequenceUpdate={updateSequence} + triggersOpts={{ + + }} + dims={{ + nodeHeight: dgconst.NODE_HEIGHT, + nodeWidth: dgconst.NODE_WIDTH, + distanceFactor: dgconst.DISTANCE_FACTOR, + circleSize: dgconst.CIRCLE_SIZE, + padding: { + x: dgconst.PADDING, + y: dgconst.PADDING, + }, + }} /> diff --git a/webapp/src/components/DAGFlow/DAGNode.tsx b/webapp/src/components/DAGFlow/DAGNode.tsx index ac23945..0c178bf 100644 --- a/webapp/src/components/DAGFlow/DAGNode.tsx +++ b/webapp/src/components/DAGFlow/DAGNode.tsx @@ -44,7 +44,9 @@ export const DAGNode: FC<{ data: DAGNodeProps }> = ({ {label} -
+
{ + console.log('editing me', label, onEditClick, onEditClick()) + }}> diff --git a/webapp/src/components/DAGFlow/index.stories.tsx b/webapp/src/components/DAGFlow/index.stories.tsx index 1e0d00c..dde957d 100644 --- a/webapp/src/components/DAGFlow/index.stories.tsx +++ b/webapp/src/components/DAGFlow/index.stories.tsx @@ -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 +} as ComponentMeta -const Template: ComponentStory = args => { - const [state, setState] = useState(args.automation) - const triggerEditor = makeAumationStateEditor(state, setState).triggers; +const Template: ComponentStory = args => { + const [state, setState] = useState({ + trigger: args.trigger, + sequence: args.sequence, + }) + console.log(state) return
- 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 })} />
} @@ -51,290 +47,244 @@ const Template: ComponentStory = 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: [] } diff --git a/webapp/src/components/DAGFlow/index.tsx b/webapp/src/components/DAGFlow/index.tsx index e3f5e77..fe8f27f 100644 --- a/webapp/src/components/DAGFlow/index.tsx +++ b/webapp/src/components/DAGFlow/index.tsx @@ -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 = ({ - automation, - opts, +export const DAGAutomationFlow: FC = ({ + sequence, + trigger, + onTriggerUpdate, + onSequenceUpdate, dims, }) => { + // state + const [modalState, setModalState] = useState(null); + + // modal + let modalBody = <> + if (modalState) { + if (modalState.single) { + modalBody = setModalState(null)} + onSave={n => { modalState.update(n as any); setModalState(null); }} + allowedTypes={modalState.allowedTypes} + saveBtnCreateText={modalState.saveBtnCreateText} + /> + } else { + modalBody = 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 <> + + {modalBody} + = ({ - ); + ; } @@ -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 }, diff --git a/webapp/src/components/DAGFlow/sequenceConvertor.ts b/webapp/src/components/DAGFlow/sequenceConvertor.ts index 96e8469..51f084f 100644 --- a/webapp/src/components/DAGFlow/sequenceConvertor.ts +++ b/webapp/src/components/DAGFlow/sequenceConvertor.ts @@ -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 = {}, + }: 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 { diff --git a/webapp/src/components/DAGFlow/triggerConvertor.ts b/webapp/src/components/DAGFlow/triggerConvertor.ts index 578af6f..f471a99 100644 --- a/webapp/src/components/DAGFlow/triggerConvertor.ts +++ b/webapp/src/components/DAGFlow/triggerConvertor.ts @@ -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 } diff --git a/webapp/src/components/DAGFlow/types.ts b/webapp/src/components/DAGFlow/types.ts index 5d26a6b..b936005 100644 --- a/webapp/src/components/DAGFlow/types.ts +++ b/webapp/src/components/DAGFlow/types.ts @@ -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; +export type DAGAutomationFlowNode = Node; 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, -} \ No newline at end of file +} + +export type UpdateModalState = ( + s: ModalState +) => void; + +export type ModalState = { + single: true, + node: T + update: (n: T) => void; + saveBtnCreateText?: boolean; + allowedTypes: MultiNodeEditorProps['allowedTypes'], +} | { + single: false, + node: AutomationSequenceNode[] + update: (n: AutomationSequenceNode[]) => void; + allowedTypes: ['condition'] +} diff --git a/webapp/src/components/DAGFlow/updater.test.ts b/webapp/src/components/DAGFlow/updater.test.ts new file mode 100644 index 0000000..d3e6e2e --- /dev/null +++ b/webapp/src/components/DAGFlow/updater.test.ts @@ -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") +}) \ No newline at end of file diff --git a/webapp/src/components/DAGFlow/updater.ts b/webapp/src/components/DAGFlow/updater.ts new file mode 100644 index 0000000..63f9336 --- /dev/null +++ b/webapp/src/components/DAGFlow/updater.ts @@ -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; + +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), + ] + } +}) diff --git a/webapp/src/components/Inputs/styles.ts b/webapp/src/components/Inputs/styles.ts index f151dc6..d9c5cbf 100644 --- a/webapp/src/components/Inputs/styles.ts +++ b/webapp/src/components/Inputs/styles.ts @@ -27,8 +27,8 @@ const commonInputStyle = (theme: AppTheme) => ({ export const useButtonStyles = createAppUseStyles<{}>(theme => ({ input: { ...commonInputStyle(theme).input, - paddingTop: '1em', - paddingBottom: '1em', + paddingTop: '0.5em', + paddingBottom: '0.5em', cursor: 'pointer', }, })); diff --git a/webapp/src/components/MultiNodeEditors/index.stories.tsx b/webapp/src/components/MultiNodeEditors/index.stories.tsx index e87c929..353197c 100644 --- a/webapp/src/components/MultiNodeEditors/index.stories.tsx +++ b/webapp/src/components/MultiNodeEditors/index.stories.tsx @@ -50,14 +50,7 @@ export const InAModal: ComponentStory = props => { {...props} sequence={state} onClose={() => setOpen(!open)} - onAdd={(n, slide) => { setState([...state, n]); slide(state.length) }} - onRemove={(n, slide) => { - setState([ - ...state.slice(0, n), - ...state.slice(n + 1) - ]); - slide(state.length - 2) - }} + onSave={setState} />
diff --git a/webapp/src/components/MultiNodeEditors/index.tsx b/webapp/src/components/MultiNodeEditors/index.tsx index 39482ae..d382428 100644 --- a/webapp/src/components/MultiNodeEditors/index.tsx +++ b/webapp/src/components/MultiNodeEditors/index.tsx @@ -36,43 +36,84 @@ const makeDefault = (nodeType: keyof AutomationNodeMapping): AutomationNode => { } } -export interface Props { +export interface MultiNodeEditorProps { sequence: AutomationNode[]; allowedTypes?: Array; - onAdd?: (n: AutomationNode, slide: (i: number) => void) => void; onClose?: () => void; - onSave?: (i: number, n: AutomationNode) => void; - onRemove?: (i: number, slide: (i: number) => void) => void; + onSave?: (n: AutomationNode[]) => void; } -export const MultiNodeEditor: FC = ({ - sequence, +export const MultiNodeEditor: FC = ({ + sequence: initialState, allowedTypes = ['action', 'condition'], - onClose, - onAdd = () => { }, + onClose = () => { }, onSave = () => { }, - onRemove = () => { }, }) => { - const [slide, setSlide] = useState(0); + // state + const [{ slide, state, isNodeModified, isModified, isReady }, setState] = useState({ + slide: 0, + state: initialState, + isModified: false, + isNodeModified: false, + isReady: true, + }) + // alias + const areYouSureItsModified = () => isNodeModified ? + window.confirm("You've made changes, by pressing this you will lose them!") : + true + const areYouSureItsNotReady = () => !isReady ? + window.confirm("The node is not ready, are you sure you want to move?") : + true + const onAdd = () => setState({ + slide: state.length, + state: [...state, makeDefault(allowedTypes[0])], + isNodeModified: false, + isReady, + isModified: true, + }); + const onRemove = () => setState({ + slide: slide > 0 ? slide - 1 : 0, + state: [...state.slice(0, slide), ...state.slice(slide + 1)], + isNodeModified: false, + isReady, + isModified: true, + }); + const onNodeSave = (n: AutomationNode) => setState({ + slide, + state: [...state.slice(0, slide), n, ...state.slice(slide + 1)], + isNodeModified: false, + isReady, + isModified: true, + }); + const onSaveAll = () => isNodeModified ? + window.alert("Please save the node data first!") : + onSave(state) + const onNextOrAdd = () => { + if (!areYouSureItsModified()) { + return + } + if (!areYouSureItsNotReady()) { + return + } + if (slide >= state.length - 1) { + onAdd() + } else { + setState({ slide: slide + 1, state, isNodeModified, isReady, isModified, }) + } + } + const onBack = () => areYouSureItsModified() && + areYouSureItsNotReady() && + setState({ slide: slide - 1, state, isNodeModified, isReady, isModified, }) // components const nextOrAddBtn = ; // branch - if (sequence.length === 0) { - return
= ({ }}> {nextOrAddBtn}
- +
+ +
} return <>
- - {slide + 1}/{sequence.length} + @@ -103,10 +146,22 @@ export const MultiNodeEditor: FC = ({
onSave(slide, n)} - /> + onSave={onNodeSave} + onFlags={ + (ir, inm) => ((inm !== isNodeModified) || (ir !== isReady)) && + setState({ slide, state, isNodeModified: inm, isReady: ir, isModified }) + } + > + + +
+ {slide + 1}/{state.length} +
} diff --git a/webapp/src/components/NodeEditor/OptionManager/index.ts b/webapp/src/components/NodeEditor/OptionManager/index.ts index 767f1e6..b2fa5f7 100644 --- a/webapp/src/components/NodeEditor/OptionManager/index.ts +++ b/webapp/src/components/NodeEditor/OptionManager/index.ts @@ -1,22 +1,32 @@ -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import { AutomationNode, AutomationNodeTypes } from 'types/automations'; import { AutomationNodeSubtype } from 'types/automations'; import { getOptionManager } from './getOptionManager'; export const useEditorNodeState = (node: AutomationNode) => { - const [state, setState] = useState(node); + const [{ node: state, isModified }, setAllState] = useState({ + node, + isModified: false, + }); + useEffect(() => { + setAllState({ node, isModified: false }) + }, [node]) + const setState = (node: AutomationNode) => setAllState(({ node, isModified: true })) const nodeType: AutomationNodeTypes = state.$smType ?? 'trigger'; const subType: AutomationNodeSubtype = state.$smType === 'action' ? state.action : state.$smType === 'condition' ? state.condition : state.platform; - const subTypes = getSubTypeList(nodeType) + const subTypes = getSubTypeList(nodeType) const optionManager = getOptionManager(nodeType, subType as any); return { nodeType, subType, subTypes, + get isModified() { + return isModified + }, get data() { return state }, @@ -101,7 +111,7 @@ const getSubTypeList = (nodeType: T): AutomationN 'time', 'trigger', 'zone', - ]as any + ] as any case 'trigger': return [ 'event', @@ -116,7 +126,7 @@ const getSubTypeList = (nodeType: T): AutomationN 'webhook', 'zone', 'device', - ]as any + ] as any default: return []; } diff --git a/webapp/src/components/NodeEditor/index.css b/webapp/src/components/NodeEditor/index.css index 521762f..1772c6c 100644 --- a/webapp/src/components/NodeEditor/index.css +++ b/webapp/src/components/NodeEditor/index.css @@ -1,16 +1,27 @@ .node-editor--root { - display : flex; - flex-direction : column; + display: flex; + flex-direction: column; justify-content: center; - align-items : center; - height : 100%; + align-items: center; + height: 100%; + padding: 1em; + margin-top: 0.5em; +} + +.node-editor--root.modded { + border: 1px solid var(--change); + border-radius: 5px; +} + +.node-editor--root.modded * { + border-color: var(--change); } .node-editor--body-title { - display : flex; - flex-direction : row; + display: flex; + flex-direction: row; justify-content: space-between; - margin-bottom : 6px; + margin-bottom: 6px; } .node-editor--body-title>* { @@ -18,21 +29,22 @@ } .node-editor--body { - overflow : overlay; - padding-left : 1%; + overflow: overlay; + padding-left: 1%; padding-right: 1%; - min-width : 100%; + min-width: 100%; min-height: fit-content; } .node-editor--footer { - bottom : 0; - left : 0; - display : flex; - flex-direction : row; + bottom: 0; + left: 0; + display: flex; + flex-direction: row; justify-content: space-between; - align-items : center; - width : 100%; - min-height : 50px; -} + align-items: center; + width: 100%; + min-height: 50px; + min-width: 25vw; +} \ No newline at end of file diff --git a/webapp/src/components/NodeEditor/index.tsx b/webapp/src/components/NodeEditor/index.tsx index 85f7893..f3b969b 100644 --- a/webapp/src/components/NodeEditor/index.tsx +++ b/webapp/src/components/NodeEditor/index.tsx @@ -11,6 +11,7 @@ export interface Props { allowedTypes?: Array; onClose?: () => void; onSave?: (n: AutomationNode) => void; + onFlags?: (isReady: boolean, isModified: boolean) => void; saveBtnCreateText?: boolean; } @@ -19,11 +20,22 @@ export const NodeEditor: FC = ({ allowedTypes = ["action", "condition", "trigger"], onClose = () => { }, onSave = () => { }, + onFlags = () => { }, saveBtnCreateText = false, + children }) => { + // state const state = useEditorNodeState(node); - return
+ // state + const isModified = state.isModified; + const isReady = state.isReady(); + + // events + onFlags(isReady, isModified); + + // render + return
{allowedTypes.length > 1 ? = ({
+ isReady && onSave(state.data) + }} disabled={!isReady}>{saveBtnCreateText ? "Create" : "Save"} + {children}
} diff --git a/webapp/src/components/SequenceNodes/updater.ts b/webapp/src/components/SequenceNodes/updater.ts index f33cf42..67035a7 100644 --- a/webapp/src/components/SequenceNodes/updater.ts +++ b/webapp/src/components/SequenceNodes/updater.ts @@ -14,7 +14,7 @@ export const makeUpdater = ( removeNode(i: number) { return onChange([ ...sequence.slice(0, i), - ...sequence.slice(i+1), + ...sequence.slice(i + 1), ]) }, addNode() { @@ -40,7 +40,7 @@ export const makeUpdater = ( return onChange([ ...sequence.slice(0, i), node, - ...sequence.slice(i+1), + ...sequence.slice(i + 1), ]) }, updateChooseActionData(i: number, data: ChooseAction['action_data']) { @@ -50,7 +50,7 @@ export const makeUpdater = ( action_data: data, }) }, - makeChildUpdaterForChooseAction(i: number, j:number | null) { + makeChildUpdaterForChooseAction(i: number, j: number | null) { const node = sequence[i]; if ((node.$smType === 'action') && (node.action === 'choose')) { if (j !== null) { @@ -66,7 +66,7 @@ export const makeUpdater = ( ...node.action_data.choose[j], sequence: seq, }, - ...node.action_data.choose.slice(j+1), + ...node.action_data.choose.slice(j + 1), ] } }), diff --git a/webapp/src/styles/root.css b/webapp/src/styles/root.css index 6d450a5..70a5ed1 100644 --- a/webapp/src/styles/root.css +++ b/webapp/src/styles/root.css @@ -4,6 +4,7 @@ --primary-accent: #bbbbbb; --secondary-accent: #929191; --error: #c55; + --change: #0f9; touch-action: pan-x pan-y; height: 100%; } @@ -45,4 +46,19 @@ body, * { transition: all 200ms ease-out; +} + +.column { + display: flex; + flex-direction: column; +} + +.center { + justify-content: center; + align-items: center; +} + +.row { + display: flex; + flex-direction: row; } \ No newline at end of file diff --git a/webapp/src/utils/AutomationState.ts b/webapp/src/utils/AutomationState.ts index a55c83b..710426e 100644 --- a/webapp/src/utils/AutomationState.ts +++ b/webapp/src/utils/AutomationState.ts @@ -1,4 +1,4 @@ -import { AutomationData } from "types/automations"; +import { AutomationData, AutomationSequenceNode } from "types/automations"; import { AutomationTrigger } from '../types/automations/triggers'; export type AumationStateEditor = ReturnType; @@ -32,5 +32,9 @@ export const makeAumationStateEditor = ( trigger: automation.trigger .concat([t]) }), - } + }, + updateSequence: (s: AutomationSequenceNode[]) => onUpdate({ + ...automation, + sequence: s, + }) }) \ No newline at end of file