This commit is contained in:
ari committed 2022-07-15 18:35:25 -04:00
1 parent a35e8e127f
commit 2ea96973ad
20 files changed
+372 -150

No files matched your search

+1
View File
@@ -1 +1,2 @@
.vscode/*.log
webapp/src/types/validators/index.test.ts
@@ -29,10 +29,41 @@
display: flex;
flex-direction: row;
gap: 0.25em;
justify-content: flex-end;
justify-content: space-between;
margin-top: 0.25em;
}
.automation-editor--flow-wrapper--toolbar--title {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
gap: 0.25em;
width: 100%;
}
.automation-editor--flow-wrapper--toolbar--title--text .id {
font-size: 0.75em;
max-width: 15em;
padding: 0;
margin: 0;
white-space: break-word;
overflow: hidden;
text-overflow: ellipsis;
}
.automation-editor--flow-wrapper--toolbar .automation-editor--flow-wrapper--toolbar--modes .MuiSelect-select {
padding-left: 0.25em;
padding-right: 0.25em;
padding-top: 1.15em;
padding-bottom: 0.25em;
}
.automation-editor--flow-wrapper--toolbar .automation-editor--flow-wrapper--toolbar--modes .MuiInputLabel-root {
font-size: 0.9em;
left: -0.5em;
}
.automation-editor--flow-wrapper.changed>.automation-editor--flow-wrapper--toolbar * {
border-color: var(--mui-success-light);
color: var(--mui-success-light)
@@ -45,7 +45,8 @@ Simple.args = {
Use: "Flushing",
},
metadata: {
id: "random",
id:
"random" + String(Date.now()) + String(Date.now()) + String(Date.now()),
alias: "Random",
description: "Example Metadata",
trigger_variables: {
@@ -16,6 +16,8 @@ import { ArrowBack } from "@mui/icons-material";
import { useCookies } from "react-cookie";
import { DAGDims } from "components/DAGGraph/elements/types";
import { DAGAutomationGraph } from "components/DAGGraph";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { InputList } from "components/Inputs/InputList";
interface Props {
automation?: AutomationData;
@@ -95,6 +97,53 @@ export const AutomationEditor: FC<Props> = ({
className={["automation-editor--flow-wrapper", state.status].join(" ")}
>
<div className="automation-editor--flow-wrapper--toolbar">
<div className="automation-editor--flow-wrapper--toolbar--title">
<span className="automation-editor--flow-wrapper--toolbar--title--text">
<div className="id">{state.data.metadata.id}</div>
<b>{state.data.metadata.alias}</b>
</span>
<InputList
fullWidth={false}
label="Mode"
className="automation-editor--flow-wrapper--toolbar--modes"
current={{
id: state.data.metadata.mode,
label: "",
}}
onChange={({ id }) =>
updateMetadata(
{
...state.data.metadata,
mode: id,
},
state.data.tags
)
}
getKey={({ id }) => id}
getDescription={({ label }) => label}
options={[
{
id: "single",
label: "Do not start a new run. Issue a warning.",
},
{
id: "parallel",
label:
"Start a new, independent run in parallel with previous runs.",
},
{
id: "queued",
label:
"Start a new run after all previous runs complete. Runs are guaranteed to execute in the order they were queued.",
},
{
id: "restart",
label: "Start a new run after first stopping previous run.",
},
]}
/>
<small>{state.data.metadata.description}</small>
</div>
{!dims.flipped && (
<Button
className={"automation-editor--flow-wrapper--toolbar--flip-btn"}
@@ -101,7 +101,7 @@ export const BadAutmations = make([
condition: [],
tags: {},
metadata: {
id: "Bad Choose Sequence",
id: "Bad Choose Example",
alias: "Bad Choose",
description: "Example Metadata",
trigger_variables: {
@@ -112,7 +112,7 @@ export const BadAutmations = make([
trigger: [],
sequence: [
{
choose: {},
choose: [],
},
] as any,
},
@@ -69,7 +69,7 @@ export const DAGGraphBoardInner: FC<DAGGraphBoardProps> = ({
nodesDraggable={false}
{...elements}
>
<Controls showInteractive={false} />
<Controls showInteractive={false} showFitView />
</ReactFlow>
</>
);
@@ -468,3 +468,36 @@ ParallelAuto.args = {
],
},
};
export const BadNodes = Template.bind({});
BadNodes.args = {
...BadNodes.args,
automation: {
condition: [
{
event: "triggerme",
},
{
condition: "and",
thisshouldnotbehere: "1",
conditions: "1234",
},
] as any,
trigger: [
{ platform: "homeassistant" },
{ platfom: "bobid" },
{ condition: "and" },
"text?",
] as any,
sequence: [
{
parallel: {
bad: "me",
},
},
{
platform: "event",
},
] as any,
},
};
@@ -14,6 +14,7 @@ import { SequenceNodeMaker } from "../nodes/SequenceNode";
import {
getNodeType,
convertScriptConditionFieldToAutomationConditions,
validateNode,
} from "utils/automations";
import { ButtonNodeMaker } from "../nodes/ButtonNode";
import { AddIcon } from "components/Icons";
@@ -24,6 +25,9 @@ import { getSpecialNodeMaker, makeSpecialNodeMaker } from "./specialnodes";
import { getNodeSubType } from "../../../utils/automations";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import Add from "@mui/icons-material/Add";
import { SequenceNodeDataProps } from "../nodes/SequenceNode/types";
import InfoOutlined from "@mui/icons-material/InfoOutlined";
import { convertFailuresToSequenceNodeDataProps } from "./util";
export const useAutomationNodes = (
automation: AutomationActionData,
@@ -91,11 +95,23 @@ export const makeTriggerNodes: ElementMaker<AutomationTrigger> = (
...dims.collection,
collectionType: "trigger",
onAddNode: () => stateUpdater.basic.trigger.addNode(null),
nodes: nodes.map((node, index) => ({
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("trigger", index, {}),
})),
nodes: nodes.map((node, index) => {
const failures = validateNode(node, ["condition"]);
if (failures) {
return {
enabled: node.enabled ?? true,
...stateUpdater.createNodeActions("trigger", index, {}),
...convertFailuresToSequenceNodeDataProps(failures),
};
}
return {
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("trigger", index, {}),
};
}),
})
);
return outputState;
@@ -112,11 +128,23 @@ export const makeConditionNodes: ElementMaker<AutomationCondition> = (
collectionType: "condition",
hasInput: !!lastNodeId,
onAddNode: () => stateUpdater.basic.condition.addNode(null),
nodes: nodes.map((node, index) => ({
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("condition", index, {}),
})),
nodes: nodes.map((node, index) => {
const failures = validateNode(node, ["condition"]);
if (failures) {
return {
enabled: node.enabled ?? true,
...stateUpdater.createNodeActions("condition", index, {}),
...convertFailuresToSequenceNodeDataProps(failures),
};
}
return {
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("condition", index, {}),
};
}),
})
);
if (lastNodeId && outputState.lastNodeId) {
@@ -133,10 +161,25 @@ export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
const outputState = new DAGElementsOutputState(position, dims);
nodes.forEach((node, nodeIndex) => {
// the JSON.stringify is hack to make the edges render nicely
const nodeId = `${args.nodeId}-${
args.nodeIndex
}-${nodeIndex}-${JSON.stringify(node)}`;
const nodeId = `${args.nodeId}-${args.nodeIndex}-${nodeIndex}`;
outputState.incNextPos("node");
let nodeData: SequenceNodeDataProps = {
color: getNodeType(node) === "action" ? "green" : "blue",
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...state.getIsClosedActions(nodeId, node),
...stateUpdater.createNodeActions("sequence", nodeIndex, {
includeAdd: true,
flipped: dims.flipped,
}),
};
const failures = validateNode(node, ["action", "condition"]);
if (failures) {
nodeData = {
...nodeData,
...convertFailuresToSequenceNodeDataProps(failures),
};
}
const element = outputState.addNode(
SequenceNodeMaker.makeElement(
{
@@ -144,36 +187,29 @@ export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
position: outputState.nextPos,
},
dims,
{
color: getNodeType(node) === "action" ? "green" : "blue",
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...state.getIsClosedActions(nodeId, node),
...stateUpdater.createNodeActions("sequence", nodeIndex, {
includeAdd: true,
flipped: dims.flipped,
}),
}
nodeData
),
true
);
if (nodeIndex === 0 && lastNodeId) {
outputState.addEdge(lastNodeId, element.id);
}
const specialNodeMaker = getSpecialNodeMaker(
getNodeSubType(node, true) as any
);
if (specialNodeMaker) {
outputState.extend(
specialNodeMaker([node] as any, {
...args,
nodeId,
lastNodeId: element.id,
position: outputState.getLastNodePos(),
nodeIndex,
}),
true
if (!failures) {
const specialNodeMaker = getSpecialNodeMaker(
getNodeSubType(node, true) as any
);
if (specialNodeMaker) {
outputState.extend(
specialNodeMaker([node] as any, {
...args,
nodeId,
lastNodeId: element.id,
position: outputState.getLastNodePos(),
nodeIndex,
}),
true
);
}
}
});
@@ -0,0 +1,21 @@
import { MiniFailure } from "types/validators/helper";
import { SequenceNodeColor } from "../nodes/SequenceNode/types";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
export const convertFailuresToSequenceNodeDataProps = (
failures: MiniFailure[]
) => {
return {
label: (
<>
<InfoOutlinedIcon />
<div className="daggraph--error">
{failures.map((f, i) => (
<span key={i}>{f.message}</span>
))}
</div>
</>
),
color: "error" as SequenceNodeColor,
};
};
@@ -1,49 +0,0 @@
import { Button } from "components/Inputs/Button";
import InputYaml from "components/Inputs/InputYaml";
import { FC } from "react";
import { DAGGraphBoardProps } from "../board/types";
export const ErroredBoard: FC<
DAGGraphBoardProps & {
error: Error | any;
}
> = (props) => {
// const makeSet = <K 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>
);
};
@@ -71,11 +71,11 @@ export const CollectionNode: FC<CollectionNodeProps> = ({
<div className="collection-nodes--inner">
{nodes.map((n, i) => (
<SequenceNodeElement
{...n}
{...sequenceNode}
key={i}
color={color}
flipped={flipped}
{...n}
{...sequenceNode}
/>
))}
</div>
@@ -6,6 +6,7 @@ import { AutomationActionData } from "types/automations";
export type CollectionNodeChildProps = Partial<SequenceNodeActions> & {
enabled: boolean;
label: ReactNode;
color?: SequenceNodeColor;
};
export type CollectionNodeDataProps = Size & {
nodes: CollectionNodeChildProps[];
@@ -1,6 +1,6 @@
import { ReactNode } from "react";
export type SequenceNodeColor = "red" | "blue" | "green" | "lblue";
export type SequenceNodeColor = "red" | "blue" | "green" | "lblue" | "error";
export type SequenceNodeOnMove<Direction extends string> = Record<
Direction,
() => void
@@ -11,6 +11,8 @@ export const useSequenceNodeColor = (color: SequenceNodeColor): string => {
: color === "lblue"
? theme.palette.info.light
: color === "red"
? theme.palette.warning.dark
: color === "error"
? theme.palette.error.dark
: "none";
};
@@ -0,0 +1,15 @@
.MuiMenuItem-root.input-list--menu-item {
display: inherit;
}
.input-list--menu-item .input-list--menu-item--description {
font-size: 0.75em;
max-width: 80vw;
overflow: hidden;
text-overflow: ellipsis;
overflow-wrap: break-word;
}
.MuiSelect-select .input-list--menu-item--description {
display: none;
}
+17 -3
View File
@@ -1,3 +1,5 @@
import "./InputList.css";
import FormHelperText from "@mui/material/FormHelperText";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
@@ -15,11 +17,13 @@ export type Props<T extends string | Object> = {
className?: string;
prettyOptionLabels?: boolean;
getKey?: (n: T) => string;
getDescription?: (n: T) => string;
placeholder?: any;
title?: string;
helperText?: string;
endAdornment?: ReactNode;
disabled?: boolean;
fullWidth?: boolean;
};
export function InputList<T extends string | Object>({
current,
@@ -30,11 +34,13 @@ export function InputList<T extends string | Object>({
className,
prettyOptionLabels = true,
getKey = String,
getDescription,
placeholder,
title,
helperText,
endAdornment,
disabled,
fullWidth = true,
}: Props<T>) {
const invalidCurrent =
current && !options.map(getKey).includes(getKey(current));
@@ -43,7 +49,7 @@ export function InputList<T extends string | Object>({
className={className}
variant="filled"
sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}
fullWidth
fullWidth={fullWidth}
disabled={disabled}
>
<InputLabel>{label}</InputLabel>
@@ -62,12 +68,20 @@ export function InputList<T extends string | Object>({
label={label}
variant="filled"
error={invalidCurrent}
fullWidth
fullWidth={fullWidth}
disabled={disabled}
>
{options.map((t, i) => (
<MenuItem key={i} value={getKey(t)}>
<MenuItem key={i} value={getKey(t)} className="input-list--menu-item">
{prettyOptionLabels ? prettyName(getKey(t)) : getKey(t)}
{!!getDescription && (
<>
<br />
<div className="input-list--menu-item--description">
{getDescription(t)}
</div>
</>
)}
</MenuItem>
))}
</Select>
+23 -6
View File
@@ -2,14 +2,31 @@ import { FC } from "react";
export const SimpleErrorElement: FC<{ error: Error }> = ({ error }) => {
return (
<>
<b>{error?.name}</b>
<div
style={{
padding: "1em",
}}
>
<b>Error Name</b>: {error?.name}
<br />
<b>{error?.message}</b>
<b>Error Message</b>
{error?.message}
<br />
<span>{error?.stack}</span>
<b>Error Stack</b>
<code
style={{
display: "flex",
flexDirection: "column",
padding: "1em",
}}
>
{error?.stack?.split("\n").map((t, i) => (
<span key={i}>{t}</span>
))}
</code>
<br />
<span>{JSON.stringify(error)}</span>
</>
<b>JSON:</b>
<code>{JSON.stringify(error)}</code>
</div>
);
};
+52 -46
View File
@@ -1,55 +1,61 @@
import * as st from "superstruct";
import { AutomationMetadata } from "./metadata";
import { AutomationData } from './autmation';
import { getFailures } from './helper';
import { AutomationData } from "./autmation";
import { getFailures } from "./helper";
import { AutomationTimeString } from "./common";
import { ParallelAction } from "./actions";
test('superstructure is', () => {
const badCheck = st.is({}, AutomationMetadata);
expect(badCheck).toBeFalsy()
})
test("superstructure is", () => {
const badCheck = st.is({}, AutomationMetadata);
expect(badCheck).toBeFalsy();
});
test('getFailures returns failures', () => {
const failures = getFailures({ metadata: {} }, AutomationData);
expect(failures).toHaveLength(6)
})
test("getFailures returns failures", () => {
const failures = getFailures({ metadata: {} }, AutomationData);
expect(failures).toHaveLength(6);
});
test('getFailures returns null', () => {
const failures = getFailures({
id: "test",
alias: "hey",
description: "wow",
mode: "single",
}, AutomationMetadata);
expect(failures).toBeNull()
})
test("getFailures returns null", () => {
const failures = getFailures(
{
id: "test",
alias: "hey",
description: "wow",
mode: "single",
},
AutomationMetadata
);
expect(failures).toBeNull();
});
test('AutomationTimeString is valid', () => {
for (const c of [
'10:23',
'15:02',
'13:00:1',
'23:00:23'
]) {
const failures = getFailures(c, AutomationTimeString)
expect(failures).toBeNull()
}
})
test("AutomationTimeString is valid", () => {
for (const c of ["10:23", "15:02", "13:00:1", "23:00:23"]) {
const failures = getFailures(c, AutomationTimeString);
expect(failures).toBeNull();
}
});
test("AutomationTimeString is invalid", () => {
for (const c of ["xx:23", "1x:02", "13:0a:1c", "25:00:23", "11"]) {
const failures = getFailures(
{
time: c,
},
st.object({
time: AutomationTimeString,
})
);
expect(failures).toHaveLength(1);
}
});
test('AutomationTimeString is invalid', () => {
for (const c of [
'xx:23',
'1x:02',
'13:0a:1c',
'25:00:23',
'11'
]) {
const failures = getFailures({
"time": c
}, st.object({
time: AutomationTimeString,
}))
expect(failures).toHaveLength(1)
}
})
test("Node Validation for parallel", () => {
expect(
getFailures(
{
parallel: { bad: "me" },
},
ParallelAction
)
).toHaveLength(1);
});
+23
View File
@@ -0,0 +1,23 @@
import { validateNode } from "./automations";
test("validate works on bad conditions", () => {
expect(
validateNode(
{
condition: "and",
thisshouldnotbehere: "1",
conditions: "1234",
} as any,
["condition"]
)
).toHaveLength(1);
expect(
validateNode(
{
event: "triggerme",
},
["condition"]
)
).toHaveLength(2);
});
+23 -2
View File
@@ -196,6 +196,18 @@ export const validateNode = (
node: AutomationNode,
allowedNodeTypes: AutomationNodeTypes[] = []
): MiniFailure[] | null => {
if (typeof node !== "object") {
return [
{
message: [
`Expected an object but got type of "${typeof node}" = ${JSON.stringify(
node
)}`,
],
path: "$",
},
];
}
let nodeType = getNodeType(node);
let errors: MiniFailure[] = [];
if (allowedNodeTypes.length > 0 && !allowedNodeTypes.includes(nodeType)) {
@@ -203,7 +215,7 @@ export const validateNode = (
message: [
`Got node of type "${nodeType}" but expected one of {${allowedNodeTypes}}`,
],
path: "",
path: "$",
});
nodeType = allowedNodeTypes[0];
}
@@ -214,7 +226,16 @@ export const validateNode = (
errors.push({ message: [`Failed to identifiy subtype`], path: "" });
}
if (nodeSubType) {
const failures = getFailures(node, AllValidators[nodeType][nodeSubType]);
const validator = AllValidators[nodeType][nodeSubType];
if (!validator) {
return errors.concat([
{
message: [`"${nodeSubType}" is not a known type for ${nodeType}`],
path: "$",
},
]);
}
const failures = getFailures(node, validator);
if (failures) {
errors = errors.concat(failures);
}