using new board

This commit is contained in:
ari committed 2022-07-12 21:28:45 -04:00
1 parent 2d78319683
commit 595aa2dfa1
33 files changed
+312 -2629

No files matched your search

@@ -46,11 +46,11 @@
padding: 0.25em;
}
.automation-editor--flow-wrapper.changed>.automation-editor--flow-wrapper--flow {
.automation-editor--flow-wrapper.changed>.dag-graphboard {
border-color: var(--mui-success-light);
}
.automation-editor--flow-wrapper--flow {
.dag-graphboard {
flex: 1;
border: 1px solid var(--mui-grey-700);
margin: 0 0 0.5em 0;
@@ -1,100 +1,99 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { AutomationEditor } from './index';
import { useState } from 'react';
import * as dgconst from 'components/DAGFlow/constants';
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { AutomationEditor } from "./index";
import { useState } from "react";
import { Page } from "components/Page";
import { makeTagDB } from "components/AutomationList/TagDB";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
export default {
title: 'App/AutomationList/Editor',
title: "App/AutomationList/Editor",
component: AutomationEditor,
parameters: { actions: { argTypesRegex: '^on.*' } },
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
dims: dgconst.DEFAULT_DIMS,
}
} as ComponentMeta<typeof AutomationEditor>
dims: DEFAULT_DIMS,
},
} as ComponentMeta<typeof AutomationEditor>;
const Template: ComponentStory<typeof AutomationEditor> = args => {
const [state, setState] = useState(args.automation)
return <Page>
<AutomationEditor
{...args}
tagDB={makeTagDB(state ? [state] : [])}
automation={state}
onUpdate={s => {
window.setTimeout(() => setState(s), 3000)
}}
/>
</Page>
}
const Template: ComponentStory<typeof AutomationEditor> = (args) => {
const [state, setState] = useState(args.automation);
return (
<Page>
<AutomationEditor
{...args}
tagDB={makeTagDB(state ? [state] : [])}
automation={state}
onUpdate={(s) => {
window.setTimeout(() => setState(s), 3000);
}}
/>
</Page>
);
};
export const Loading = Template.bind({});
export const Simple = Template.bind({})
export const Simple = Template.bind({});
Simple.args = {
...Simple.args,
automation: {
condition: [],
tags: {
"Room": "Bathroom",
"For": "Toliet",
"Type": "Smell",
"Use": "Flushing"
Room: "Bathroom",
For: "Toliet",
Type: "Smell",
Use: "Flushing",
},
metadata: {
id: "random",
alias: "Random",
description: "Example Metadata",
trigger_variables: {
'wowo': '!'
wowo: "!",
},
mode: 'single',
mode: "single",
},
trigger: [
{
"platform": "numeric_state",
"entity_id": "test",
platform: "numeric_state",
entity_id: "test",
},
{
"platform": "homeassistant",
"event": "start",
}
platform: "homeassistant",
event: "start",
},
],
sequence: [
{
condition: 'and',
condition: "and",
conditions: [
{
condition: 'numeric_state',
entity_id: 'sensor.temperature_kitchen',
below: '15',
condition: "numeric_state",
entity_id: "sensor.temperature_kitchen",
below: "15",
},
{
condition: 'template',
value_template: 'states(switch.kitchen_light) == "on"'
}
]
condition: "template",
value_template: 'states(switch.kitchen_light) == "on"',
},
],
},
{
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
service: "media_player.play_media",
target: {
entity_id: "media_player.kitchen_dot"
entity_id: "media_player.kitchen_dot",
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
]
}
}
},
},
],
},
};
export const EmptyStart = Template.bind({})
export const EmptyStart = Template.bind({});
EmptyStart.args = {
...EmptyStart.args,
automation: {
@@ -105,31 +104,28 @@ EmptyStart.args = {
alias: "Random",
description: "Example Metadata",
trigger_variables: {
'wowo': '!'
wowo: "!",
},
mode: 'single',
mode: "single",
},
trigger: [
],
sequence: []
}
}
trigger: [],
sequence: [],
},
};
export const BadAutomationInvalidMetadata = Template.bind({})
export const BadAutomationInvalidMetadata = Template.bind({});
BadAutomationInvalidMetadata.args = {
...BadAutomationInvalidMetadata.args,
automation: {
condition: [],
tags: {},
metadata: {
} as any,
trigger: [
],
sequence: []
}
}
metadata: {} as any,
trigger: [],
sequence: [],
},
};
export const BadAutomationInvalidTriggers = Template.bind({})
export const BadAutomationInvalidTriggers = Template.bind({});
BadAutomationInvalidTriggers.args = {
...BadAutomationInvalidTriggers.args,
automation: {
@@ -140,18 +136,16 @@ BadAutomationInvalidTriggers.args = {
alias: "Random",
description: "Example Metadata",
trigger_variables: {
'wowo': '!'
wowo: "!",
},
mode: 'single',
mode: "single",
},
trigger: [
"haha I am a string"
] as any,
sequence: []
}
}
trigger: ["haha I am a string"] as any,
sequence: [],
},
};
export const BadAutomationInvalidSequence = Template.bind({})
export const BadAutomationInvalidSequence = Template.bind({});
BadAutomationInvalidSequence.args = {
...BadAutomationInvalidSequence.args,
automation: {
@@ -162,15 +156,15 @@ BadAutomationInvalidSequence.args = {
alias: "Bad Choose Sequence",
description: "Example Metadata",
trigger_variables: {
'wowo': '!'
wowo: "!",
},
mode: 'single',
mode: "single",
},
trigger: [],
sequence: [
{
choose: {}
}
] as any
}
}
choose: {},
},
] as any,
},
};
@@ -7,8 +7,6 @@ import { AutoInfoBox } from "./AutoInfoBox";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { Button } from "components/Inputs/Button";
import { useAutomatioEditorState, EditorData } from "./state";
import { SafeDAGAutomationFlow } from "components/DAGFlow/safe";
import { DAGAutomationFlowDims } from "components/DAGFlow/types";
import { MiniFailure } from "types/validators/helper";
import InputYaml from "components/Inputs/InputYaml";
import { TagDB } from "components/AutomationList/TagDB";
@@ -16,10 +14,12 @@ import Skeleton from "@mui/material/Skeleton";
import LinearProgress from "@mui/material/LinearProgress";
import { ArrowBack } from "@mui/icons-material";
import { useCookies } from "react-cookie";
import { DAGDims } from "components/DAGGraph/elements/types";
import { DAGAutomationGraph } from "components/DAGGraph";
interface Props {
automation?: AutomationData;
dims: DAGAutomationFlowDims;
dims: DAGDims;
onUpdate: (auto: AutomationData) => void;
tagDB: TagDB;
}
@@ -112,18 +112,14 @@ export const AutomationEditor: FC<Props> = ({
Save <CheckMarkIcon color="#bf4" />
</Button>
</div>
<SafeDAGAutomationFlow
className="automation-editor--flow-wrapper--flow"
<DAGAutomationGraph
sequence={state.data.sequence}
trigger={state.data.trigger}
condition={state.data.condition}
onSequenceUpdate={updateSequence}
onTriggerUpdate={updateTrigger}
onConditionUpdate={updateCondition}
dims={{
...dims,
flipped,
}}
isFlipped={flipped}
/>
</div>
</div>
@@ -3,95 +3,89 @@ import { ComponentMeta, ComponentStory } from "@storybook/react";
import { useState } from "react";
import { AutomationList } from ".";
import { bigMockAutoList } from "utils/mocks";
import * as dgconst from 'components/DAGFlow/constants';
import { Page } from "components/Page";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
export default {
title: 'App/AutomationList',
title: "App/AutomationList",
component: AutomationList,
parameters: { actions: { argTypesRegex: '^on.*' } },
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
dims: dgconst.DEFAULT_DIMS
}
dims: DEFAULT_DIMS,
},
} as ComponentMeta<typeof AutomationList>;
const Template: ComponentStory<typeof AutomationList> = (args) => {
const [autos, setAutos] = useState(args.automations);
return (
<Page>
<AutomationList
{...args}
automations={autos}
onAdd={(a) => {
args.onAdd(a);
setAutos([...autos, a]);
}}
onRemove={(i) => {
args.onRemove(i);
setAutos([...autos.slice(0, i), ...autos.slice(i + 1)]);
}}
onUpdate={(i, a) => {
args.onUpdate(i, a);
setAutos([...autos.slice(0, i), a, ...autos.slice(i + 1)]);
}}
/>
</Page>
);
};
const Template: ComponentStory<typeof AutomationList> = args => {
const [autos, setAutos] = useState(args.automations)
return <Page>
<AutomationList {...args} automations={autos}
onAdd={a => {
args.onAdd(a);
setAutos([...autos, a]);
}}
onRemove={i => {
args.onRemove(i);
setAutos([
...autos.slice(0, i),
...autos.slice(i + 1),
]);
}}
onUpdate={(i, a) => {
args.onUpdate(i, a);
setAutos([
...autos.slice(0, i),
a,
...autos.slice(i + 1),
]);
}}
/>
</Page>
}
export const EmptyStart = Template.bind({})
export const EmptyStart = Template.bind({});
EmptyStart.args = {
...EmptyStart.args,
automations: [],
}
};
export const FewAutos = Template.bind({})
export const FewAutos = Template.bind({});
FewAutos.args = {
...FewAutos.args,
automations: bigMockAutoList,
}
};
export const BadAutmations = Template.bind({})
export const BadAutmations = Template.bind({});
BadAutmations.args = {
...BadAutmations.args,
automations: [
{
"metadata": {
"alias": "Set Thermostat to 76 at 8am",
"description": "",
"mode": "single",
metadata: {
alias: "Set Thermostat to 76 at 8am",
description: "",
mode: "single",
} as any,
"trigger": [
trigger: [
{
"at": "08:00:00",
"platform": "time"
}
at: "08:00:00",
platform: "time",
},
],
"condition": [
condition: [
{
"condition": "state",
"entity_id": "climate.thermostat",
"state": "cool"
}
condition: "state",
entity_id: "climate.thermostat",
state: "cool",
},
],
"sequence": [
sequence: [
{
"data": {
"temperature": 76
data: {
temperature: 76,
},
"service": "climate.set_temperature",
"target": {
"entity_id": "climate.thermostat"
}
}
service: "climate.set_temperature",
target: {
entity_id: "climate.thermostat",
},
},
],
"tags": {},
tags: {},
},
{
condition: [],
@@ -101,16 +95,16 @@ BadAutmations.args = {
alias: "Bad Choose",
description: "Example Metadata",
trigger_variables: {
'wowo': '!'
wowo: "!",
},
mode: 'single',
mode: "single",
},
trigger: [],
sequence: [
{
choose: {}
}
] as any
choose: {},
},
] as any,
},
{
condition: [],
@@ -120,61 +114,55 @@ BadAutmations.args = {
alias: "Bad Trigger",
description: "Example Metadata",
trigger_variables: {
'wowo': '!'
wowo: "!",
},
mode: 'single',
mode: "single",
},
trigger: [
"haha I am a string"
] as any,
sequence: []
trigger: ["haha I am a string"] as any,
sequence: [],
},
{
condition: [],
tags: {},
metadata: {
} as any,
trigger: [
],
sequence: []
}
metadata: {} as any,
trigger: [],
sequence: [],
},
],
}
};
export const FewAutosWithSlowLoader: ComponentStory<typeof AutomationList> = args => {
const [autos, setAutos] = useState(args.automations)
return <Page>
<AutomationList {...args} automations={autos}
onAdd={a => {
window.setTimeout(() => {
args.onAdd(a);
setAutos([...autos, a]);
}, 10000)
}}
onRemove={i => {
window.setTimeout(() => {
args.onRemove(i);
setAutos([
...autos.slice(0, i),
...autos.slice(i + 1),
]);
}, 10000)
}}
onUpdate={(i, a) => {
window.setTimeout(() => {
args.onUpdate(i, a);
setAutos([
...autos.slice(0, i),
a,
...autos.slice(i + 1),
]);
}, 10000)
}}
/>
</Page>
}
export const FewAutosWithSlowLoader: ComponentStory<typeof AutomationList> = (
args
) => {
const [autos, setAutos] = useState(args.automations);
return (
<Page>
<AutomationList
{...args}
automations={autos}
onAdd={(a) => {
window.setTimeout(() => {
args.onAdd(a);
setAutos([...autos, a]);
}, 10000);
}}
onRemove={(i) => {
window.setTimeout(() => {
args.onRemove(i);
setAutos([...autos.slice(0, i), ...autos.slice(i + 1)]);
}, 10000);
}}
onUpdate={(i, a) => {
window.setTimeout(() => {
args.onUpdate(i, a);
setAutos([...autos.slice(0, i), a, ...autos.slice(i + 1)]);
}, 10000);
}}
/>
</Page>
);
};
FewAutosWithSlowLoader.args = {
...FewAutosWithSlowLoader.args,
automations: bigMockAutoList,
}
};
@@ -1,5 +1,4 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { DEFAULT_DIMS } from "components/DAGFlow/constants";
import { Page } from "components/Page";
import { MetadataBoxTag } from "./AutomationMetadataBox";
import { useState } from "react";
@@ -2,34 +2,31 @@ import { ComponentMeta, ComponentStory } from "@storybook/react";
import { ConnectedAutomationList } from ".";
import { createMockAuto } from "utils/mocks";
import { useMockApiService } from "apiService";
import { DEFAULT_DIMS } from 'components/DAGFlow/constants';
import { Page } from "components/Page";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
export default {
title: 'App/AutomationList/Connected',
title: "App/AutomationList/Connected",
component: ConnectedAutomationList,
parameters: { actions: { argTypesRegex: '^on.*' } },
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
dims: DEFAULT_DIMS,
initialAutomations: [],
}
},
} as ComponentMeta<typeof ConnectedAutomationList>;
const Template: ComponentStory<any> = args => {
const Template: ComponentStory<any> = (args) => {
const api = useMockApiService(args.initialAutomations);
return <Page>
<ConnectedAutomationList
{...args}
api={api}
/>
</Page>
}
return (
<Page>
<ConnectedAutomationList {...args} api={api} />
</Page>
);
};
export const EmptyStart = Template.bind({})
export const EmptyStart = Template.bind({});
export const FewAutos = Template.bind({})
export const FewAutos = Template.bind({});
FewAutos.args = {
...FewAutos.args,
initialAutomations: [
@@ -44,21 +41,23 @@ FewAutos.args = {
createMockAuto(),
createMockAuto(),
],
}
};
export const Loading: ComponentStory<any> = args => {
export const Loading: ComponentStory<any> = (args) => {
const api = useMockApiService(args.initialAutomations);
return <Page>
<ConnectedAutomationList
{...args}
api={{
...api,
state: {
"automations": {
"ready": false
}
}
}}
/>
</Page>
}
return (
<Page>
<ConnectedAutomationList
{...args}
api={{
...api,
state: {
automations: {
ready: false,
},
},
}}
/>
</Page>
);
};
@@ -7,7 +7,6 @@ import { defaultAutomation } from "utils/defaults";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { ApiService } from "apiService/core";
import { AutomationListBox } from "./AutomationListBox";
import { DAGAutomationFlowDims } from "components/DAGFlow/types";
import useWindowSize from "utils/useWindowSize";
import { makeTagDB } from "./TagDB";
import LinearProgress from "@mui/material/LinearProgress";
@@ -16,13 +15,14 @@ import { useCookies } from "react-cookie";
import { useHA } from "haService";
import { ArrowBack } from "@mui/icons-material";
import { useSnackbar } from "notistack";
import { DAGDims } from "components/DAGGraph/elements/types";
interface AutomationListParams {
automations: AutomationData[];
onUpdate: (i: number, auto: AutomationData) => void;
onAdd: (auto: AutomationData) => void;
onRemove: (i: number) => void;
dims: DAGAutomationFlowDims;
dims: DAGDims;
children?: ReactNode;
}
@@ -134,7 +134,7 @@ export const AutomationList: FC<AutomationListParams> = ({
};
interface ConnectedAutomationListParams {
dims: DAGAutomationFlowDims;
dims: DAGDims;
api: ApiService;
}
export const ConnectedAutomationList: FC<ConnectedAutomationListParams> = ({
@@ -1,61 +0,0 @@
import { FC } from "react";
import { AddIcon, TrashIcon } from '../Icons/index';
import { useCircleStyles } from './styles';
import { Handle, Position, XYPosition } from 'react-flow-renderer';
export interface DAGCircleProps {
onAdd?: () => void;
onRemove?: () => void;
size: number,
backgroundColor?: string;
disableSource?: boolean;
disableTarget?: boolean;
flipped: boolean;
}
export const makeFlowCircle = (
circleId: string,
position: XYPosition,
data: DAGCircleProps,
) => ({
id: circleId,
type: 'dagcircle',
position,
data
})
export const DAGCircle: FC<{ data: DAGCircleProps }> = ({
data: {
size,
onAdd,
onRemove,
backgroundColor,
disableSource = false,
disableTarget = false,
flipped,
}
}) => {
const { classes } = useCircleStyles({
size,
hasOnFunction: !!onRemove || !!onAdd,
hasRemoveFunction: !!onRemove,
backgroundColor,
});
return <>
{!disableSource && <Handle type="source" position={flipped ? Position.Bottom : Position.Right} />}
{!disableTarget && <Handle type="target" position={flipped ? Position.Top : Position.Left} />}
<div className={classes.root}>
{
onAdd ?
<AddIcon
size={70} units="%"
className={classes.icon}
onClick={onAdd}
/>
: (backgroundColor || onRemove) ? "" : "else"
}
{onRemove ? <TrashIcon className={classes.trashIcon} onClick={onRemove} /> : <></>}
</div>
</>
}
@@ -1,53 +0,0 @@
.dagnode-error {
display: flex;
flex-direction: column;
justify-content: flex-end;
font-size: 0.85em;
z-index: 0;
}
.dagnode-error.open .dagnode-error--inner {
align-items: flex-start;
padding-top: 1em;
}
.dagnode-error--inner {
position: relative;
flex: 1;
/* internal positioning */
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
gap: 0.5em;
/* shape */
background-color: var(--mui-error-dark);
border-radius: 1em;
height: 100%;
max-height: 100%;
max-width: 100%;
margin-top: 2.5px;
margin-bottom: 2.5px;
border-top-width: 1px;
border-top-style: solid;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
border-top-color: var(--mui-error-main);
}
.dagnode-error--inner:hover {
background-color: var(--mui-error-contrastText);
cursor: default;
}
.dagnode-error--inner--edit-icon:hover {
transform: rotate(180deg);
cursor: pointer;
background-color: var(--mui-error-main);
padding: 0.5em;
border-radius: 10px;
height: 0.25em;
width: 0.25em;
}
@@ -1,47 +0,0 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { DAGAutomationFlow } from '.';
import * as dgconst from "components/DAGFlow/constants";
import ReactFlow, { Controls } from 'react-flow-renderer';
import { DAGErrorNode } from "./DAGErrorNode";
import { convertToFlowNode } from "./helpers";
import { Page } from "components/Page";
export default {
title: 'DAGAutomationFlow/Viewer/DAGErrorNode',
component: DAGAutomationFlow,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
"height": dgconst.NODE_HEIGHT,
"width": dgconst.NODE_WIDTH,
}
} as ComponentMeta<typeof DAGErrorNode>
export const Examples: ComponentStory<typeof DAGErrorNode> = args => {
const nodes = ["1", "2", "3", "4"].map((id, i) => ({
"data": args,
"id": id,
"type": "mynode",
"position": {
"x": 50 + dgconst.NODE_HEIGHT * dgconst.DISTANCE_FACTOR * i,
"y": 50 + dgconst.NODE_HEIGHT * dgconst.DISTANCE_FACTOR * i
}
}));
return <Page>
<ReactFlow
defaultNodes={nodes}
nodeTypes={{
"mynode": convertToFlowNode(DAGErrorNode)
}}
snapToGrid
onlyRenderVisibleElements
nodesConnectable={false}
nodesDraggable={false}
>
<Controls />
</ReactFlow>
</Page>
}
@@ -1,56 +0,0 @@
import "./DAGErrorNode.css";
import { Handle, Position } from "react-flow-renderer";
import { FC } from "react";
import { InfoIcon, PencilIcon } from "components/Icons";
export interface DAGErrorNodeProps {
height: number;
width: number;
flipped: boolean;
hasInput?: boolean;
error?: any;
onEdit: () => void;
}
export const DAGErrorNode: FC<DAGErrorNodeProps> = ({
height,
width,
hasInput,
error,
onEdit,
flipped,
}) => {
// render
return (
<>
{hasInput && (
<Handle
type="target"
position={flipped ? Position.Top : Position.Left}
/>
)}
<Handle
type="source"
position={flipped ? Position.Bottom : Position.Right}
/>
<div
className={["dagnode-error"].join(" ")}
style={{
height,
width,
maxHeight: height,
maxWidth: width,
}}
>
<div className={"dagnode-error--inner"} title={String(error)}>
<InfoIcon color="var(--mui-error-light)" size={1.25} />
Invalid Node
<PencilIcon
className="dagnode-error--inner--edit-icon"
size={1.25}
onClick={onEdit}
/>
</div>
</div>
</>
);
};
@@ -1,155 +0,0 @@
import { AutomationSequenceNode } from "types/automations";
import { ModalState } from "./types";
import { makeDagFlowUpdate } from "./DAGFlowUpdater";
import { AutomationTrigger } from "types/automations/triggers";
import { AutomationCondition } from "types/automations/conditions";
const mockDAGFlowUpdater = (
initialSequences: AutomationSequenceNode[] = [],
initialTriggers: AutomationTrigger[] = [],
initialConditions: AutomationCondition[] = []
) => {
let sequence = [...initialSequences];
let trigger = [...initialTriggers];
let condition = [...initialConditions];
const modalStates: ModalState[] = [];
const updater = makeDagFlowUpdate({
sequence,
trigger,
condition,
openModal: (m) => {
modalStates.push(m);
},
onTriggerUpdate: (t) => {
trigger = [...t];
},
onSequenceUpdate: (s) => {
sequence = [...s];
},
onConditionUpdate: (c) => {
condition = [...c];
},
});
return {
get condition() {
return condition;
},
get trigger() {
return trigger;
},
get sequence() {
return sequence;
},
get modalStates() {
return modalStates;
},
updater,
};
};
test("DAGFlowUpdater.onaddNode add node when we have nothing", () => {
const emptyMock = mockDAGFlowUpdater();
emptyMock.updater.addNode(null, "sequence");
expect(emptyMock.modalStates.length).toEqual(1);
emptyMock.modalStates[0].update({
device_id: "testme",
});
expect((emptyMock.sequence[0] as any).device_id).toEqual("testme");
});
test("DAGFlowUpdater.onaddNode add node to end when we have 1 thing", () => {
const mock = mockDAGFlowUpdater([
{
choose: [],
},
]);
mock.updater.addNode(null, "sequence");
expect(mock.modalStates.length).toEqual(1);
mock.modalStates[0].update({
device_id: "testme",
});
expect(mock.sequence.length).toEqual(2);
expect((mock.sequence[1] as any).device_id).toEqual("testme");
});
test("DAGFlowUpdater.onaddNode add node to start when we have 1 thing", () => {
const mock = mockDAGFlowUpdater([
{
choose: [],
},
]);
mock.updater.addNode(0, "sequence");
expect(mock.modalStates.length).toEqual(1);
mock.modalStates[0].update({
device_id: "testme",
});
expect(mock.sequence.length).toEqual(2);
expect((mock.sequence[0] as any).device_id).toEqual("testme");
});
test("DAGFlowUpdater.onaddNode add node to start when we have many things", () => {
const mock = mockDAGFlowUpdater([
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
]);
mock.updater.addNode(0, "sequence");
expect(mock.modalStates.length).toEqual(1);
mock.modalStates[0].update({
device_id: "testme",
});
expect(mock.sequence.length).toEqual(8);
expect((mock.sequence[0] as any).device_id).toEqual("testme");
});
test("DAGFlowUpdater.onaddNode add node to middle when we have many things", () => {
const mock = mockDAGFlowUpdater([
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
{
choose: [],
},
]);
mock.updater.addNode(2, "sequence");
expect(mock.modalStates.length).toEqual(1);
mock.modalStates[0].update({
device_id: "testme",
});
expect(mock.sequence.length).toEqual(8);
expect((mock.sequence[2] as any).device_id).toEqual("testme");
});
@@ -1,116 +0,0 @@
import { AutomationSequenceNode } from "types/automations";
import { AutomationCondition } from "types/automations/conditions";
import { AutomationTrigger } from "types/automations/triggers";
import { Namer } from "utils/formatting";
import { makeOnEditAutomationConditions } from "./helpers";
import { ModalState, TriggerMakerOptions } from "./types";
import { makeSequenceUpdater, SequenceUpdater } from "./updater";
export type DagFlowUpdateBaseArgs = {
trigger: AutomationTrigger[];
condition: AutomationCondition[];
sequence: AutomationSequenceNode[];
onTriggerUpdate: (t: AutomationTrigger[]) => void;
onSequenceUpdate: (s: AutomationSequenceNode[]) => void;
onConditionUpdate: (s: AutomationCondition[]) => void;
};
export type DagFlowUpdateArgs = DagFlowUpdateBaseArgs & {
openModal: (m: ModalState) => void;
};
export type DagFlowUpdate = ReturnType<typeof makeDagFlowUpdate>;
export const makeDagFlowUpdate = (args: DagFlowUpdateArgs) => {
const methods = {
addNode(
afterIndex: number | null,
nodeType: "sequence" | "trigger" | "only-conditions"
) {
return args.openModal({
saveBtnCreateText: true,
node:
nodeType === "sequence"
? {
device_id: "",
}
: nodeType === "trigger"
? {
id: "",
}
: {
condition: "and",
conditions: [],
},
update: (n) => {
if (afterIndex !== null) {
args.onSequenceUpdate([
...args.sequence.slice(0, afterIndex),
n,
...args.sequence.slice(afterIndex),
]);
} else {
args.onSequenceUpdate([...args.sequence, n]);
}
},
allowedTypes:
nodeType === "sequence"
? ["action", "condition"]
: nodeType === "trigger"
? ["trigger"]
: ["condition"],
});
},
onEditAutomationConditions() {
return makeOnEditAutomationConditions(
args.condition,
args.onConditionUpdate,
args.openModal
)();
},
makeTriggerMakerOptions(namer: Namer): TriggerMakerOptions {
return {
namer,
onAdd: () =>
args.openModal({
saveBtnCreateText: true,
node: {
platform: "device",
},
update: (n) => {
args.onTriggerUpdate([...args.trigger, n]);
},
allowedTypes: ["trigger"],
}),
onDelete: (i) =>
args.onTriggerUpdate([
...args.trigger.slice(0, i),
...args.trigger.slice(i + 1),
]),
onEdit: (i) =>
args.openModal({
node: args.trigger[i],
update: (t) =>
args.onTriggerUpdate([
...args.trigger.slice(0, i),
t,
...args.trigger.slice(i + 1),
]),
allowedTypes: ["trigger"],
}),
onSetEnabled: (i) =>
args.onTriggerUpdate([
...args.trigger.slice(0, i),
{ ...args.trigger[i], enabled: !(args.trigger[i].enabled ?? true) },
...args.trigger.slice(i + 1),
]),
};
},
get sequenceUpdater(): SequenceUpdater {
return makeSequenceUpdater(
args.sequence,
args.onSequenceUpdate,
args.openModal
);
},
};
return methods;
};
-95
View File
@@ -1,95 +0,0 @@
.dagnode {
font-size: 0.9em;
display: flex;
justify-content: center;
align-items: center;
cursor: default;
}
.dagnode--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;
}
.dagnode--label {
flex: 1;
display: flex;
align-items: flex-start;
justify-content: center;
overflow: hidden;
}
.dagnode--label span {
text-align: center;
white-space: break-word;
overflow: hidden;
text-overflow: ellipsis;
}
.dagnode--enabled-flag {
position: absolute;
top: -1.5em;
right: -2.5em;
}
.dagnode--midway-options {
position: absolute;
bottom: -2.5em;
left: calc(50%-0.5em);
z-index: 10;
}
.dagnode--midway-options button {
padding: 0;
color: var(--mui-primary-main);
background-color: var(--mui-primary-contrastText);
}
.dagnode--midway-options button:hover {
color: var(--mui-primary-dark);
background-color: var(--mui-primary-contrastText);
}
.dagnode .dagnode--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>.dagnode--actions-btn, .dagnode--actions-btn:hover {
color: var(--mui-common-black);
background-color: var(--mui-grey-400);
border-radius: 20px;
}
.dagnode--actions--move.right {
transform: rotate(180deg);
}
.dagnode--actions--move.up {
transform: rotate(90deg);
}
.dagnode--actions--move.down {
transform: rotate(270deg);
}
Whitespace-only changes.
@@ -1,86 +0,0 @@
import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { DAGAutomationFlow } from ".";
import * as dgconst from "components/DAGFlow/constants";
import ReactFlow, { Controls } from "react-flow-renderer";
import { DAGNode } from "./DAGNode";
import { convertToFlowNode } from "./helpers";
import { Page } from "components/Page";
export default {
title: "DAGAutomationFlow/Viewer/DAGNode",
component: DAGAutomationFlow,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
color: "lblue",
height: dgconst.NODE_HEIGHT,
width: dgconst.NODE_WIDTH,
label: "test",
hasInput: true,
},
} as ComponentMeta<typeof DAGNode>;
const Template: ComponentStory<typeof DAGNode> = (args) => {
return (
<Page>
<ReactFlow
defaultNodes={[
{
id: "one",
position: { x: 0, y: 0 },
type: "mynode",
data: args,
},
]}
nodeTypes={{
mynode: convertToFlowNode(DAGNode),
}}
snapToGrid
onlyRenderVisibleElements
nodesConnectable={false}
nodesDraggable={false}
>
<Controls />
</ReactFlow>
</Page>
);
};
export const Colors: ComponentStory<typeof DAGNode> = (args) => {
const nodes = ["blue", "red", "green", "lblue"].map((color, i) => ({
data: { ...args, color },
id: color,
type: "mynode",
position: {
x: 50 + dgconst.NODE_HEIGHT * dgconst.DISTANCE_FACTOR * i,
y: 50 + dgconst.NODE_HEIGHT * dgconst.DISTANCE_FACTOR * i,
},
}));
return (
<Page>
<ReactFlow
defaultNodes={nodes}
nodeTypes={{
mynode: convertToFlowNode(DAGNode),
}}
snapToGrid
onlyRenderVisibleElements
nodesConnectable={false}
nodesDraggable={false}
>
<Controls />
</ReactFlow>
</Page>
);
};
export const OnMoveAllDirections = Template.bind({});
OnMoveAllDirections.args = {
...OnMoveAllDirections.args,
onMove: {
up: console.log,
down: console.log,
left: console.log,
right: console.log,
},
};
-206
View File
@@ -1,206 +0,0 @@
import "./DAGNode.css";
import "./DAGNode.flipped.css";
import { NodeColor } from "types/graphs";
import { Handle, Position } from "react-flow-renderer";
import { FC, ReactNode } from "react";
import IconButton from "@mui/material/IconButton";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import SettingsOutlinedIcon from "@mui/icons-material/SettingsOutlined";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { createToNodeMakerFunction } from "./helpers";
import { SpeedDial } from "components/SpeedDial";
import Edit from "@mui/icons-material/Edit";
import { useTheme } from "@mui/material";
import InputBoolean from "components/Inputs/InputBoolean";
import { useConfirm } from "material-ui-confirm";
import { useSnackbar } from "notistack";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import Add from "@mui/icons-material/Add";
export type DAGNodeOnMove<Direction extends string> = Record<
Direction,
() => void
>;
export type DAGNodeOnMoveEvents = Partial<
DAGNodeOnMove<"up" | "down" | "left" | "right">
>;
export interface DAGNodeDataProps {
onXClick?: () => void;
onEditClick?: () => void;
onSetEnabled?: () => void;
onAddNode?: () => void;
onMove?: DAGNodeOnMoveEvents;
color: NodeColor;
label: ReactNode;
hasInput?: boolean;
enabled: boolean;
}
export interface DAGNodeProps extends DAGNodeDataProps {
height: number;
width: number;
flipped: boolean;
}
export const makeConditionPoint = createToNodeMakerFunction<
{
label: ReactNode;
onEditClick: () => void;
onAddNode: () => void;
},
DAGNodeProps
>((pre, { conditionWidth, conditionHeight, flipped }) => ({
color: "lblue",
height: conditionHeight,
width: conditionWidth,
hasInput: true,
enabled: true,
flipped,
...pre,
}));
export const makeActionPoint = createToNodeMakerFunction<
DAGNodeDataProps,
DAGNodeProps
>((pre, { nodeHeight, nodeWidth, flipped }) => ({
...pre,
height: nodeHeight,
width: nodeWidth,
flipped,
}));
export const DAGNode: FC<DAGNodeProps> = ({
label,
height,
width,
onXClick,
onEditClick = () => {},
onAddNode,
onMove = {},
color,
hasInput = false,
flipped,
enabled,
onSetEnabled,
}) => {
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 (
<>
<div
className={[
"dagnode",
flipped ? "flipped" : "",
enabled ? "enabled" : "disabled",
].join(" ")}
style={{
height,
width,
}}
>
<div
className="dagnode--inner"
style={{
maxHeight: `calc(${height}px - 1em)`,
maxWidth: `calc(${width}px - 1em)`,
minWidth: Math.max(width / 2, height / 2),
borderBottomColor: theme.palette.grey[500],
borderLeftColor: theme.palette.grey[700],
borderRightColor: theme.palette.grey[700],
borderTopColor: nodeColor,
backgroundColor: enabled
? theme.palette.background.default
: theme.palette.grey[600],
}}
>
<SpeedDial
icon={<SettingsOutlinedIcon className="dagnode--actions-btn" />}
>
<IconButton onClick={onEditClick} size="small">
<Edit color="success" fontSize="inherit" />
</IconButton>
{Object.entries(onMove).map(([key, action]) => (
<IconButton
key={key}
onClick={action}
size="small"
className={["dagnode--actions--move", key].join(" ")}
>
<ArrowBackIcon fontSize="inherit" />
</IconButton>
))}
{onXClick && (
<IconButton
onClick={() => {
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"
>
<DeleteForeverIcon fontSize="inherit" color="error" />
</IconButton>
)}
</SpeedDial>
{!!onSetEnabled && (
<InputBoolean
key="enabled-flag"
className="dagnode--enabled-flag"
label=""
value={enabled}
onChange={onSetEnabled}
/>
)}
{/* <Info className="dagnode--info-icon" style={{ color: nodeColor }} /> */}
{hasInput && (
<Handle
type="target"
position={flipped ? Position.Top : Position.Left}
/>
)}
<Handle
type="source"
position={flipped ? Position.Bottom : Position.Right}
/>
<div
className="dagnode--label"
style={{
maxHeight: `calc(${height}px - 1em)`,
maxWidth: `calc(${width}px - 1em)`,
minHeight: `1em`,
}}
>
{typeof label === "string" ? <span>{label}</span> : label}
</div>
</div>
{onAddNode && (
<div className="dagnode--midway-options">
<ButtonIcon icon={<Add />} onClick={onAddNode} />
</div>
)}
</div>
</>
);
};
@@ -1,23 +0,0 @@
import { DAGAutomationFlowDims } from "components/DAGFlow/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.75 as const;
export const PADDING = 50 as const;
export const DEFAULT_DIMS = {
nodeHeight: NODE_HEIGHT,
nodeWidth: NODE_WIDTH,
conditionHeight: CONDITION_HEIGHT,
conditionWidth: CONDITION_WIDTH,
distanceFactor: DISTANCE_FACTOR,
circleSize: CIRCLE_SIZE,
padding: {
x: PADDING,
y: PADDING,
},
flipped: true,
} as DAGAutomationFlowDims;
@@ -1,18 +0,0 @@
import { DAGCircleProps, makeFlowCircle } from "./DAGCircle";
import { DAGAutomationFlowDims } from "./types";
import { Node, XYPosition } from "react-flow-renderer";
export const makeAddButton = (
id: string,
position: XYPosition,
{ circleSize, flipped }: DAGAutomationFlowDims,
onAdd: () => void,
disableTarget: boolean = true
): Node<DAGCircleProps> =>
makeFlowCircle(id, position, {
flipped,
size: circleSize,
onAdd,
disableSource: true,
disableTarget,
});
-60
View File
@@ -1,60 +0,0 @@
import { FC } from "react";
import {
DAGAutomationFlowDims,
UpdateModalState,
} from "components/DAGFlow/types";
import { Node, XYPosition } from "react-flow-renderer";
import { AutomationCondition } from "types/automations/conditions";
export const convertToFlowNode =
<D extends {}>(Component: FC<D>): FC<{ data: D }> =>
({ data }) => {
return <Component {...data} />;
};
export const createToNodeMakerFunction =
<NodePreData extends {}, NodeData extends {}>(
convert: (pre: NodePreData, dims: DAGAutomationFlowDims) => NodeData
) =>
(
id: string,
position: XYPosition,
data: NodePreData,
dims: DAGAutomationFlowDims
): Node<NodeData> => ({
id,
type: "dagnode",
position,
data: convert(data, dims),
});
export const makeOnEditAutomationConditions =
(
conditions: AutomationCondition[],
updateConditions: (c: AutomationCondition[]) => void,
openModal: UpdateModalState
) =>
() =>
openModal({
node:
conditions.length > 1
? {
condition: "and",
conditions,
}
: conditions.length === 1
? conditions[0]
: {
condition: "state",
entity_id: "",
state: "",
},
allowedTypes: ["condition"],
update: (c: AutomationCondition) => {
if (c.condition === "and") {
updateConditions(c.conditions);
} else {
updateConditions([c]);
}
},
});
@@ -1,263 +0,0 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { DAGAutomationFlow } from '.';
import { useState } from 'react';
import * as dgconst from "components/DAGFlow/constants";
import { Page } from "components/Page";
export default {
title: 'DAGAutomationFlow/Viewer',
component: DAGAutomationFlow,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
dims: dgconst.DEFAULT_DIMS
}
} as ComponentMeta<typeof DAGAutomationFlow>
const Template: ComponentStory<typeof DAGAutomationFlow> = args => {
const [state, setState] = useState({
trigger: args.trigger,
sequence: args.sequence,
condition: args.condition,
})
return <Page>
<DAGAutomationFlow
{...args}
{...state}
onTriggerUpdate={trigger => {
setState({ ...state, trigger })
}}
onSequenceUpdate={sequence => setState({ ...state, sequence })}
onConditionUpdate={condition => setState({ ...state, condition })}
/>
</Page>
}
export const Simple = Template.bind({})
Simple.args = {
...Simple.args,
condition: [],
trigger: [
{
"platform": "numeric_state",
"entity_id": "test",
},
{
"platform": "homeassistant",
"event": "start",
}
],
sequence: [
{
condition: 'and',
conditions: [
{
condition: 'numeric_state',
entity_id: 'sensor.temperature_kitchen',
below: '15',
},
{
condition: 'template',
value_template: 'states(switch.kitchen_light) == "on"'
}
]
},
{
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,
condition: [],
trigger: [
{
"platform": "numeric_state",
"entity_id": "test",
},
{
"platform": "homeassistant",
"event": "start",
},
{
"bad": "node"
} as any
],
sequence: [
{
"condition": "and",
"conditions": [
{
"condition": "numeric_state",
"entity_id": "sensor.temperature_kitchen",
"below": "15"
},
{
"condition": "template",
"value_template": "states(switch.kitchen_light) == \"on\""
}
]
},
{
"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"
}
},
{
"alias": "Bad Node",
},
{
"choose": [
{
"conditions": [
{
"condition": "state",
"entity_id": "lights.bathroom",
"state": "off",
}
],
"sequence": [
{
"service": "light.turn_on",
"target": {
"entity_id": "lights.bathroom"
},
"data": {}
},
{
"alias": "Turn off bedroom",
"service": "light.turn_off",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
}
]
},
{
"conditions": [
{
"condition": "state",
"entity_id": "lights.bedroom",
"state": "off",
}
],
"sequence": [
{
"alias": "Turn on bedroom",
"service": "light.turn_on",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
},
{
"choose": [
{
"conditions": [],
"sequence": [
{
"choose": [],
"default": [],
}
]
}
],
"default": [
{
"choose": [],
"default": [],
}
],
}
]
}
],
"default": [
{
"service": "light.turn_off",
"target": {
"entity_id": "lights.bathroom"
},
"data": {}
}
]
},
{
"condition": "and",
"conditions": []
}
]
}
export const EmptyStart = Template.bind({})
EmptyStart.args = {
...EmptyStart.args,
condition: [],
trigger: [],
sequence: []
}
export const Errors = Template.bind({})
Errors.args = {
...Errors.args,
condition: [
{
"condition": "numeric_state",
} as any
],
trigger: [
{
"platform": "event",
} as any
],
sequence: [
{
"choose": {}
} as any
]
}
export const ComplexFlipped = Complex.bind({})
ComplexFlipped.args = {
...Complex.args,
dims: {
...dgconst.DEFAULT_DIMS,
...Complex.args.dims,
flipped: true,
}
}
export const SimpleFlipped = Simple.bind({})
SimpleFlipped.args = {
...Simple.args,
dims: {
...dgconst.DEFAULT_DIMS,
...Complex.args.dims,
flipped: true,
}
}
-138
View File
@@ -1,138 +0,0 @@
import { FC, useState } from "react";
import ReactFlow, { Controls } from "react-flow-renderer";
import { triggerToFlow } from "./triggerConvertor";
import { DAGNode, makeConditionPoint } from "./DAGNode";
import { DAGAutomationFlowDims, FlowData, ModalState } from "./types";
import { DAGCircle } from "./DAGCircle";
import { sequenceToFlow } from "./sequenceConvertor";
import { NodeEditor } from "components/NodeEditor";
import { Modal } from "components/Modal";
import { convertToFlowNode } from "./helpers";
import { DAGErrorNode } from "./DAGErrorNode";
import { useHA } from "haService";
import { getDescriptionFromAutomationNode } from "utils/formatting";
import { DagFlowUpdateBaseArgs, makeDagFlowUpdate } from "./DAGFlowUpdater";
const nodeTypes = {
dagnode: convertToFlowNode(DAGNode),
errornode: convertToFlowNode(DAGErrorNode),
dagcircle: DAGCircle,
};
export type DAGAutomationFlowProps = DagFlowUpdateBaseArgs & {
className?: string;
dims: DAGAutomationFlowDims;
};
export const DAGAutomationFlow: FC<DAGAutomationFlowProps> = (props) => {
// state
const [modalState, setModalState] = useState<ModalState | null>(null);
const { namer } = useHA();
const dagUpdater = makeDagFlowUpdate({
...props,
openModal: setModalState,
});
// alias
const { className, dims, sequence, condition, trigger } = props;
// modal
let modalBody = <></>;
if (modalState) {
modalBody = (
<NodeEditor
node={modalState.node}
onClose={() => setModalState(null)}
onSave={(n) => {
modalState.update(n as any);
setModalState(null);
}}
allowedTypes={modalState.allowedTypes}
saveBtnCreateText={modalState.saveBtnCreateText}
/>
);
}
// convert automation to flow data
const condPoint = makeConditionPoint(
"c",
dims.flipped
? {
y: dims.padding.y + dims.nodeHeight * dims.distanceFactor,
x: dims.padding.x + (dims.nodeWidth - dims.conditionWidth) / 2,
}
: {
x: dims.padding.x + dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y + (dims.nodeHeight - dims.conditionHeight) / 2,
},
{
label: getDescriptionFromAutomationNode(
{
condition: "and",
conditions: condition,
},
namer,
true
),
onEditClick: dagUpdater.onEditAutomationConditions,
onAddNode: () => dagUpdater.addNode(0, "sequence"),
},
dims
);
const flowData: FlowData = {
nodes: [condPoint],
edges: [],
};
triggerToFlow(
flowData,
trigger,
condPoint.id,
dims,
dagUpdater.makeTriggerMakerOptions(namer)
);
sequenceToFlow(
flowData,
sequence,
condPoint.id,
{
...dims,
padding: dims.flipped
? {
y: condPoint.position.y - dims.nodeHeight,
x: dims.padding.x,
}
: {
x: condPoint.position.x - dims.nodeWidth,
y: dims.padding.y,
},
},
namer,
dagUpdater.sequenceUpdater
);
// this fixes some strange edge drawing issue
flowData.edges = flowData.edges.map((e) => ({
...e,
source: `${e.source}-${dims.flipped}`,
target: `${e.target}-${dims.flipped}`,
}));
flowData.nodes = flowData.nodes.map((n) => ({
...n,
id: `${n.id}-${dims.flipped}`,
}));
// render
return (
<>
<Modal open={!!modalState}>{modalBody}</Modal>
<ReactFlow
className={className}
nodeTypes={nodeTypes}
snapToGrid
onlyRenderVisibleElements
nodesConnectable={false}
nodesDraggable={false}
{...flowData}
>
<Controls />
</ReactFlow>
</>
);
};
-4
View File
@@ -1,4 +0,0 @@
.dag-flow-safe {
height: 100%;
overflow: scroll;
}
-84
View File
@@ -1,84 +0,0 @@
import "./safe.css";
import { Component, ErrorInfo } from "react";
import { DAGAutomationFlow, DAGAutomationFlowProps } from ".";
import { AutomationSequenceNode } from "types/automations";
import { AutomationCondition } from "types/automations/conditions";
import { AutomationTrigger } from 'types/automations/triggers';
import InputYaml from "components/Inputs/InputYaml";
import { Button } from "components/Inputs/Button";
type GoodState = {
hasError: false;
}
type FailedStateData = {
sequence: AutomationSequenceNode[],
condition: AutomationCondition[],
trigger: AutomationTrigger[],
}
type FailedState = {
hasError: true,
error: any,
errorInfo?: ErrorInfo,
} & FailedStateData
type State = GoodState | FailedState
export class SafeDAGAutomationFlow extends Component<DAGAutomationFlowProps, State> {
state: State = {
hasError: false
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
this.setState({
hasError: true,
error,
errorInfo,
sequence: this.props.sequence,
condition: this.props.condition,
trigger: this.props.trigger,
})
}
render() {
if (this.state.hasError) {
const makeSet = <K extends keyof FailedStateData>(k: K) => (d: FailedStateData[K]) => this.setState({
...this.state,
[k]: d,
});
const makeSave = <K extends keyof FailedStateData>(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 <div className="dag-flow-safe">
<h1>An Error has occured.</h1>
<h1>Failed to Open Autmation!</h1>
Something is likely not configured in your automation properly.
<hr />
<h2>Error:</h2>
<h2>{String(this.state.error)}</h2>
<br />
{JSON.stringify(this.state.error, null, 4)}
{this.state.errorInfo && this.state.errorInfo.componentStack.split('\n').map((s, i) => <>
<span key={i}>{s}</span><br key={`br-${i}`} />
</>)}
<h2>Automation YAML</h2>
<InputYaml label="Trigger" value={this.state.trigger} onChange={makeSet('trigger')} />
<Button onClick={makeSave('trigger')}>Save Triggers</Button>
<InputYaml label="Condition" value={this.state.condition} onChange={makeSet('condition')} />
<Button onClick={makeSave('condition')}>Save Conditions</Button>
<InputYaml label="Action" value={this.state.sequence} onChange={makeSet('sequence')} />
<Button onClick={makeSave('sequence')}>Save Actions</Button>
</div>
}
return <DAGAutomationFlow {...this.props} />;
}
}
@@ -1,405 +0,0 @@
import { AutomationSequenceNode } from "types/automations";
import { DAGAutomationFlowDims, FlowData } from "./types";
import { getDescriptionFromAutomationNode, Namer } from "utils/formatting";
import { XYPosition } from "react-flow-renderer";
import { ChooseAction } from "types/automations/actions";
import { makeFlowCircle } from "./DAGCircle";
import { createOnRemoveForChooseNode, SequenceUpdater } from "./updater";
import { getNodeType } from "utils/automations";
import { makeAddButton } from "./flowDataMods";
import {
makeActionPoint,
makeConditionPoint,
DAGNodeOnMoveEvents,
} from "./DAGNode";
export const sequenceToFlow = (
flowData: FlowData,
sequence: AutomationSequenceNode[],
fromPoint: string,
dims: DAGAutomationFlowDims,
namer: Namer,
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}`;
let position: XYPosition;
if (lasPos) {
position = dims.flipped
? {
y: lasPos.y + dims.nodeHeight * dims.distanceFactor,
x: dims.padding.x,
}
: {
x: lasPos.x + dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y,
};
} else {
position = dims.flipped
? {
y: dims.padding.y + dims.nodeHeight * dims.distanceFactor * (i + 2),
x: dims.padding.x,
}
: {
x: dims.padding.x + dims.nodeWidth * dims.distanceFactor * (i + 2),
y: dims.padding.y,
};
}
// draw node
if (getNodeType(node) === "action") {
if ("choose" in node) {
try {
const out = addChooseNode(
node,
position,
nodeId,
dims,
namer,
updater,
i
);
position = out.lastPos;
flowData = mergeFlowDatas(flowData, out.flowData);
} catch (err) {
console.error(err);
addErrorNode(
flowData,
nodeId,
position,
dims,
err,
updater.makeOnEditForBadNode(i)
);
}
} else {
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
onMove: updater.makeOnMoveEvents(i, dims.flipped),
namer,
onAddNode: () => updater.addNode(i + 1),
onSetEnabled: () =>
updater.updateNode(i, {
...node,
enabled: !(node.enabled ?? true),
}),
});
}
} else {
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
onMove: updater.makeOnMoveEvents(i, dims.flipped),
namer,
onAddNode: () => updater.addNode(i + 1),
onSetEnabled: () =>
updater.updateNode(i, {
...node,
enabled: !(node.enabled ?? true),
}),
});
}
addEdge(flowData, lastPointId, nodeId, false);
lastPointId = nodeId;
lasPos = position;
}
return {
position: lasPos,
pointId: lastPointId,
};
};
const xyApply = (
p1: XYPosition,
p2: XYPosition,
fcn: (a: number, b: number) => number
): XYPosition => ({
x: fcn(p1.x, p2.x),
y: fcn(p1.y, p2.y),
});
const addEdge = (
flowData: FlowData,
source: string,
target: string,
animated: boolean = false
) =>
flowData.edges.push({
id: `${source}-${target}`,
source,
target,
animated,
});
const addSingleNode = (
flowData: FlowData,
node: AutomationSequenceNode,
position: XYPosition,
nodeId: string,
dims: DAGAutomationFlowDims,
opts: {
onEditClick: () => void;
onXClick: () => void;
onAddNode: () => void;
namer: Namer;
onMove: DAGNodeOnMoveEvents;
onSetEnabled: () => void;
}
) =>
flowData.nodes.push(
makeActionPoint(
nodeId,
position,
{
label: getDescriptionFromAutomationNode(node, opts.namer, true),
color: getNodeType(node) === "action" ? "green" : "blue",
hasInput: true,
enabled: node.enabled ?? true,
...opts,
},
dims
)
);
const addErrorNode = (
flowData: FlowData,
nodeId: string,
position: XYPosition,
{ nodeHeight, nodeWidth }: DAGAutomationFlowDims,
error: any,
onEdit: () => void,
hasInput: boolean = true
) =>
flowData.nodes.push({
id: nodeId,
type: "errornode",
position,
data: {
height: nodeHeight,
width: nodeWidth,
hasInput,
onEdit,
error,
},
});
const addChooseNode = (
node: ChooseAction,
position: XYPosition,
nodeId: string,
dims: DAGAutomationFlowDims,
namer: Namer,
updater: SequenceUpdater,
i: number
) => {
const flowData: FlowData = {
nodes: [],
edges: [],
};
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
namer,
onMove: updater.makeOnMoveEvents(i, dims.flipped),
onAddNode: () => updater.addNode(i + 1),
onSetEnabled: () =>
updater.updateNode(i, {
...node,
enabled: !(node.enabled ?? true),
}),
});
let lastPos: XYPosition = position;
if (!(node.enabled ?? true)) {
return { lastPos, flowData };
}
// conditions
node.choose.forEach(({ sequence, conditions }, j) => {
const sequenceId = `${nodeId}.${j}`;
const childUpdater = updater.makeChildUpdaterForChooseAction(i, j);
// edit/delete circle
const circle = makeFlowCircle(
`${sequenceId}>delete`,
dims.flipped
? {
y: position.y + dims.nodeHeight * dims.distanceFactor,
x:
lastPos.x +
Math.max(dims.nodeWidth, dims.conditionWidth) *
dims.distanceFactor,
}
: {
x: position.x + dims.nodeWidth * dims.distanceFactor,
y:
lastPos.y +
Math.max(dims.nodeHeight, dims.conditionHeight) *
dims.distanceFactor,
},
{
flipped: dims.flipped,
size: dims.circleSize,
onRemove: createOnRemoveForChooseNode(
node,
(d) => updater.updateNode(i, d),
j
),
}
);
flowData.nodes.push(circle);
addEdge(flowData, nodeId, circle.id, true);
const condNode = makeConditionPoint(
`${sequenceId}>cond`,
dims.flipped
? {
y: circle.position.y + dims.circleSize * dims.distanceFactor,
x: circle.position.x - (dims.conditionWidth - dims.circleSize) / 2,
}
: {
x: circle.position.x + dims.circleSize * dims.distanceFactor,
y: circle.position.y - (dims.conditionHeight - dims.circleSize) / 2,
},
{
label: getDescriptionFromAutomationNode(
{
condition: "and",
conditions,
},
namer,
true
),
onEditClick: updater.makeOnEditConditionsForChooseNode(i, j),
onAddNode: () => childUpdater.addNode(0),
},
dims
);
flowData.nodes.push(condNode);
addEdge(flowData, circle.id, condNode.id, true);
// actual sub sequence
const lastPoint = sequenceToFlow(
flowData,
sequence,
condNode.id,
{
...dims,
padding: dims.flipped
? {
y: condNode.position.y - dims.nodeHeight,
x:
condNode.position.x -
(dims.nodeWidth - dims.conditionWidth) / 2,
}
: {
x: condNode.position.x - dims.nodeWidth,
y:
condNode.position.y -
(dims.nodeHeight - dims.conditionHeight) / 2,
},
},
namer,
childUpdater,
`${sequenceId}.`
);
if (lastPoint.position) {
lastPos = xyApply(lastPos, lastPoint.position, Math.max);
} else {
lastPos = xyApply(
lastPos,
dims.flipped
? {
y: lastPos.y,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor,
}
: {
x: lastPos.x,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor,
},
Math.max
);
}
});
const totalChildren = node.choose.length;
// add button
const addCirlce = makeAddButton(
`${nodeId}>add`,
dims.flipped
? {
y: position.y + dims.nodeHeight * dims.distanceFactor,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor,
}
: {
x: position.x + dims.nodeWidth * dims.distanceFactor,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor,
},
dims,
() =>
updater.updateNode(i, {
...node,
choose: [
...node.choose,
{
sequence: [],
conditions: [],
},
],
}),
false
);
flowData.nodes.push(addCirlce);
addEdge(flowData, nodeId, addCirlce.id, true);
// else
const elseCircle = makeFlowCircle(
`${nodeId}>else`,
dims.flipped
? {
y: position.y + dims.nodeHeight * dims.distanceFactor,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor * 2,
}
: {
x: position.x + dims.nodeWidth * dims.distanceFactor,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor * 2,
},
{ size: dims.circleSize, flipped: dims.flipped }
);
flowData.nodes.push(elseCircle);
addEdge(flowData, nodeId, elseCircle.id, true);
const lastPoint = sequenceToFlow(
flowData,
node.default ?? [],
elseCircle.id,
{
...dims,
padding: dims.flipped
? {
y: position.y,
x: elseCircle.position.x - 1.4 * dims.circleSize,
}
: {
x: position.x - dims.nodeWidth,
y: elseCircle.position.y - dims.circleSize / 4,
},
},
namer,
updater.makeChildUpdaterForChooseAction(i, null),
`${nodeId}.${totalChildren}.`
);
if (lastPoint.position) {
lastPos = xyApply(lastPos, lastPoint.position, Math.max);
} else {
lastPos = xyApply(lastPos, elseCircle.position, Math.max);
}
return { lastPos, flowData };
};
export const mergeFlowDatas = (fd1: FlowData, fd2: FlowData): FlowData => {
fd1.edges = fd1.edges.concat(fd2.edges);
fd1.nodes = fd1.nodes.concat(fd2.nodes);
return fd1;
};
-151
View File
@@ -1,151 +0,0 @@
import { Styles } from "jss";
import { createAppUseStyles } from "styles/theme";
import { NodeColor } from "types/graphs";
export const useNodeStyles = createAppUseStyles<{
color: NodeColor;
nodeHeight: number;
nodeWidth: number;
accentBackground: boolean;
}>((theme) => {
const edgeStyle: Styles = {
flex: "1",
display: "flex",
flexDirection: "column",
flexWrap: "nowrap",
borderRadius: "1em",
justifyContent: "space-around",
alignItems: "center",
"&:hover": {
backgroundColor: theme.primaryAccent,
cursor: "pointer",
},
};
const buttonStyle: Styles = {
fontSize: "8px",
backgroundColor: "rgba(0,0,0,0)",
color: theme.primaryAccent,
borderStyle: "none",
height: "15px",
width: "15px",
cursor: "pointer",
};
return {
speeddial: {
height: "2em",
width: "2em",
},
root: ({ nodeHeight, nodeWidth }) => ({
display: "flex",
flexDirection: "column",
justifyContent: "flex-end",
height: nodeHeight,
maxHeight: nodeHeight,
maxWidth: nodeWidth,
width: nodeWidth,
fontSize: 10,
}),
inner: ({ color, accentBackground }) => ({
position: "relative",
display: "flex",
flexDirection: "row",
backgroundColor: !accentBackground
? theme.secondary
: color === "lblue"
? theme.condition.primaryColorOpaque
: "none",
borderRadius: "1em",
flex: 1,
height: `100%`,
maxHeight: `100%`,
maxWidth: "100%",
marginTop: "2.5px",
marginBottom: "2.5px",
borderTopWidth: "1px",
borderTopStyle: "solid",
borderTopLeftRadius: "10px",
borderTopRightRadius: "10px",
borderTopColor:
color === "red"
? theme.redAccent
: color === "blue"
? theme.condition.primaryColor
: color === "green"
? theme.green
: color === "lblue"
? theme.condition.primaryAccent
: "none",
}),
textWrap: {
display: "flex",
flex: 4,
textAlign: "center",
justifyContent: "center",
alignItems: "center",
height: "100%",
maxHeight: "100%",
maxWidth: "50%",
},
text: {
textOverflow: "ellipsis",
overflow: "hidden",
whiteSpace: "break-spaces",
lineBreak: "anywhere",
cursor: "default",
},
buttonDelete: {
...buttonStyle,
"&:hover": {
color: theme.primary,
},
},
buttonEdit: {
...buttonStyle,
"&:hover": {
transform: "rotate(45deg)",
},
},
leftEdge: {
...edgeStyle,
borderLef: `1px ${theme.secondaryAccent} solid`,
borderTopRightRadius: 0,
borderBottomRightRadius: 0,
},
rightEdge: {
...edgeStyle,
borderRight: `1px ${theme.secondaryAccent} solid`,
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0,
},
};
});
export const useCircleStyles = createAppUseStyles<{
size: number;
hasOnFunction: boolean;
hasRemoveFunction: boolean;
backgroundColor?: string;
}>((theme) => ({
root: ({ size, hasOnFunction, hasRemoveFunction, backgroundColor }) => {
const baseColor = backgroundColor ? backgroundColor : theme.green;
const hoverColor = hasOnFunction ? theme.greenOpaque : baseColor;
return {
backgroundColor: baseColor,
borderRadius: hasRemoveFunction ? 10 : 500,
height: size,
width: size,
color: theme.primary,
cursor: hasOnFunction ? "pointer" : "default",
"&:hover": {
backgroundColor: hoverColor,
},
fontSize: `${size * 0.4}px`,
display: "flex",
justifyContent: "center",
alignItems: "center",
};
},
trashIcon: {
padding: 1,
},
}));
@@ -1,76 +0,0 @@
import { AutomationTrigger } from "types/automations/triggers";
import { DAGAutomationFlowDims, FlowData, TriggerMakerOptions } from "./types";
import { makeAddButton } from "./flowDataMods";
import { getDescriptionFromAutomationNode } from "utils/formatting";
import { makeActionPoint } from "./DAGNode";
export const triggerToFlow = (
flowData: FlowData,
trigger: AutomationTrigger[],
toPoint: string,
dims: DAGAutomationFlowDims,
opts: TriggerMakerOptions
) => {
const {
distanceFactor,
nodeHeight,
nodeWidth,
padding,
conditionHeight,
circleSize,
flipped,
} = dims;
// convert all triggers to dag nodes
trigger.forEach((t, i) => {
const flowId = `t-${i}`;
flowData.nodes.push(
makeActionPoint(
flowId,
flipped
? {
y: padding.y,
x: padding.x + nodeWidth * distanceFactor * i,
}
: {
x: padding.x,
y: padding.y + nodeHeight * distanceFactor * i,
},
{
label: getDescriptionFromAutomationNode(t, opts.namer, true),
color: "red",
onEditClick: () => opts.onEdit(i),
onXClick: () => opts.onDelete(i),
enabled: t.enabled ?? true,
onSetEnabled: () => opts.onSetEnabled(i),
},
dims
)
);
flowData.edges.push({
id: `e(${flowId})-(${toPoint})`,
source: flowId,
target: toPoint,
});
});
// create a 'add button'
flowData.nodes.push(
makeAddButton(
"trigger-add",
flipped
? {
y: padding.y + circleSize / 4,
x: padding.x + nodeWidth * distanceFactor * trigger.length,
}
: {
x: padding.x + nodeWidth * 0.4,
y:
padding.y +
conditionHeight / 2 +
nodeHeight * distanceFactor * trigger.length,
},
dims,
opts.onAdd
)
);
};
-48
View File
@@ -1,48 +0,0 @@
import { Edge, Node, XYPosition } from "react-flow-renderer";
import { AutomationNodeTypes, AutomationSequenceNode } from "types/automations";
import { DAGCircleProps } from "./DAGCircle";
import { DAGNodeProps } from "./DAGNode";
import { AutomationTrigger } from "types/automations/triggers";
import { DAGErrorNodeProps } from "./DAGErrorNode";
import { Namer } from "utils/formatting";
export type DAGAutomationFlowDims = {
padding: XYPosition;
nodeHeight: number;
nodeWidth: number;
conditionWidth: number;
conditionHeight: number;
circleSize: number;
distanceFactor: number;
flipped: boolean;
};
export type DAGAutomationFlowNode = Node<
DAGNodeProps | DAGCircleProps | DAGErrorNodeProps | any
>;
export type FlowData = {
nodes: DAGAutomationFlowNode[];
edges: Edge[];
};
export type TriggerMakerOptions = {
onAdd: () => void;
onEdit: (i: number) => void;
onDelete: (i: number) => void;
namer: Namer;
onSetEnabled: (i: number) => void;
};
export type UpdateModalState<
T extends AutomationSequenceNode | AutomationTrigger = any
> = (s: ModalState<T>) => void;
export type ModalState<
T extends AutomationSequenceNode | AutomationTrigger = any
> = {
isError?: boolean;
node: T;
update: (n: T) => void;
saveBtnCreateText?: boolean;
allowedTypes: AutomationNodeTypes[];
};
@@ -1,45 +0,0 @@
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;
},
(ms) => modalStates.push(ms)
);
return {
get state() {
return state;
},
modalStates,
updater,
};
};
test("sequence updater updates nodes", () => {
const mock = mockSequenceUpdater([
{
choose: [
{
conditions: [],
sequence: [],
},
],
default: [],
},
]);
expect(mock.state.length).toBe(1);
expect((mock.state[0] as ChooseAction).alias).toBe(undefined);
mock.updater.updateNode(0, {
...mock.state[0],
alias: "Hello",
} as any);
expect((mock.state[0] as any).alias).toBe("Hello");
});
-171
View File
@@ -1,171 +0,0 @@
import { AutomationSequenceNode } from "types/automations";
import { ChooseAction } from "types/automations/actions";
import { AutomationCondition } from "types/automations/conditions";
import { UpdateModalState } from "./types";
import { getNodeType } from "../../utils/automations";
import { DAGNodeOnMoveEvents } from "./DAGNode";
import { cleanUpUndefined } from "components/NodeEditor/OptionManager/OptionManager";
import { makeOnEditAutomationConditions } from "./helpers";
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(afterIndex: number | null = null) {
return openModal({
saveBtnCreateText: true,
node: {
device_id: "",
},
update: (n) => {
if (afterIndex !== null) {
onChange([
...sequence.slice(0, afterIndex),
n,
...sequence.slice(afterIndex),
]);
} else {
onChange([...sequence, n]);
}
},
allowedTypes: ["action", "condition"],
});
},
updateNode(i: number, node: AutomationSequenceNode) {
if (JSON.stringify(node) !== JSON.stringify(sequence[i])) {
return onChange([
...sequence.slice(0, i),
node,
...sequence.slice(i + 1),
]);
}
},
updateChooseActionData(i: number, data: ChooseAction) {
const node = sequence[i] as ChooseAction;
return this.updateNode(i, {
...node,
...data,
});
},
makeChildUpdaterForChooseAction(i: number, j: number | null) {
const node = sequence[i];
if ("choose" in node) {
if (j !== null) {
return makeSequenceUpdater(
node.choose[j].sequence,
(seq) =>
this.updateNode(i, {
...node,
choose: [
...node.choose.slice(0, j),
{
...node.choose[j],
sequence: seq,
},
...node.choose.slice(j + 1),
],
}),
openModal
);
} else {
return makeSequenceUpdater(
node.default ?? [],
(seq) =>
this.updateNode(i, {
...node,
default: seq,
}),
openModal
);
}
}
throw new Error(`Cannot create sub-updater for ${node}`);
},
makeOnModalOpenForNode(i: number, node: AutomationSequenceNode) {
return () =>
openModal({
node,
allowedTypes: ["action", "condition"],
update: (n) => this.updateNode(i, n),
});
},
makeOnEditConditionsForChooseNode(i: number, j: number) {
const node = sequence[i] as ChooseAction;
return makeOnEditAutomationConditions(
node.choose[j].conditions,
(conditions) =>
this.updateNode(i, {
...node,
choose: [
...node.choose.slice(0, j),
{
sequence: node.choose[j].sequence,
conditions: conditions as AutomationCondition[],
},
...node.choose.slice(j + 1),
],
}),
openModal
);
},
makeOnEditForBadNode(i: number) {
const node = sequence[i];
return () =>
openModal({
isError: true,
node,
allowedTypes: [getNodeType(node)],
update: (n) => this.updateNode(i, n),
});
},
makeOnMoveEvents(i: number, flipped: boolean): DAGNodeOnMoveEvents {
const moveBack =
i > 0
? () =>
onChange([
...sequence.slice(0, i - 1),
sequence[i],
sequence[i - 1],
...sequence.slice(i + 1),
])
: undefined;
const moveForward =
i < sequence.length - 1
? () =>
onChange([
...sequence.slice(0, i),
sequence[i + 1],
sequence[i],
...sequence.slice(i + 2),
])
: undefined;
if (flipped) {
return cleanUpUndefined({
up: moveBack,
down: moveForward,
});
} else {
return cleanUpUndefined({
right: moveForward,
left: moveBack,
});
}
},
});
export const createOnRemoveForChooseNode =
(action: ChooseAction, update: (data: ChooseAction) => void, j: number) =>
() =>
update({
...action,
choose: [...action.choose.slice(0, j), ...action.choose.slice(j + 1)],
});
+70
View File
@@ -0,0 +1,70 @@
import { FC, useState } from "react";
import {
AutomationActionData,
AutomationSequenceNode,
} from "types/automations";
import { useHA } from "haService";
import { ModalState } from "./board/types";
import { createUpdater } from "./updater";
import { useAutomationNodes } from "./elements";
import { DEFAULT_DIMS } from "./elements/constants";
import { DAGGraphBoard } from "./board";
import { AutomationTrigger } from "types/automations/triggers";
import { AutomationCondition } from "types/automations/conditions";
export const DAGAutomationGraph: FC<{
sequence: AutomationSequenceNode[];
trigger: AutomationTrigger[];
condition: AutomationCondition[];
onSequenceUpdate: (s: AutomationSequenceNode[]) => void;
onTriggerUpdate: (t: AutomationTrigger[]) => void;
onConditionUpdate: (c: AutomationCondition[]) => void;
isFlipped: boolean;
}> = (props) => {
const { namer } = useHA();
const [modalState, setModalState] =
useState<ModalState | undefined>(undefined);
const updater = createUpdater({
openModal: setModalState,
sequence: {
data: props.sequence,
onUpdate: props.onSequenceUpdate,
},
condition: {
data: props.condition,
onUpdate: props.onConditionUpdate as any,
},
trigger: {
data: props.trigger,
onUpdate: props.onTriggerUpdate as any,
},
});
const elementData = useAutomationNodes(
{
sequence: props.sequence,
condition: props.condition,
trigger: props.trigger,
},
{
dims: {
...DEFAULT_DIMS,
flipped: props.isFlipped,
},
namer,
openModal: setModalState,
stateUpdater: updater,
}
);
return (
<DAGGraphBoard
modalState={modalState}
closeModal={() => setModalState(undefined)}
state={{
ready: true,
data: {
elements: elementData,
},
}}
/>
);
};
@@ -1,6 +1,5 @@
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";
@@ -12,9 +11,8 @@ export default {
component: SequenceNode,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
...DEFAULT_DIMS.node,
color: "lblue",
height: dgconst.NODE_HEIGHT,
width: dgconst.NODE_WIDTH,
label: "test",
hasInput: true,
enabled: true,
@@ -67,8 +65,16 @@ export const Colors: ComponentStory<typeof SequenceNode> = (args) => {
{
id: color,
position: {
x: 50 + dgconst.NODE_HEIGHT * dgconst.DISTANCE_FACTOR * i,
y: 50 + dgconst.NODE_HEIGHT * dgconst.DISTANCE_FACTOR * i,
x:
50 +
DEFAULT_DIMS.node.height *
DEFAULT_DIMS.distanceFactor.node *
i,
y:
50 +
DEFAULT_DIMS.node.height *
DEFAULT_DIMS.distanceFactor.node *
i,
},
},
DEFAULT_DIMS,
+10 -18
View File
@@ -1,21 +1,13 @@
import { ApiService } from 'apiService/core';
import { ApiService } from "apiService/core";
import { ConnectedAutomationList } from "components/AutomationList";
import { DEFAULT_DIMS } from "components/DAGFlow/constants";
import { Page } from 'components/Page';
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { Page } from "components/Page";
import { FC } from "react";
export const AutomationRoute: FC<{ api: ApiService }> = ({
api
}) => {
return <Page>
<ConnectedAutomationList
dims={DEFAULT_DIMS}
api={api}
/>
</Page>
}
export const AutomationRoute: FC<{ api: ApiService }> = ({ api }) => {
return (
<Page>
<ConnectedAutomationList dims={DEFAULT_DIMS} api={api} />
</Page>
);
};