updated automation metadata

This commit is contained in:
Ari Sosnovsky committed 2021-11-12 14:39:55 -05:00
1 parent 54c1edba0c
commit ccca0edb65
20 files changed
+238 -723

No files matched your search

@@ -1,264 +0,0 @@
import { GRAPH_HEIGHT, GRAPH_WIDTH, NODE_HEIGHT, NODE_WIDTH } from "./constants";
import { DAG } from "./types";
import {clip, computeDAG} from "./dagFuncs";
test('it clips overflowing values', () => {
expect(clip([GRAPH_WIDTH, GRAPH_HEIGHT])).toEqual([
GRAPH_WIDTH-NODE_WIDTH,
GRAPH_HEIGHT-NODE_HEIGHT
])
expect(clip([-10, -10])).toEqual([
0, 0
])
expect(clip([0, 0])).toEqual([
0, 0
])
})
test('simple empty input dag', () => {
expect(computeDAG({
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [],
condition: [],
action: [
],
})).toEqual({
nodes: {},
edges: [
],
})
})
test('simple single node type input dag', () => {
expect(computeDAG({
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [
{
platform: 'time',
at: '10:00:00'
}
],
condition: [
{
$smType: 'condition',
condition: 'template',
condition_data: {
value_template: 'states(switch.kitchen_light) == "on"'
}
}
],
action: [
{
$smType: 'action',
action: "service",
action_data: {
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
}
],
})).toEqual({
nodes: {
"trigger.0": {
text: '',
// text: "At 10:00:00",
loc: [0,5],
color: 'green',
},
"condition.0": {
loc: [NODE_WIDTH*1.5, 5],
text: '',
color: 'blue',
// text: 'states(switch.kitchen_light) == "on"'
},
"action.0": {
loc: [NODE_WIDTH*3, 5],
text: '',
color: 'red',
// text: 'Start Music In Kitchen',
}
},
edges: [
{ from: 'trigger.0', to: 'condition.0', direction: '1->2' },
{ from: 'condition.0', to: 'action.0', direction: '1->2' },
],
} as DAG)
})
test('simple dag with no triggers', () => {
expect(computeDAG({
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [
],
condition: [
{
$smType: "condition",
condition: 'template',
condition_data: {
value_template: 'states(switch.kitchen_light) == "on"'
}
}
],
action: [
{
$smType: "action",
action: "service",
action_data: {
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
}
],
})).toEqual({
nodes: {
"condition.0": {
loc: [NODE_WIDTH*1.5, 5],
text: '',
color: 'blue',
// text: 'states(switch.kitchen_light) == "on"'
},
"action.0": {
loc: [NODE_WIDTH*3, 5],
text: '',
color: 'red',
// text: 'Start Music In Kitchen',
}
},
edges: [
{ from: 'condition.0', to: 'action.0', direction: '1->2' },
],
} as DAG)
})
test('simple dag with no conditions', () => {
expect(computeDAG({
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [
{
platform: 'time',
at: '10:00:00'
}
],
condition: [],
action: [
{
$smType: 'action',
action: 'service',
action_data: {
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
}
],
})).toEqual({
nodes: {
"trigger.0": {
text: '',
// text: "At 10:00:00",
loc: [0,5],
color: 'green',
},
"action.0": {
loc: [NODE_WIDTH*3, 5],
text: '',
color: 'red',
// text: 'Start Music In Kitchen',
}
},
edges: [
{ from: 'trigger.0', to: 'action.0', direction: '1->2' },
],
} as DAG)
})
test('simple dag with no actions', () => {
expect(computeDAG({
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [
{
platform: 'time',
at: '10:00:00'
}
],
condition: [
{
$smType: "condition",
condition: 'template',
condition_data: {
value_template: 'states(switch.kitchen_light) == "on"'
}
}
],
action: [
],
})).toEqual({
nodes: {
"trigger.0": {
text: '',
// text: "At 10:00:00",
loc: [0,5],
color: 'green',
},
"condition.0": {
loc: [NODE_WIDTH*1.5, 5],
text: '',
color: 'blue',
// text: 'states(switch.kitchen_light) == "on"'
},
},
edges: [
{ from: 'trigger.0', to: 'condition.0', direction: '1->2' }
],
} as DAG)
})
@@ -1,89 +0,0 @@
import { AutomationData } from "../../automations/types";
import { GRAPH_HEIGHT, GRAPH_WIDTH, NODE_HEIGHT, NODE_WIDTH } from "./constants";
import {DAG, Node, Point, NormalizedDag} from "./types";
export const clip = (p: Point) : Point => {
const [x,y] = p.map(c => Math.max(0, c));
return [Math.min(GRAPH_WIDTH-NODE_WIDTH, x), Math.min(GRAPH_HEIGHT-NODE_HEIGHT, y)]
}
export const normalizeDAG = (dag: DAG): NormalizedDag => {
// let overflow: bo
const nodes = Object.keys(dag.nodes).map<[string, Node]>(nodeId => [nodeId, {
...dag.nodes[nodeId],
loc: clip(dag.nodes[nodeId].loc),
}]).reduce((all, [nodeId, next]) => ({
[nodeId]: next,
...all,
}),{});
return {
nodes,
edges: dag.edges,
}
}
export const computeDAG = (automation: AutomationData) : DAG => {
const nodes: DAG['nodes'] = {};
const edges: DAG['edges'] = [];
const triggerIds: string[] = [];
automation.trigger.forEach((t,i) => {
nodes[`trigger.${i}`] = {
loc: [0, 5+NODE_HEIGHT*i*1.5],
text: "",
color: 'green',
}
triggerIds.push(`trigger.${i}`);
})
let lastConditionId: string | undefined = undefined;
automation.condition.forEach((c,i) => {
const cid = `condition.${i}`;
nodes[cid] = {
loc: [NODE_WIDTH*1.5, 5+NODE_HEIGHT*i*1.5],
text: "",
color: 'blue',
}
lastConditionId = cid;
if (i === 0) {
triggerIds.forEach(tid => edges.push({
from: tid, to: cid, direction: '1->2',
}));
} else {
edges.push({
from: lastConditionId, to: cid, direction: '1->2',
})
}
});
if (!lastConditionId) {
if(triggerIds.length > 0) {
lastConditionId = triggerIds[triggerIds.length-1]
}
}
const actionIds: string[] = [];
automation.action.forEach((c,i) => {
const aid = `action.${i}`;
nodes[aid] = {
loc: [NODE_WIDTH*3, 5+NODE_HEIGHT*i*1.5],
text: "",
color: 'red',
}
actionIds.push(aid);
if (i === 0) {
if (lastConditionId) {
edges.push({
from: lastConditionId, to: aid, direction: '1->2',
});
}
} else {
edges.push({
from: `action.${i-1}`, to: aid, direction: '1->2',
})
}
})
return {
nodes, edges
}
}
@@ -1,53 +0,0 @@
import { useEffect, useRef, useState } from "react"
import { GRAPH_HEIGHT, GRAPH_WIDTH, NODE_WIDTH } from "./constants";
import DAGEdge from "./DAGEdge";
import DAGNode from "./DAGNode";
import { DAG, Node } from "./types";
import { normalizeDAG } from "./dagFuncs";
export interface Props extends DAG {
onDelete: (nodeId: string) => void;
onOpenNode: (nodeId: string) => void;
}
export default function AutomationDAG({
onDelete,
onOpenNode,
...dag
}: Props) {
// state
const {nodes, edges} = normalizeDAG(dag);
// render
return <div className="automation-dag" >
<svg
viewBox={[0,0,GRAPH_WIDTH, GRAPH_HEIGHT].join(" ")}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
<marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5"
markerWidth="6" markerHeight="6"
orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" />
</marker>
</defs>
{/* <rect x="1" y="1" height={GRAPH_HEIGHT-1} width={GRAPH_WIDTH} stroke="white" fill="none"/> */}
<g className="automation-dag-edges">
{edges.map(({from, to, direction}, i) => <DAGEdge
key={i}
p1={nodes[from].loc}
p2={nodes[to].loc}
direction={direction}
/>
)}
</g>
<g className="automation-dag-nodes">
{Object.keys(nodes).map((nodeId) =>
<DAGNode
key={nodeId}
{...nodes[nodeId]}
onXClick={() => onDelete(nodeId)}
onOpenClick={() => onOpenNode(nodeId)}
/>
)}
</g>
</svg>
</div>
}
@@ -0,0 +1,42 @@
import { AutomationMetadata } from "~/automations/types";
import InputList from "../Inputs/InputList";
import InputText from "../Inputs/InputText";
import InputTextArea from "../Inputs/InputTextArea";
interface Props {
metadata: AutomationMetadata;
onUpdate: (m: AutomationMetadata) => void;
}
export default function AutoInfoBox({
metadata,
onUpdate,
}: Props) {
// aliases
const onUpdateMetadata = <K extends keyof AutomationMetadata>(k: K) =>(update: AutomationMetadata[K]) => onUpdate({
...metadata,
[k]: update
})
// render
return <g className="automation-dag-title">
<foreignObject x={0} y={0} height={125} width={100}>
<div>
<InputText label="ID" value={metadata.id} onChange={onUpdateMetadata('id')} />
<InputText label="Name" value={metadata.alias} onChange={onUpdateMetadata('alias')} />
<InputTextArea label="Description" value={metadata.description} onChange={onUpdateMetadata('description')} />
<InputList
label="Mode"
current={metadata.mode}
onChange={onUpdateMetadata('mode')}
options={[
'parallel',
'single',
'queued',
'restart'
]}
/>
</div>
</foreignObject>
</g>
}
@@ -1,35 +0,0 @@
import { PropsWithChildren, useState } from "react";
export interface Props {
title: string;
initialOpenState?: boolean;
onXClick?: () => void;
}
export default function AutomationNode({
children,
title,
initialOpenState=false,
onXClick = () => {},
}: PropsWithChildren<Props>) {
const [isOpen, setOpen] = useState(initialOpenState);
return <div className="automation-node">
<div className="automation-node-inner">
<div
className="automation-node-inner-edge left"
onClick={() => onXClick()}
>
<div className="automation-node-side-button">X</div>
</div>
<div className="automation-node-inner-text">{title}</div>
<div
className="automation-node-inner-edge right"
onClick={() => setOpen(!isOpen)}
>
<div className="automation-node-side-button">{isOpen ? "▲" : "▼"}</div>
</div>
</div>
<div className={`automation-node-children ${isOpen ? "open" : "closed"}`}>
{children}
</div>
</div>
}
@@ -1,20 +0,0 @@
import { useState } from "react";
import { AutomationCondition } from "../../automation/types/condition";
import InputList from "../InputList";
export interface Props {
condition: AutomationCondition
}
export default function ConditionNode({
condition
}: Props) {
return <div className="condition-node">
{/* <InputList
current={condition.condition}
options={}
/> */}
</div>
}
@@ -11,7 +11,7 @@ export interface EdgeProp {
export default ({p1, p2, direction}: EdgeProp) => {
const [x1,y1] = [p1[0] + NODE_WIDTH, p1[1]+NODE_HEIGHT/2]
const [x2,y2] = [p2[0], p2[1]+NODE_HEIGHT/2]
const [mx,my] = [(x1+x2)/2, (y1+y2)/2]
const [_,my] = [(x1+x2)/2, (y1+y2)/2]
const theta = Math.atan2(y2 -y1, x2-x1) -Math.PI / 2
const cx1 = x1 + NODE_WIDTH
const cy1 = my - 30 * Math.cos(theta)
@@ -9,7 +9,6 @@ export interface NodeProp extends Node {
isOpen?: boolean;
onXClick?: () => void;
onOpenClick?: () => void;
color?: Node['color'];
}
export default ({
loc: [x,y],
@@ -19,10 +18,10 @@ export default ({
onXClick=() => {},
onOpenClick=() => {},
isOpen=false,
color='none',
nodeType,
}: NodeProp) => <foreignObject x={x} y={y} width={width} height={height}>
<div className="automation-dag--node">
<div className={`automation-dag--node-inner ${color !== 'none' ? `top-color ${color}`: ''}`}>
<div className={`automation-dag--node-inner ${nodeType}`}>
<div className="automation-dag--node-inner-edge left" onClick={onXClick}>
<div className="automation-node-side-button">X</div>
</div>
@@ -1,46 +0,0 @@
import { useState, useEffect } from "react";
import StateManager from "../../automation/StateManager";
import { AutomationNodeType, AutomationNodeTypes, NodeSubType, typeList } from "../../automation/types";
import InputList from "../InputList";
export interface Props<T extends AutomationNodeType> {
node_type: T,
onClose: () => void,
onCreate: (newnode: AutomationNodeTypes[T]) => void,
}
export default function NewNodeModal<T extends AutomationNodeType>({
node_type,
onClose,
onCreate,
}: Props<T>) {
const [selectedSubType, setSubType] = useState<NodeSubType>(typeList[node_type][0]);
const stateManager = new StateManager(node_type, selectedSubType);
useEffect(() => {
if (stateManager.nodeType !== node_type || stateManager.nodeSubtype !== selectedSubType) {
stateManager.swapBaseState(node_type, selectedSubType)
}
}, [node_type, selectedSubType]);
return <div className="new-node-modal">
<div className="new-node-modal--background" onClick={() => onClose()}></div>
<div className="new-node-modal--inner" onClick={e => e.preventDefault()}>
<div className="new-node-modal--title">Create {node_type[0].toUpperCase()}{node_type.slice(1)}</div>
<div className="new-node-modal--body">
<InputList label="Type:"
options={typeList[node_type]}
current={selectedSubType}
onChange={n => setSubType(n as NodeSubType)}
/>
{stateManager.renderOptionList()}
</div>
<div className="new-node-modal--footer">
<button onClick={() => onClose()}>Close</button>
<button onClick={() => onCreate(stateManager.state)}
disabled={!stateManager.isReady}>
Create
</button>
</div>
</div>
</div>
}
@@ -1,21 +0,0 @@
import StateManager from "../../automation/StateManager";
import { AutomationAction } from "../../automation/types";
import { determineNodeTypes, getDescriptionFromAutomationNode } from "../../automation/utils";
import AutomationNode from "./AutomationNode";
export interface Props {
data: AutomationAction;
onDelete: () => void;
}
export default function ScriptNode({
data,
onDelete,
}: Props) {
const [nodeType, nodeSubType] = determineNodeTypes(data);
const stateManager = new StateManager(nodeType, nodeSubType, data);
return <AutomationNode title={getDescriptionFromAutomationNode(data)} onXClick={onDelete}>
{stateManager.renderOptionList()}
</AutomationNode>
}
+36 -82
View File
@@ -1,87 +1,41 @@
import { useState } from "react";
import * as types from "../../automation/types";
import AutomationNode from "./AutomationNode";
import NewNodeModal from "./NewNodeModal";
import ScriptNode from "./ScriptNode";
import { AutomationData } from "~/automations/types";
import AutoInfoBox from "./AutoInfoBox";
export interface Props {
automation: types.Automation;
interface Props {
automation: AutomationData;
onUpdate: (auto: AutomationData) => void;
}
export default function AutomationEditor({ automation }: Props) {
// state
const [modalState, setModalState] = useState<types.AutomationNodeType | null>(null);
const [state, setState] = useState(automation);
export default function AutomationEditor({
automation,
onUpdate,
}: Props) {
// helper state functions
const addNode = <T extends types.AutomationNodeType>(node_type: T, node: types.AutomationNodeTypes[T]) => {
const nodes: types.AutomationNode<T>[] = state[node_type];
setState({
...state,
[node_type]: nodes.concat([node as any])
});
}
const removeNode = <T extends types.AutomationNodeType>(node_type: T, node_id: number) => {
const nodes: types.AutomationNode<T>[] = state[node_type];
setState({
...state,
[node_type]: nodes
.slice(0, node_id)
.concat(
nodes.slice(
node_id + 1,
nodes.length
)
)
});
}
// helper element functions
const makeChild = <T extends types.AutomationNodeType>(node_type: T) => {
return [
<div className="automation-editor--elm-list" key="list">
{state[node_type].map((n, i) => (
<ScriptNode
key={i}
onDelete={() => removeNode(node_type, i)}
data={n as any}
/>
))}
</div>,
<button
key="btn"
className="elm-list"
onClick={() => setModalState(node_type)}
>
Add +
</button>
];
}
const graphWidth = 300;
const graphHeight = 300;
return <div className="automation-editor">
<AutomationNode
title={`${automation.alias} (${automation.mode})`}
initialOpenState={true}
>
<div className="automation-editor--root">
<div className="automation-editor--triggers">
<h4>Trigger</h4>
{makeChild("trigger")}
<h4>Condition</h4>
{makeChild("condition")}
</div>
<div className="automation-editor--playground">
<h4>Actions</h4>
{makeChild("action")}
</div>
</div>
</AutomationNode>
{modalState && <NewNodeModal
node_type={modalState}
onClose={() => setModalState(null)}
onCreate={node => {
addNode(modalState, node);
setModalState(null);
}}
/>}
</div>
return <div className="automation-dag" >
<svg
viewBox={[0,0,graphWidth, graphHeight].join(" ")}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
<marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5"
markerWidth="6" markerHeight="6"
orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" />
</marker>
</defs>
<AutoInfoBox
metadata={automation.metadata}
onUpdate={metadata => onUpdate({...automation, metadata})}
/>
{/* <rect x="1" y="1" height={GRAPH_HEIGHT-1} width={GRAPH_WIDTH} stroke="white" fill="none"/> */}
{/* <g className="automation-dag-edges">
</g>
<g className="automation-dag-nodes">
</g> */}
</svg>
</div>
}
@@ -1,10 +1,11 @@
import { AutomationNodeTypes } from "../../automations/types";
export type Point = [number, number];
export interface Node {
loc: Point;
text: JSX.Element | string;
color?: 'red' | 'green' | 'blue' | 'none';
nodeType: AutomationNodeTypes;
}
export interface Edge {
from: string;
@@ -16,6 +17,3 @@ export interface DAG {
nodes: Record<string,Node>;
edges: Array<Edge>;
}
export interface NormalizedDag extends DAG {
// overflow: boolean;
}
@@ -0,0 +1,37 @@
import { useToolTip } from "~/tooltip/context";
import InputWrapper from "./InputWrapper";
export interface Props {
textBoxFor?: string;
label: string;
value: string;
onChange: (v: string) => void;
additionalTooltipFilters?: Record<string, string>;
}
export default function InputTextArea({
label,
textBoxFor,
value="",
onChange,
additionalTooltipFilters={},
}: Props) {
const tooltip = useToolTip();
return <InputWrapper label={label}>
<textarea
value={value}
onChange={e => {
e.preventDefault();
onChange(e.target.value)
}}
onFocus={e => textBoxFor && tooltip.setFocus(
e.target.getBoundingClientRect(),
{
searchObject: textBoxFor,
searchText: value,
filterObjects: additionalTooltipFilters,
},
onChange
)}
/>
</InputWrapper>
}
+10 -6
View File
@@ -1,4 +1,4 @@
import { useRef, useState, useEffect } from "react";
import { useRef, useState, useEffect, HTMLProps } from "react";
import CheckMarkIcon from "~/icons/checkmark";
import PencilIcon from "~/icons/pencil";
import { useToolTip } from "~/tooltip/context";
@@ -10,6 +10,7 @@ export interface Props {
value: string;
onChange: (v: string) => void;
additionalTooltipFilters?: Record<string, string>;
useTextArea?: boolean;
}
export default function InputViewEdit({
label,
@@ -17,6 +18,7 @@ export default function InputViewEdit({
value="",
onChange,
additionalTooltipFilters={},
useTextArea=false,
}: Props) {
const tooltip = useToolTip();
const [isEditing, setIsEditing] = useState(false);
@@ -29,16 +31,18 @@ export default function InputViewEdit({
if (isEditing && inputRef.current) {
inputRef.current.focus()
}
}, [inputRef.current, isEditing])
}, [inputRef.current, isEditing]);
const Text = useTextArea ? (p: HTMLProps<any>) => <textarea {...p}/> : (p: HTMLProps<any>) => <input {...p}/>;
return <InputWrapper label={label}>
{isEditing ? <input
{isEditing ? <Text
ref={inputRef}
value={value}
onChange={e => {
e.preventDefault();
onChange={(e:any) => {
onChangeWrapped(e.target.value)
}}
onFocus={e => textBoxFor && tooltip.setFocus(
onFocus={(e: any) => textBoxFor && tooltip.setFocus(
e.target.getBoundingClientRect(),
{
searchObject: textBoxFor,