refactor of dagflow start

This commit is contained in:
ari committed 2022-07-09 19:22:04 -04:00
1 parent 3cb6070aca
commit d62c484f33
29 files changed
+1463 -16

No files matched your search

@@ -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;
@@ -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;
}
};
@@ -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<AutomationActionData>(props.automation);
const [modalState, setModalState] =
useState<ModalState | undefined>(undefined);
const updater = createUpdaterFromAutomationData(
setModalState,
state,
setState
);
const elementData = makeAutomationNodes(state, {
dims: {
...DEFAULT_DIMS,
flipped: props.flipped,
},
namer,
openModal: setModalState,
stateUpdater: updater,
});
return (
<DAGGraphBoard
modalState={modalState}
closeModal={() => 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<typeof Demo>;
const Template: ComponentStory<typeof Demo> = (args) => (
<Page>
<Demo {...args} />
</Page>
);
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: [],
},
};
@@ -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,
});
});
@@ -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<AutomationTrigger> = (
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<AutomationCondition> = (
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,
};
};
@@ -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 },
]);
});
@@ -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 },
]
);
};
@@ -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<A extends AutomationNode = AutomationNode> = (
haNodes: A[],
args: ElementMakerProps
) => ElementMakerOutput;