diff --git a/webapp/src/components/DAGGraph/board/index.css b/webapp/src/components/DAGGraph/board/index.css new file mode 100644 index 0000000..9c8499c --- /dev/null +++ b/webapp/src/components/DAGGraph/board/index.css @@ -0,0 +1,14 @@ +.dag-graphboard { + min-height: 100%; + min-width: 100%; +} + +.dag-graphboard.loading { + position: relative; +} + +.dag-graphboard.loading span { + position: absolute; + left: 50%; + top: 50%; +} \ No newline at end of file diff --git a/webapp/src/components/DAGGraph/board/index.stories.tsx b/webapp/src/components/DAGGraph/board/index.stories.tsx new file mode 100644 index 0000000..4e6ab5d --- /dev/null +++ b/webapp/src/components/DAGGraph/board/index.stories.tsx @@ -0,0 +1,91 @@ +import React from "react"; +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { DAGGraphBoard } from "."; +import { Page } from "components/Page"; +import { SimpleErrorElement } from "components/SimpleErrorElement"; + +export default { + title: "DAGGraph/Board", + component: DAGGraphBoard, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: {}, +} as ComponentMeta; + +const Template: ComponentStory = (args) => { + return ( + + + + ); +}; + +export const Loading = Template.bind({}); +Loading.args = { + ...Loading.args, + state: { + ready: false, + }, +}; + +export const Errored = Template.bind({}); +Errored.args = { + ...Loading.args, + state: { + ready: true, + data: { + error: , + }, + }, +}; + +export const Empty = Template.bind({}); +Empty.args = { + ...Empty.args, + state: { + ready: true, + data: { + elements: { + nodes: [], + edges: [], + }, + }, + }, +}; + +export const Basic = Template.bind({}); +Basic.args = { + ...Basic.args, + state: { + ready: true, + data: { + elements: { + nodes: [ + { + position: { x: 50, y: 50 }, + id: "1", + data: { + label: "hi", + }, + }, + { + position: { x: 500, y: 200 }, + id: "2", + data: { + label: "hi", + }, + }, + ], + edges: [ + { id: "1->2", source: "1", target: "2", label: "wow" }, + { + id: "2->1", + source: "2", + target: "1", + label: "yes", + animated: true, + }, + ], + }, + }, + }, +}; diff --git a/webapp/src/components/DAGGraph/board/index.tsx b/webapp/src/components/DAGGraph/board/index.tsx new file mode 100644 index 0000000..004ae8e --- /dev/null +++ b/webapp/src/components/DAGGraph/board/index.tsx @@ -0,0 +1,66 @@ +import "./index.css"; + +import { FC } from "react"; +import CircularProgress from "@mui/material/CircularProgress"; +import ReactFlow, { Controls } from "react-flow-renderer"; + +import { NodeEditor } from "components/NodeEditor"; +import { Modal } from "components/Modal"; + +import { nodeTypes } from "../nodes"; +import { DAGGraphBoardProps } from "./types"; + +export const DAGGraphBoard: FC = ({ + modalState, + state, + closeModal, +}) => { + // render unready or errored states + if (!state.ready) { + return ( +
+ +
+ ); + } + + if ("error" in state.data) { + return
{state.data.error}
; + } + + // modal + let modalBody = <>; + if (modalState) { + modalBody = ( + { + modalState.update(n as any); + closeModal(); + }} + allowedTypes={modalState.allowedTypes} + saveBtnCreateText={modalState.saveBtnCreateText} + /> + ); + } + + // main render + return ( + <> + {modalBody} + + + + + ); +}; diff --git a/webapp/src/components/DAGGraph/board/types.ts b/webapp/src/components/DAGGraph/board/types.ts new file mode 100644 index 0000000..999aadd --- /dev/null +++ b/webapp/src/components/DAGGraph/board/types.ts @@ -0,0 +1,34 @@ +import { ReactNode } from "react"; +import { AutomationNodeTypes, AutomationSequenceNode } from "types/automations"; +import { ElementData } from "../elements/types"; +import { AutomationTrigger } from "types/automations/triggers"; + +export type DAGGraphBoardState = + | { + ready: false; + } + | { + ready: true; + data: + | { + error: ReactNode; + } + | { + elements: ElementData; + }; + }; +export type DAGGraphBoardProps = { + state: DAGGraphBoardState; + modalState?: ModalState; + closeModal: () => void; +}; + +export type ModalState< + T extends AutomationSequenceNode | AutomationTrigger = any +> = { + isError?: boolean; + node: T; + update: (n: T) => void; + saveBtnCreateText?: boolean; + allowedTypes: AutomationNodeTypes[]; +}; diff --git a/webapp/src/components/DAGGraph/elements/constants.ts b/webapp/src/components/DAGGraph/elements/constants.ts new file mode 100644 index 0000000..25b40f4 --- /dev/null +++ b/webapp/src/components/DAGGraph/elements/constants.ts @@ -0,0 +1,29 @@ +import { DAGDims } from "./types"; + +export const NODE_WIDTH = 170 as const; +export const NODE_HEIGHT = 70 as const; +export const CONDITION_HEIGHT = 90 as const; +export const CONDITION_WIDTH = 200 as const; +export const CIRCLE_SIZE = 40 as const; +export const DISTANCE_FACTOR = 1.25 as const; + +export const DEFAULT_DIMS = { + node: { + height: NODE_HEIGHT, + width: NODE_WIDTH, + }, + condition: { + height: CONDITION_HEIGHT, + width: CONDITION_WIDTH, + }, + circle: { + height: CIRCLE_SIZE, + width: CIRCLE_SIZE, + }, + distanceFactor: DISTANCE_FACTOR, + position: { + x: 50, + y: 50, + }, + flipped: true, +} as DAGDims; diff --git a/webapp/src/components/DAGGraph/elements/distance.ts b/webapp/src/components/DAGGraph/elements/distance.ts new file mode 100644 index 0000000..9bdc28c --- /dev/null +++ b/webapp/src/components/DAGGraph/elements/distance.ts @@ -0,0 +1,45 @@ +import { DAGDims, DAGEntities, Size } from "./types"; +import { XYPosition } from "react-flow-renderer"; + +export const moveAlong = ( + by: keyof DAGEntities, + startPoint: XYPosition, + increment: number, + dims: DAGDims, + direction: "under" | "next" = "next" +): XYPosition => { + const moveOnY = { + y: startPoint.y + dims[by].height * dims.distanceFactor * increment, + x: startPoint.x + dims[by].width, + }; + const moveOnX = { + x: startPoint.x + dims[by].width * dims.distanceFactor * increment, + y: startPoint.y + dims[by].height, + }; + if (direction === "next") { + return dims.flipped ? moveOnX : moveOnY; + } else { + return !dims.flipped ? moveOnX : moveOnY; + } +}; + +export const computeSize = ( + by: keyof DAGEntities, + dims: DAGDims, + count: number, + direction: "under" | "next" = "next" +): Size => { + const moveOnY = { + height: dims[by].height * count, + width: dims[by].width * dims.distanceFactor, + }; + const moveOnX = { + width: dims[by].width * count, + height: dims[by].height * dims.distanceFactor, + }; + if (direction === "next") { + return dims.flipped ? moveOnX : moveOnY; + } else { + return !dims.flipped ? moveOnX : moveOnY; + } +}; diff --git a/webapp/src/components/DAGGraph/elements/index.stories.tsx b/webapp/src/components/DAGGraph/elements/index.stories.tsx new file mode 100644 index 0000000..2018aef --- /dev/null +++ b/webapp/src/components/DAGGraph/elements/index.stories.tsx @@ -0,0 +1,121 @@ +import React, { FC, useState } from "react"; +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { Page } from "components/Page"; +import { DAGGraphBoard } from "components/DAGGraph/board"; +import { AutomationTrigger } from "types/automations/triggers"; +import { makeTriggerNodes, makeAutomationNodes } from "."; +import { useHA } from "haService"; +import { AutomationActionData } from "types/automations"; +import { createUpdaterFromAutomationData } from "../updater"; +import { ModalState } from "../board/types"; +import { DEFAULT_DIMS } from "./constants"; + +const Demo: FC<{ + automation: AutomationActionData; + flipped: boolean; +}> = (props) => { + const { namer } = useHA(); + const [state, setState] = useState(props.automation); + const [modalState, setModalState] = + useState(undefined); + const updater = createUpdaterFromAutomationData( + setModalState, + state, + setState + ); + const elementData = makeAutomationNodes(state, { + dims: { + ...DEFAULT_DIMS, + flipped: props.flipped, + }, + namer, + openModal: setModalState, + stateUpdater: updater, + }); + return ( + setModalState(undefined)} + state={{ + ready: true, + data: { + elements: elementData, + }, + }} + /> + ); +}; + +export default { + title: "DAGGraph/Elements", + component: Demo, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: { + flipped: true, + automation: { + trigger: [], + condition: [], + sequence: [], + }, + }, +} as ComponentMeta; + +const Template: ComponentStory = (args) => ( + + + +); + +export const Empty = Template.bind({}); +export const Trigger = Template.bind({}); +Trigger.args = { + ...Trigger.args, + automation: { + trigger: [ + { platform: "homeassistant", event: "up" }, + { + platform: "tag", + tag_id: "Test Me", + device_id: "testme", + enabled: false, + }, + ], + condition: [], + sequence: [], + }, +}; +export const Conditions = Template.bind({}); +Conditions.args = { + ...Conditions.args, + automation: { + trigger: [ + { + platform: "device", + device_id: "asdasdas", + }, + ], + condition: [ + { + condition: "and", + conditions: [ + { + condition: "numeric_state", + entity_id: "sensor.temperature_kitchen", + below: "15", + }, + { + condition: "template", + value_template: 'states(switch.kitchen_light) == "on"', + }, + ], + }, + + { + condition: "numeric_state", + entity_id: "sensor.temperature_kitchen", + below: "15", + }, + ], + sequence: [], + }, +}; diff --git a/webapp/src/components/DAGGraph/elements/index.test.ts b/webapp/src/components/DAGGraph/elements/index.test.ts new file mode 100644 index 0000000..0333650 --- /dev/null +++ b/webapp/src/components/DAGGraph/elements/index.test.ts @@ -0,0 +1,77 @@ +import { Namer } from "utils/formatting"; +import { makeTriggerNodes } from "."; +import { createUpdaterFromAutomationData } from "../updater"; +import { DEFAULT_DIMS } from "./constants"; +import { ElementMakerProps } from "./types"; + +const makeDummyArgs = (): ElementMakerProps => ({ + dims: DEFAULT_DIMS, + elementData: { + nodes: [], + edges: [], + }, + namer: { + getDeviceName(device_id) { + return device_id; + }, + getServiceName(service) { + return service; + }, + getEntityName(entity_id, maxEntities = 1) { + if (Array.isArray(entity_id)) { + return entity_id.slice(0, maxEntities).join(" and "); + } else { + return entity_id; + } + }, + }, + nodeId: "t", + nodeIndex: 0, + stateUpdater: createUpdaterFromAutomationData( + () => {}, + { condition: [], trigger: [], sequence: [] }, + () => {} + ), + position: { x: 0, y: 0 }, + openModal: () => {}, +}); + +test("triggers bbox computed correctly -- one node", () => { + const dummyArgs = makeDummyArgs(); + const state = makeTriggerNodes( + [{ platform: "homeassistant", event: "up" }], + dummyArgs + ); + expect(state.elementData.nodes.length).toEqual(1); + expect(state.bbox[0]).toStrictEqual({ + x: 0, + y: 0, + }); + expect(state.bbox[1]).toStrictEqual({ + y: DEFAULT_DIMS.node.height * 2, + x: DEFAULT_DIMS.node.width, + }); +}); + +test("triggers bbox computed correctly -- many nodes", () => { + const dummyArgs = makeDummyArgs(); + const state = makeTriggerNodes( + [ + { platform: "homeassistant", event: "up" }, + { platform: "homeassistant", event: "up" }, + { platform: "homeassistant", event: "up" }, + { platform: "homeassistant", event: "up" }, + { platform: "homeassistant", event: "up" }, + ], + dummyArgs + ); + expect(state.elementData.nodes.length).toEqual(5); + expect(state.bbox[0]).toStrictEqual({ + x: 0, + y: 0, + }); + expect(state.bbox[1]).toStrictEqual({ + y: DEFAULT_DIMS.node.height * 2, + x: DEFAULT_DIMS.node.width * 6, + }); +}); diff --git a/webapp/src/components/DAGGraph/elements/index.ts b/webapp/src/components/DAGGraph/elements/index.ts new file mode 100644 index 0000000..890b2b0 --- /dev/null +++ b/webapp/src/components/DAGGraph/elements/index.ts @@ -0,0 +1,136 @@ +import { + Bbox, + ElementMaker, + ElementMakerBaseProps, + ElementMakerOutput, +} from "./types"; +import { AutomationTrigger } from "types/automations/triggers"; +import { SequenceNodeMaker } from "../nodes/SequenceNode"; +import * as distance from "./distance"; +import { getDescriptionFromAutomationNode } from "utils/formatting"; +import { AutomationActionData } from "types/automations"; +import { AutomationCondition } from "types/automations/conditions"; +import { pointApply, updateBBox } from "./math"; + +export const makeAutomationNodes = ( + automation: AutomationActionData, + args: ElementMakerBaseProps +) => { + let state: ElementMakerOutput = { + elementData: { + nodes: [], + edges: [], + }, + bbox: [ + { x: 0, y: 0 }, + { x: 0, y: 0 }, + ], + }; + console.log(args); + state = makeTriggerNodes(automation.trigger, { + ...args, + elementData: state.elementData, + position: state.bbox[0], + nodeId: "trigger", + nodeIndex: 0, + }); + + console.log(state); + const conditionStartPoint = pointApply(...state.bbox, (a, b) => (a + b) / 2); + if (args.dims.flipped) { + conditionStartPoint.y += args.dims.node.height * args.dims.distanceFactor; + } else { + conditionStartPoint.x += args.dims.node.width * args.dims.distanceFactor; + } + + const condOut = makeConditionNodes(automation.condition, { + ...args, + elementData: state.elementData, + position: pointApply(...state.bbox, (a, b) => (a + b) / 2), + nodeId: "condition", + nodeIndex: 0, + }); + + console.log(condOut); + + return condOut.elementData; +}; + +export const makeTriggerNodes: ElementMaker = ( + nodes, + { + elementData, + dims, + namer, + openModal, + stateUpdater, + nodeId, + nodeIndex, + position, + } +) => { + let bbox: Bbox = [position, position]; + nodes.forEach((node, index) => { + const element = SequenceNodeMaker.makeElement( + { + id: `${nodeId}-${nodeIndex}-${index}`, + position: distance.moveAlong("node", position, index, dims), + }, + dims, + { + color: "red", + enabled: node.enabled ?? true, + label: getDescriptionFromAutomationNode(node, namer, true), + onSetEnabled: () => stateUpdater.basic.trigger.setEnabled(index), + onEditClick: () => + openModal({ + allowedTypes: ["trigger"], + node: node, + update: (n) => stateUpdater.basic.trigger.updateNode(n, index), + }), + } + ); + elementData.nodes.push(element); + bbox = updateBBox(bbox, element.position, dims.node); + }); + + return { + elementData, + bbox, + }; +}; + +export const makeConditionNodes: ElementMaker = ( + nodes, + { elementData, nodeId, nodeIndex, position, dims, namer } +) => { + let bbox: Bbox = [position, position]; + + nodes.forEach((node, index) => { + const element = SequenceNodeMaker.makeElement( + { + id: `${nodeId}-${nodeIndex}-${index}`, + position: distance.moveAlong( + "condition", + position, + index, + dims, + "under" + ), + }, + dims, + { + color: "blue", + enabled: node.enabled ?? true, + label: getDescriptionFromAutomationNode(node, namer, true), + } + ); + elementData.nodes.push(element); + bbox = updateBBox(bbox, element.position, dims.condition); + }); + + return { + elementData, + bbox, + }; +}; diff --git a/webapp/src/components/DAGGraph/elements/math.test.ts b/webapp/src/components/DAGGraph/elements/math.test.ts new file mode 100644 index 0000000..04bcdd6 --- /dev/null +++ b/webapp/src/components/DAGGraph/elements/math.test.ts @@ -0,0 +1,20 @@ +import { updateBBox } from "./math"; + +test("compute bbox correctly", () => { + expect( + updateBBox( + [ + { x: 0, y: 0 }, + { x: 0, y: 0 }, + ], + { x: 0, y: 70 }, + { + height: 70, + width: 170, + } + ) + ).toStrictEqual([ + { x: 0, y: 0 }, + { x: 170, y: 140 }, + ]); +}); diff --git a/webapp/src/components/DAGGraph/elements/math.ts b/webapp/src/components/DAGGraph/elements/math.ts new file mode 100644 index 0000000..7acafd0 --- /dev/null +++ b/webapp/src/components/DAGGraph/elements/math.ts @@ -0,0 +1,37 @@ +import { Node, XYPosition } from "react-flow-renderer"; +import { Bbox, Size } from "./types"; + +export const pointApply = ( + p1: XYPosition, + p2: XYPosition, + fcn: (a: number, b: number) => number +): XYPosition => ({ + x: fcn(p1.x, p2.x), + y: fcn(p1.y, p2.y), +}); + +export const addSize = (p: XYPosition, size: Size): XYPosition => ({ + x: p.x + size.width, + y: p.y + size.height, +}); + +export const updateBBox = (bbox: Bbox, p: XYPosition, size: Size): Bbox => { + const ps = addSize(p, size); + return [pointApply(bbox[0], ps, Math.min), pointApply(bbox[1], ps, Math.max)]; +}; + +export const computeBBox = (nodes: Node[]): Bbox => { + return nodes.reduce( + (bbox: Bbox, n) => { + const p0 = n.position; + const height = n.data.height ?? n.style?.height; + const width = n.data.width ?? n.style?.width; + + return updateBBox(bbox, p0, { height, width }); + }, + [ + { x: 0, y: 0 }, + { x: 0, y: 0 }, + ] + ); +}; diff --git a/webapp/src/components/DAGGraph/elements/types.ts b/webapp/src/components/DAGGraph/elements/types.ts new file mode 100644 index 0000000..a0615bf --- /dev/null +++ b/webapp/src/components/DAGGraph/elements/types.ts @@ -0,0 +1,46 @@ +import { Edge, XYPosition } from "react-flow-renderer"; +import { AutomationNode } from "types/automations"; +import { Namer } from "utils/formatting"; +import { ModalState } from "../board/types"; +import { DAGAutomationFlowNode } from "../nodes"; +import { DAGGraphUpdater } from "../updater"; + +export type Bbox = [XYPosition, XYPosition]; +export type Size = { height: number; width: number }; +export type ElementData = { + nodes: DAGAutomationFlowNode[]; + edges: Edge[]; +}; +export type DAGEntityDim = Size; +export type DAGEntities = { + node: DAGEntityDim; + circle: DAGEntityDim; + condition: DAGEntityDim; + trigger: DAGEntityDim; +}; +export type DAGDims = DAGEntities & { + position: XYPosition; + distanceFactor: number; + flipped: boolean; +}; +export type ElementMakerBaseProps = { + stateUpdater: DAGGraphUpdater; + dims: DAGDims; + namer: Namer; + openModal: (m: ModalState) => void; +}; +export type ElementMakerProps = ElementMakerBaseProps & { + elementData: ElementData; + nodeId: string; + nodeIndex: number; + position: XYPosition; +}; +export type ElementMakerOutput = { + elementData: ElementData; + bbox: Bbox; +}; + +export type ElementMaker = ( + haNodes: A[], + args: ElementMakerProps +) => ElementMakerOutput; diff --git a/webapp/src/components/DAGGraph/error/index.tsx b/webapp/src/components/DAGGraph/error/index.tsx new file mode 100644 index 0000000..3b94ad7 --- /dev/null +++ b/webapp/src/components/DAGGraph/error/index.tsx @@ -0,0 +1,49 @@ +import { Button } from "components/Inputs/Button"; +import InputYaml from "components/Inputs/InputYaml"; +import { FC } from "react"; +import { DAGGraphBoardProps } from "../board/types"; + +export const ErroredBoard: FC< + DAGGraphBoardProps & { + error: Error | any; + } +> = (props) => { + // const makeSet = (k: K) => (d: FailedStateData[K]) => this.setState({ + // ...this.state, + // [k]: d, + // }); + // const makeSave = (k: K) => () => { + // if (!this.state.hasError) { + // return + // } + // if (k === 'condition') { + // this.props.onConditionUpdate(this.state.condition) + // } else if (k === 'sequence') { + // this.props.onSequenceUpdate(this.state.sequence) + // } else if (k === 'trigger') { + // this.props.onTriggerUpdate(this.state.trigger) + // } + // } + return ( +
+

An Error has occured.

+

Failed to Open Autmation!

+ Something is likely not configured in your automation properly. +
+

Error:

+ {/*

{String(this.state.error)}

*/} +
+ {/* {JSON.stringify(this.state.error, null, 4)} */} + {/* {this.state.errorInfo && this.state.errorInfo.componentStack.split('\n').map((s, i) => <> + {s}
+ )} */} +

Automation YAML

+ {/* + + + + + */} +
+ ); +}; diff --git a/webapp/src/components/DAGGraph/nodes/NodeMaker.tsx b/webapp/src/components/DAGGraph/nodes/NodeMaker.tsx new file mode 100644 index 0000000..6752af7 --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/NodeMaker.tsx @@ -0,0 +1,38 @@ +import { FC } from "react"; +import { NodeProps, XYPosition, Node } from "react-flow-renderer"; +import { DAGDims } from "../elements/types"; + +export type NodeMaker = ReturnType; +export const makeNodeMaker = < + NodeType extends string, + PreNodeData extends {}, + NodeData extends {} +>( + nodeType: NodeType, + DAGNode: FC, + convert: (pre: PreNodeData, dims: DAGDims) => NodeData +) => { + return { + get nodeType() { + return nodeType; + }, + GraphNode: (p: NodeProps) => { + return ; + }, + makeElement( + reactFlowProps: { + id: string; + position: XYPosition; + parentNode?: string; + }, + dims: DAGDims, + data: PreNodeData + ): Node { + return { + ...reactFlowProps, + type: nodeType, + data: convert(data, dims), + }; + }, + }; +}; diff --git a/webapp/src/components/DAGGraph/nodes/NodeManager.tsx b/webapp/src/components/DAGGraph/nodes/NodeManager.tsx new file mode 100644 index 0000000..c9242e3 --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/NodeManager.tsx @@ -0,0 +1,27 @@ +import { FC } from "react"; +import { NodeTypes } from "react-flow-renderer"; +import { makeNodeMaker } from "./NodeMaker"; +import { DAGDims } from "../elements/types"; + +export type NodeManager = typeof NodeManager; +export const NodeManager = (() => { + const nodeTypes: NodeTypes = {}; + return { + get nodeTypes() { + return nodeTypes; + }, + register: < + NodeType extends string, + PreNodeData extends {}, + NodeData extends {} + >( + nodeType: NodeType, + DAGNode: FC, + convert: (pre: PreNodeData, dims: DAGDims) => NodeData + ) => { + const nodeMaker = makeNodeMaker(nodeType, DAGNode, convert); + nodeTypes[nodeMaker.nodeType] = nodeMaker.GraphNode; + return nodeMaker; + }, + }; +})(); diff --git a/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNode.css b/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNode.css new file mode 100644 index 0000000..dc44549 --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNode.css @@ -0,0 +1,95 @@ +.sequence-node { + font-size: 0.9em; + display: flex; + justify-content: center; + align-items: center; + cursor: default; +} + +.sequence-node--inner { + position: relative; + display: flex; + flex-direction: row; + justify-content: center; + align-items: center; + padding: 0.25em 0.75em 0.5em 0.75em; + border-style: solid; + border-top-width: 0.25em; + border-left-width: 1px; + border-right-width: 1px; + border-radius: 10px; +} + + +.sequence-node--label { + flex: 1; + display: flex; + align-items: flex-start; + justify-content: center; + overflow: hidden; +} + +.sequence-node--label span { + text-align: center; + white-space: break-word; + overflow: hidden; + text-overflow: ellipsis; +} + +.sequence-node--enabled-flag { + position: absolute; + top: -1.5em; + right: -2.5em; +} + + +.sequence-node--midway-options { + position: absolute; + bottom: -2.5em; + left: calc(50%-0.5em); + z-index: 10; +} + +.sequence-node--midway-options button { + padding: 0; + color: var(--mui-primary-main); + background-color: var(--mui-primary-contrastText); +} + +.sequence-node--midway-options button:hover { + color: var(--mui-primary-dark); + background-color: var(--mui-primary-contrastText); +} + +.sequence-node .sequence-node--inner .speed-dial { + height: 2em; + width: 2em; + min-height: 2em; + max-height: 2em; + position: absolute; + top: -1em; + left: -1em; + background-color: var(--mui-common-black); + border-color: var(--mui-grey-400); + border-style: solid; + border-width: 0.5px; + border-radius: 20px; +} + +.open>.sequence-node--actions-btn, .sequence-node--actions-btn:hover { + color: var(--mui-common-black); + background-color: var(--mui-grey-400); + border-radius: 20px; +} + +.sequence-node--actions--move.right { + transform: rotate(180deg); +} + +.sequence-node--actions--move.up { + transform: rotate(90deg); +} + +.sequence-node--actions--move.down { + transform: rotate(270deg); +} \ No newline at end of file diff --git a/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNode.stories.tsx b/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNode.stories.tsx new file mode 100644 index 0000000..b092430 --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNode.stories.tsx @@ -0,0 +1,94 @@ +import React from "react"; +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import * as dgconst from "components/DAGFlow/constants"; +import { Page } from "components/Page"; +import { SequenceNode } from "./SequenceNode"; +import { DAGGraphBoard } from "components/DAGGraph/board"; +import { SequenceNodeMaker } from "./index"; +import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants"; + +export default { + title: "DAGGraph/Nodes/Sequence", + component: SequenceNode, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: { + color: "lblue", + height: dgconst.NODE_HEIGHT, + width: dgconst.NODE_WIDTH, + label: "test", + hasInput: true, + }, +} as ComponentMeta; + +const Template: ComponentStory = (args) => { + return ( + + {}} + state={{ + ready: true, + data: { + elements: { + edges: [], + nodes: [ + SequenceNodeMaker.makeElement( + { + id: "test", + position: { + x: 50, + y: 50, + }, + }, + DEFAULT_DIMS, + args + ), + ], + }, + }, + }} + /> + + ); +}; + +export const Colors: ComponentStory = (args) => { + return ( + + {}} + state={{ + ready: true, + data: { + elements: { + edges: [], + nodes: ["blue", "red", "green", "lblue"].map((color: any, i) => + SequenceNodeMaker.makeElement( + { + id: color, + position: { + x: 50 + dgconst.NODE_HEIGHT * dgconst.DISTANCE_FACTOR * i, + y: 50 + dgconst.NODE_HEIGHT * dgconst.DISTANCE_FACTOR * i, + }, + }, + DEFAULT_DIMS, + { ...args, color } + ) + ), + }, + }, + }} + /> + + ); +}; + +export const OnMoveAllDirections = Template.bind({}); +OnMoveAllDirections.args = { + ...OnMoveAllDirections.args, + onMove: { + up: console.log, + down: console.log, + left: console.log, + right: console.log, + }, +}; diff --git a/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNode.tsx b/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNode.tsx new file mode 100644 index 0000000..f9c83dc --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNode.tsx @@ -0,0 +1,24 @@ +import { FC } from "react"; +import { Handle, Position } from "react-flow-renderer"; +import { SequenceNodeProps } from "./types"; +import { SequenceNodeElement } from "./SequenceNodeElement"; + +export const SequenceNode: FC = ({ + hasInput = false, + ...props +}) => { + return ( + + {hasInput && ( + + )} + + + ); +}; diff --git a/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNodeElement.tsx b/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNodeElement.tsx new file mode 100644 index 0000000..b75bfcd --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/SequenceNode/SequenceNodeElement.tsx @@ -0,0 +1,148 @@ +import "./SequenceNode.css"; + +import { FC, PropsWithChildren } from "react"; +import { useConfirm } from "material-ui-confirm"; +import { useSnackbar } from "notistack"; + +import { useTheme } from "@mui/material/styles"; +import IconButton from "@mui/material/IconButton"; +import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; +import ArrowBackIcon from "@mui/icons-material/ArrowBack"; +import SettingsOutlinedIcon from "@mui/icons-material/SettingsOutlined"; +import Edit from "@mui/icons-material/Edit"; +import Add from "@mui/icons-material/Add"; + +import InputBoolean from "components/Inputs/InputBoolean"; +import { ButtonIcon } from "components/Icons/ButtonIcons"; +import { SpeedDial } from "components/SpeedDial"; +import { SequenceNodeElementProps } from "./types"; + +export const SequenceNodeElement: FC< + PropsWithChildren +> = ({ + label, + height, + width, + onXClick, + onEditClick = () => {}, + onAddNode, + onMove = {}, + color, + flipped, + enabled, + onSetEnabled, + children, +}) => { + const theme = useTheme(); + const confirm = useConfirm(); + const snackbr = useSnackbar(); + const nodeColor = + color === "blue" + ? theme.palette.info.main + : color === "green" + ? theme.palette.success.light + : color === "lblue" + ? theme.palette.info.light + : color === "red" + ? theme.palette.error.dark + : "none"; + return ( + <> +
+
+ + } + > + + + + {Object.entries(onMove).map(([key, action]) => ( + + + + ))} + {onXClick && ( + { + confirm({ + description: "Are you sure you want to delete this node?", + }) + .then(() => { + onXClick(); + snackbr.enqueueSnackbar("Deleted.", { + variant: "info", + }); + }) + .catch(() => + snackbr.enqueueSnackbar("Did not delete node.", { + variant: "info", + }) + ); + }} + size="small" + > + + + )} + + {!!onSetEnabled && ( + + )} + {children} +
+ {typeof label === "string" ? {label} : label} +
+
+ {onAddNode && ( +
+ } onClick={onAddNode} /> +
+ )} +
+ + ); +}; diff --git a/webapp/src/components/DAGGraph/nodes/SequenceNode/index.tsx b/webapp/src/components/DAGGraph/nodes/SequenceNode/index.tsx new file mode 100644 index 0000000..78f29dc --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/SequenceNode/index.tsx @@ -0,0 +1,13 @@ +import { NodeManager } from "components/DAGGraph/nodes/NodeManager"; +import { SequenceNode } from "./SequenceNode"; +import { SequenceNodeDataProps } from "./types"; + +export const SequenceNodeMaker = NodeManager.register( + "SequenceNode", + SequenceNode, + (pre: SequenceNodeDataProps, { node, flipped }) => ({ + ...node, + ...pre, + flipped, + }) +); diff --git a/webapp/src/components/DAGGraph/nodes/SequenceNode/types.ts b/webapp/src/components/DAGGraph/nodes/SequenceNode/types.ts new file mode 100644 index 0000000..9faf536 --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/SequenceNode/types.ts @@ -0,0 +1,35 @@ +import { ReactNode } from "react"; + +export type SequenceNodeColor = "red" | "blue" | "green" | "lblue"; +export type SequenceNodeOnMove = Record< + Direction, + () => void +>; +export type SequenceNodeActions = { + onXClick: () => void; + onEditClick: () => void; + onSetEnabled: () => void; + onAddNode: () => void; + onMove: SequenceNodeOnMoveEvents; +}; +export type SequenceNodeOnMoveEvents = Partial< + SequenceNodeOnMove<"up" | "down" | "left" | "right"> +>; +export type SequenceNodeBaseProps = Partial & { + color: SequenceNodeColor; + label: ReactNode; + enabled: boolean; +}; +export type SequenceNodeElementProps = SequenceNodeBaseProps & { + height: number; + width: number; + flipped: boolean; +}; +export type SequenceNodeDataProps = SequenceNodeBaseProps & { + hasInput?: boolean; +}; +export interface SequenceNodeProps extends SequenceNodeDataProps { + height: number; + width: number; + flipped: boolean; +} diff --git a/webapp/src/components/DAGGraph/nodes/TriggerNodes/TriggerNodes.tsx b/webapp/src/components/DAGGraph/nodes/TriggerNodes/TriggerNodes.tsx new file mode 100644 index 0000000..746c824 --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/TriggerNodes/TriggerNodes.tsx @@ -0,0 +1,35 @@ +import Add from "@mui/icons-material/Add"; +import { ButtonIcon } from "components/Icons/ButtonIcons"; +import { FC } from "react"; +import { SequenceNodeElement } from "../SequenceNode/SequenceNodeElement"; +import { TriggerNodeProps } from "./types"; + +export const TriggerNodes: FC = ({ + onAddNode, + nodes, + sequenceNode, + height, + width, + flipped, +}) => { + return ( +
+ {nodes.map((n, i) => ( + + ))} + } onClick={onAddNode} /> +
+ ); +}; diff --git a/webapp/src/components/DAGGraph/nodes/TriggerNodes/index.tsx b/webapp/src/components/DAGGraph/nodes/TriggerNodes/index.tsx new file mode 100644 index 0000000..6b5627c --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/TriggerNodes/index.tsx @@ -0,0 +1,14 @@ +import { NodeManager } from "components/DAGGraph/nodes/NodeManager"; +import { TriggerNodes } from "./TriggerNodes"; +import { TriggerNodeDataProps } from "./types"; + +export const TriggerNodesMaker = NodeManager.register( + "TriggerNodes", + TriggerNodes, + (pre: TriggerNodeDataProps, { node, trigger, flipped }) => ({ + ...pre, + ...trigger, + sequenceNode: node, + flipped, + }) +); diff --git a/webapp/src/components/DAGGraph/nodes/TriggerNodes/types.ts b/webapp/src/components/DAGGraph/nodes/TriggerNodes/types.ts new file mode 100644 index 0000000..2d680bc --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/TriggerNodes/types.ts @@ -0,0 +1,18 @@ +import { Size } from "components/DAGGraph/elements/types"; +import { ReactNode } from "react"; +import { SequenceNodeActions } from "../SequenceNode/types"; + +export type TriggerNodeChildProps = Partial & { + enabled: boolean; + label: ReactNode; +}; +export type TriggerNodeDataProps = { + nodes: TriggerNodeChildProps[]; + onAddNode: () => void; +}; + +export type TriggerNodeProps = TriggerNodeDataProps & + Size & { + sequenceNode: Size; + flipped: boolean; + }; diff --git a/webapp/src/components/DAGGraph/nodes/index.tsx b/webapp/src/components/DAGGraph/nodes/index.tsx new file mode 100644 index 0000000..01dbe0e --- /dev/null +++ b/webapp/src/components/DAGGraph/nodes/index.tsx @@ -0,0 +1,5 @@ +import { Node, NodeTypes } from "react-flow-renderer"; +import { NodeManager } from "./NodeManager"; + +export const nodeTypes: NodeTypes = NodeManager.nodeTypes; +export type DAGAutomationFlowNode = Node; diff --git a/webapp/src/components/DAGGraph/updater/index.ts b/webapp/src/components/DAGGraph/updater/index.ts new file mode 100644 index 0000000..622a09d --- /dev/null +++ b/webapp/src/components/DAGGraph/updater/index.ts @@ -0,0 +1,100 @@ +import { + AutomationActionData, + AutomationSequenceNode, +} from "types/automations"; +import { ModalState } from "../board/types"; +import { DAGUpdaterArgs } from "./types"; + +export const createBasicUpdater = + ( + k: K, + defaultNode: AutomationActionData[K][0] + ) => + (args: DAGUpdaterArgs) => { + return { + setEnabled: (i: number) => + args[k].onUpdate([ + ...args[k].data.slice(0, i), + { ...args[k].data[i], enabled: !(args[k].data[i].enabled ?? true) }, + ...args[k].data.slice(i + 1), + ]), + updateNode: (n: N, i: number) => + args[k].onUpdate([ + ...args[k].data.slice(0, i), + n, + ...args[k].data.slice(i + 1), + ]), + deleteNode: (i: number) => + args[k].onUpdate([ + ...args[k].data.slice(0, i), + ...args[k].data.slice(i + 1), + ]), + addNode: () => + args[k].onUpdate([ + ...args[k].data, + JSON.parse(JSON.stringify(defaultNode)), + ]), + }; + }; + +export type DAGGraphUpdater = ReturnType; +export const createUpdater = ( + args: DAGUpdaterArgs<"sequence" | "condition" | "trigger"> +) => ({ + basic: { + sequence: createBasicUpdater("sequence", { + device_id: "", + })({ + sequence: args.sequence, + openModal: args.openModal, + }), + trigger: createBasicUpdater("trigger", { + platform: "device", + })({ + trigger: args.trigger, + openModal: args.openModal, + } as any), + condition: createBasicUpdater("condition", { + condition: "device", + device_id: "", + domain: "", + type: "", + })({ + condition: args.condition, + openModal: args.openModal, + } as any), + }, +}); + +export const createUpdaterFromAutomationData = ( + openModal: (m: ModalState) => void, + auto: AutomationActionData, + onUpdate: (a: AutomationActionData) => void +): DAGGraphUpdater => + createUpdater({ + sequence: { + data: auto.sequence, + onUpdate: (s: AutomationSequenceNode[]) => + onUpdate({ + ...auto, + sequence: s, + }), + }, + condition: { + data: auto.condition, + onUpdate: (s: any) => + onUpdate({ + ...auto, + condition: s, + }), + }, + trigger: { + data: auto.trigger, + onUpdate: (s: any) => + onUpdate({ + ...auto, + trigger: s, + }), + }, + openModal, + }); diff --git a/webapp/src/components/DAGGraph/updater/types.ts b/webapp/src/components/DAGGraph/updater/types.ts new file mode 100644 index 0000000..8b3e342 --- /dev/null +++ b/webapp/src/components/DAGGraph/updater/types.ts @@ -0,0 +1,13 @@ +import { AutomationActionData, AutomationNode } from "types/automations"; +import { ModalState } from "../board/types"; + +export type DAGUpdaterInput = { + data: N[]; + onUpdate: (d: N[]) => void; +}; +export type DAGUpdaterArgs = Record< + K, + DAGUpdaterInput +> & { + openModal: (m: ModalState) => void; +}; diff --git a/webapp/src/components/SimpleErrorElement.tsx b/webapp/src/components/SimpleErrorElement.tsx new file mode 100644 index 0000000..a0b9f61 --- /dev/null +++ b/webapp/src/components/SimpleErrorElement.tsx @@ -0,0 +1,15 @@ +import { FC } from "react"; + +export const SimpleErrorElement: FC<{ error: Error }> = ({ error }) => { + return ( + <> + {error?.name} +
+ {error?.message} +
+ {error?.stack} +
+ {JSON.stringify(error)} + + ); +}; diff --git a/webapp/src/types/automations/index.ts b/webapp/src/types/automations/index.ts index 17d2048..29f65f2 100644 --- a/webapp/src/types/automations/index.ts +++ b/webapp/src/types/automations/index.ts @@ -1,32 +1,40 @@ -import * as st from 'superstruct' +import * as st from "superstruct"; import { ActionType, AutomationAction } from "./actions"; import { AutomationCondition, ConditionType } from "./conditions"; import { AutomationTrigger, TriggerType } from "./triggers"; import * as mv from "types/validators/metadata"; -export type AutomationMetadata = st.Infer -export interface AutomationData { - metadata: AutomationMetadata; +export type AutomationMetadata = st.Infer; +export interface AutomationActionData { trigger: AutomationTrigger[]; condition: AutomationCondition[]; sequence: AutomationSequenceNode[]; +} +export interface AutomationData extends AutomationActionData { + metadata: AutomationMetadata; tags: Record; } export type AutomationSequenceNode = AutomationAction | AutomationCondition; export type AutomationNodeMapping = { - "trigger": AutomationTrigger; - "action": AutomationAction; - "condition": AutomationCondition; -} + trigger: AutomationTrigger; + action: AutomationAction; + condition: AutomationCondition; +}; export type AutomationNodeTypes = keyof AutomationNodeMapping; export type AutomationNode = - N extends 'trigger' ? AutomationTrigger : - N extends 'action' ? AutomationAction : - N extends 'condition' ? AutomationCondition : - never; + N extends "trigger" + ? AutomationTrigger + : N extends "action" + ? AutomationAction + : N extends "condition" + ? AutomationCondition + : never; export type AutomationNodeSubtype = - T extends 'trigger' ? TriggerType : - T extends 'action' ? ActionType : - T extends 'condition' ? ConditionType : - never; + T extends "trigger" + ? TriggerType + : T extends "action" + ? ActionType + : T extends "condition" + ? ConditionType + : never;