trigger state autofill

This commit is contained in:
ari committed 2022-06-16 21:23:28 -04:00
1 parent 736a6053ef
commit 326775848b
8 files changed
+440 -268

No files matched your search

@@ -5,6 +5,7 @@ import Chip from "@mui/material/Chip";
import { Badge } from "@mui/material";
import { SearchItem } from "./extras";
import { ReactNode } from "react";
import { prettyName } from "utils/formatting";
export type BaseOption<T = {}> = {
id: string;
@@ -204,7 +205,11 @@ export function InputAutoComplete<T extends Option>(
size="medium"
label={
<>
{id === label ? <span>{label}</span> : <b>{label}</b>}
{id === label ? (
<span>{prettyName(label)}</span>
) : (
<b>{label}</b>
)}
{id !== label && !props.onlyShowLabel && (
<small>{id}</small>
)}
@@ -41,6 +41,7 @@ export function InputList<T extends string | Object>({
className={className}
variant="filled"
sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}
fullWidth
>
<InputLabel>{label}</InputLabel>
<Select
+46 -50
View File
@@ -1,7 +1,6 @@
import React, { PropsWithChildren, ReactNode, useState } from "react";
import React, { ReactNode, useState } from "react";
import { useToolTip } from "tooltip/context";
import TextField from "@mui/material/TextField";
import InputWrapper from "./InputWrapper";
export interface Props {
textBoxFor?: string;
@@ -31,59 +30,56 @@ export default function InputText({
additionalTooltipFilters = {},
multiline = false,
maxRows = 4,
children,
className,
placeholder,
required,
}: PropsWithChildren<Props>) {
}: Props) {
const tooltip = useToolTip();
const [isFocused, setIsFocused] = useState(false);
return (
<InputWrapper className={className} label="">
<TextField
multiline={multiline}
maxRows={maxRows}
fullWidth
inputMode="text"
variant="filled"
focused={isFocused}
label={label}
value={value}
title={title}
helperText={helperText}
placeholder={placeholder}
InputProps={{
endAdornment,
}}
required={required}
onKeyDown={(e) => {
if (e.key === "Enter") {
onEnter();
}
}}
onChange={(e) => {
e.preventDefault();
onChange(e.target.value);
}}
onBlur={() => {
setIsFocused(false);
}}
onFocus={(e) => {
setIsFocused(true);
if (textBoxFor) {
tooltip.setFocus(
e.target.getBoundingClientRect(),
{
searchObject: textBoxFor,
searchText: value,
filterObjects: additionalTooltipFilters,
},
onChange
);
}
}}
/>
{children}
</InputWrapper>
<TextField
className={className}
multiline={multiline}
maxRows={maxRows}
fullWidth
inputMode="text"
variant="filled"
focused={isFocused}
label={label}
value={value}
title={title}
helperText={helperText}
placeholder={placeholder}
InputProps={{
endAdornment,
}}
required={required}
onKeyDown={(e) => {
if (e.key === "Enter") {
onEnter();
}
}}
onChange={(e) => {
e.preventDefault();
onChange(e.target.value);
}}
onBlur={() => {
setIsFocused(false);
}}
onFocus={(e) => {
setIsFocused(true);
if (textBoxFor) {
tooltip.setFocus(
e.target.getBoundingClientRect(),
{
searchObject: textBoxFor,
searchText: value,
filterObjects: additionalTooltipFilters,
},
onChange
);
}
}}
/>
);
}
+3 -2
View File
@@ -2,6 +2,7 @@ import "./extras.css";
import { FC } from "react";
import parse from "autosuggest-highlight/parse";
import match from "autosuggest-highlight/match";
import { prettyName } from "utils/formatting";
export const HighlightElm: FC<{
text: string;
@@ -38,7 +39,7 @@ export const SearchItem: FC<{
let inner = (
<>
<b>
<HighlightElm text={label} searchTerm={searchTerm} />
<HighlightElm text={prettyName(label)} searchTerm={searchTerm} />
</b>{" "}
<small>
<HighlightElm text={id} searchTerm={searchTerm} />
@@ -51,7 +52,7 @@ export const SearchItem: FC<{
inner = (
<>
<b>
<HighlightElm text={label} searchTerm={searchTerm} />
<HighlightElm text={prettyName(label)} searchTerm={searchTerm} />
</b>{" "}
</>
);
@@ -1,54 +1,128 @@
import { OptionManager } from './OptionManager';
import { AutomationTriggerState } from 'types/automations/triggers';
import InputText from 'components/Inputs/InputText';
import { InputEntity } from 'components/Inputs/InputEntities';
import { InputTime } from 'components/Inputs/InputTime';
import { OptionManager } from "./OptionManager";
import { AutomationTriggerState } from "types/automations/triggers";
import InputText from "components/Inputs/InputText";
import { InputEntity } from "components/Inputs/InputEntities";
import { InputTime } from "components/Inputs/InputTime";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { FC } from "react";
import { getEntityDomains } from "utils/automations";
import { InputList } from "components/Inputs/InputList";
import { entityDomainsAreBinary } from "../../../utils/automations";
export const TriggerState: OptionManager<AutomationTriggerState> = {
defaultState: () => ({
"platform": 'state',
"entity_id": "",
platform: "state",
entity_id: "",
}),
isReady: () => true,
renderOptionList: (state, setState) => {
return <>
<InputEntity
value={state.entity_id}
multiple
onChange={entity_id => setState({
...state,
entity_id
})}
/>
<InputText label="Attribute" value={state.attribute ?? ""} onChange={attribute => setState({
...state,
attribute
})} />
Component: ({ state, setState, entities }) => {
const attributes = entities.getAttributes(state.entity_id);
const states = entities.getStates(state.entity_id, state.attribute);
return (
<>
<InputEntity
value={state.entity_id}
multiple
onChange={(entity_id) =>
setState({
...state,
entity_id,
})
}
/>
<InputAutoComplete
label="Attribute"
value={state.attribute ?? ""}
options={attributes}
multiple={false}
onChange={(attribute) =>
setState({
...state,
attribute: attribute ?? undefined,
})
}
/>
<FromTo
entityId={state.entity_id}
hasAttribute={!!state.attribute}
values={{ to: state.to ?? "", from: state.from ?? "" }}
onChange={(x) => setState({ ...state, ...x })}
states={states}
/>
<InputTime
label="For"
value={state.for}
onChange={(_for) =>
setState({
...state,
for: _for,
})
}
/>
</>
);
},
};
export const FromTo: FC<{
entityId: string | string[];
hasAttribute: boolean;
values: { to: string; from: string };
onChange: (s: Partial<{ to: string; from: string }>) => void;
states: string[];
}> = (props) => {
if (!props.hasAttribute) {
const domains = getEntityDomains(props.entityId);
if (entityDomainsAreBinary(domains)) {
return (
<div style={{ display: "flex", flexDirection: "row", gap: "0.25em" }}>
<InputList
label="From"
options={["on", "off"]}
current={props.values.from}
onChange={(from) =>
props.onChange({
from,
})
}
/>
<InputList
label="To"
options={["on", "off"]}
current={props.values.to}
onChange={(to) =>
props.onChange({
to,
})
}
/>
</div>
);
}
}
const example = `eg. ${props.states.join(" or ")}`;
return (
<div style={{ display: "flex", flexDirection: "row", gap: "0.25em" }}>
<InputText
label="From"
value={state.from ?? ""}
onChange={from => setState({
...state,
from,
})}
value={props.values.from}
onChange={(from) =>
props.onChange({
from,
})
}
placeholder={example}
/>
<InputText
label="To"
value={state.to ?? ""}
onChange={to => setState({
...state,
to,
})}
value={props.values.to}
onChange={(to) =>
props.onChange({
to,
})
}
placeholder={example}
/>
<InputTime
label="For"
value={state.for}
onChange={_for => setState({
...state,
for: _for,
})}
/>
</>
}
}
</div>
);
};
@@ -114,3 +114,12 @@ DelayExample.args = {
wait_template: "",
},
};
export const StateTriggerExample = Action.bind({});
StateTriggerExample.args = {
...StateTriggerExample.args,
node: {
platform: "state",
entity_id: "binary_sensor.door_main",
},
};
+46
View File
@@ -18,6 +18,52 @@ export const useHAEntities = () => {
).sort(),
}));
const methods = {
getStates(inp: string[] | string, attribute?: string): string[] {
if (!entities.ready) {
return [];
}
let entityIds: string[] = [];
if (typeof inp === "string") {
entityIds = [inp];
} else if (Array.isArray(inp)) {
entityIds = inp;
}
let state: Set<string> = new Set();
entityIds.forEach((entityId) => {
if (!attribute) {
state.add(entities.collection.state[entityId].state);
} else {
const val = entities.collection.state[entityId].attributes[attribute];
if (val) {
state.add(val);
}
}
});
return Array.from(state.keys());
},
getAttributes(inp: string[] | string): string[] {
if (!entities.ready) {
return [];
}
let entityIds: string[] = [];
if (typeof inp === "string") {
entityIds = [inp];
} else if (Array.isArray(inp)) {
entityIds = inp;
}
let attributes: Set<string> = new Set();
entityIds.forEach((entityId) => {
const thisAttrs = new Set(
Object.keys(entities.collection.state[entityId].attributes)
);
if (attributes.size === 0) {
attributes = thisAttrs;
} else {
attributes = new Set([...attributes].filter((a) => thisAttrs.has(a)));
}
});
return Array.from(attributes.keys());
},
getDomainList(): string[] {
return entities.additional?.domains ?? [];
},
+212 -172
View File
@@ -1,196 +1,236 @@
import * as v from "types/validators";
import { AutomationNode, AutomationNodeMapping, AutomationNodeSubtype, AutomationNodeTypes } from "types/automations";
import { AutomationTrigger, TriggerType } from 'types/automations/triggers';
import {
AutomationNode,
AutomationNodeMapping,
AutomationNodeSubtype,
AutomationNodeTypes,
} from "types/automations";
import { AutomationTrigger, TriggerType } from "types/automations/triggers";
import { MiniFailure } from "types/validators/helper";
import { getFailures } from '../types/validators/helper';
import { getFailures } from "../types/validators/helper";
import { ActionType } from "types/automations/actions";
import { ConditionType } from "types/automations/conditions";
import * as st from 'superstruct';
import * as st from "superstruct";
export const getNodeTypeAndValidate = (node: AutomationNode, allowedTypes: AutomationNodeTypes[]) => {
const nodeType = getNodeType(node);
if (allowedTypes.includes(nodeType)) {
return nodeType
}
throw new Error(`Detected '${nodeType}' but expected one of {${allowedTypes}}`)
}
export const getNodeTypeAndValidate = (
node: AutomationNode,
allowedTypes: AutomationNodeTypes[]
) => {
const nodeType = getNodeType(node);
if (allowedTypes.includes(nodeType)) {
return nodeType;
}
throw new Error(
`Detected '${nodeType}' but expected one of {${allowedTypes}}`
);
};
export const getNodeType = (node: AutomationNode): AutomationNodeTypes => {
if ('condition' in node) {
return 'condition'
} else if ('platform' in node) {
return 'trigger'
} else {
return 'action'
}
}
if ("condition" in node) {
return "condition";
} else if ("platform" in node) {
return "trigger";
} else {
return "action";
}
};
export const getSubTypeList = <T extends AutomationNodeTypes>(nodeType: T): AutomationNodeSubtype<T>[] => {
switch (nodeType) {
case 'action':
return [
"service",
"repeat",
"wait",
"device",
"choose",
] as any
case "condition":
return [
'or',
'and',
'not',
'numeric_state',
'state',
'template',
'time',
'trigger',
'zone',
] as any
case 'trigger':
return [
'event',
'homeassistant',
'mqtt',
'numeric_state',
'state',
'tag',
'template',
'time',
'time_pattern',
'webhook',
'zone',
'device',
] as any
default:
return [];
}
}
export const makeDefault = (nodeType: keyof AutomationNodeMapping): AutomationNode => {
switch (nodeType) {
case 'action':
return {
'data': {},
'service': '',
'target': {},
}
case 'condition':
return {
condition: 'and',
conditions: []
}
default:
return {
platform: 'device',
device_id: '',
domain: '',
type: '',
subtype: '',
} as AutomationTrigger
}
}
export const getSubTypeList = <T extends AutomationNodeTypes>(
nodeType: T
): AutomationNodeSubtype<T>[] => {
switch (nodeType) {
case "action":
return ["service", "repeat", "wait", "device", "choose"] as any;
case "condition":
return [
"or",
"and",
"not",
"numeric_state",
"state",
"template",
"time",
"trigger",
"zone",
] as any;
case "trigger":
return [
"event",
"homeassistant",
"mqtt",
"numeric_state",
"state",
"tag",
"template",
"time",
"time_pattern",
"webhook",
"zone",
"device",
] as any;
default:
return [];
}
};
export const makeDefault = (
nodeType: keyof AutomationNodeMapping
): AutomationNode => {
switch (nodeType) {
case "action":
return {
data: {},
service: "",
target: {},
};
case "condition":
return {
condition: "and",
conditions: [],
};
default:
return {
platform: "device",
device_id: "",
domain: "",
type: "",
subtype: "",
} as AutomationTrigger;
}
};
export const getNodeSubType = <T extends AutomationNodeTypes>(
node: AutomationNode<T>
node: AutomationNode<T>
): AutomationNodeSubtype<T> => {
if ('condition' in node) {
return node.condition as any;
} else if ('platform' in node) {
return node.platform as any;
} else if ('service' in node) {
return 'service' as any
} else if ('repeat' in node) {
return 'repeat' as any
} else if (('wait_template' in node) || ('wait_for_trigger' in node)) {
return 'wait' as any
} else if ('event' in node) {
return 'event' as any
} else if ('device_id' in node) {
return 'device' as any
} else if ('choose' in node) {
return 'choose' as any
} else if ('delay' in node) {
return 'wait' as any
} else {
throw new Error("Invalid node type!")
}
}
if ("condition" in node) {
return node.condition as any;
} else if ("platform" in node) {
return node.platform as any;
} else if ("service" in node) {
return "service" as any;
} else if ("repeat" in node) {
return "repeat" as any;
} else if ("wait_template" in node || "wait_for_trigger" in node) {
return "wait" as any;
} else if ("event" in node) {
return "event" as any;
} else if ("device_id" in node) {
return "device" as any;
} else if ("choose" in node) {
return "choose" as any;
} else if ("delay" in node) {
return "wait" as any;
} else {
throw new Error("Invalid node type!");
}
};
const TriggerValidators: Record<TriggerType, any> = {
"homeassistant": v.triggers.AutomationTriggerHA,
"device": v.triggers.AutomationTriggerDevice,
"event": v.triggers.AutomationTriggerEvent,
"mqtt": v.triggers.AutomationTriggerMQTT,
'numeric_state': v.triggers.AutomationTriggerNumericState,
"state": v.triggers.AutomationTriggerState,
"tag": v.triggers.AutomationTriggerTag,
"template": v.triggers.AutomationTriggerTemplate,
"time": v.triggers.AutomationTriggerTime,
"time_pattern": v.triggers.AutomationTriggerTimePattern,
"webhook": v.triggers.AutomationTriggerWebhook,
"zone": v.triggers.AutomationTriggerZone,
}
homeassistant: v.triggers.AutomationTriggerHA,
device: v.triggers.AutomationTriggerDevice,
event: v.triggers.AutomationTriggerEvent,
mqtt: v.triggers.AutomationTriggerMQTT,
numeric_state: v.triggers.AutomationTriggerNumericState,
state: v.triggers.AutomationTriggerState,
tag: v.triggers.AutomationTriggerTag,
template: v.triggers.AutomationTriggerTemplate,
time: v.triggers.AutomationTriggerTime,
time_pattern: v.triggers.AutomationTriggerTimePattern,
webhook: v.triggers.AutomationTriggerWebhook,
zone: v.triggers.AutomationTriggerZone,
};
const ActionValidators: Record<ActionType, any> = {
"choose": v.actions.ChooseAction,
"device": v.actions.DeviceAction,
"event": v.actions.FireEventAction,
"repeat": v.actions.RepeatAction,
"service": v.actions.ServiceAction,
"wait": st.union([
v.actions.DelayAction,
v.actions.WaitAction
]),
}
choose: v.actions.ChooseAction,
device: v.actions.DeviceAction,
event: v.actions.FireEventAction,
repeat: v.actions.RepeatAction,
service: v.actions.ServiceAction,
wait: st.union([v.actions.DelayAction, v.actions.WaitAction]),
};
const ConditionValidators: Record<ConditionType, any> = {
"and": v.conditions.LogicCondition,
"or": v.conditions.LogicCondition,
"not": v.conditions.LogicCondition,
"numeric_state": v.conditions.NumericCondition,
"state": v.conditions.StateCondition,
"template": v.conditions.TemplateCondition,
"time": v.conditions.TimeCondition,
"trigger": v.conditions.TriggerCondition,
"zone": v.conditions.ZoneCondition,
}
and: v.conditions.LogicCondition,
or: v.conditions.LogicCondition,
not: v.conditions.LogicCondition,
numeric_state: v.conditions.NumericCondition,
state: v.conditions.StateCondition,
template: v.conditions.TemplateCondition,
time: v.conditions.TimeCondition,
trigger: v.conditions.TriggerCondition,
zone: v.conditions.ZoneCondition,
};
const AllValidators: Record<AutomationNodeTypes, any> = {
"action": ActionValidators,
"condition": ConditionValidators,
"trigger": TriggerValidators,
}
action: ActionValidators,
condition: ConditionValidators,
trigger: TriggerValidators,
};
export const validateNode = (node: AutomationNode, allowedNodeTypes: AutomationNodeTypes[] = []): MiniFailure[] | null => {
let nodeType = getNodeType(node);
let errors: MiniFailure[] = []
if (allowedNodeTypes.length > 0 && !allowedNodeTypes.includes(nodeType)) {
errors.push(
{ "message": [`Got node of type "${nodeType}" but expected one of {${allowedNodeTypes}}`], path: "" }
)
nodeType = allowedNodeTypes[0]
export const validateNode = (
node: AutomationNode,
allowedNodeTypes: AutomationNodeTypes[] = []
): MiniFailure[] | null => {
let nodeType = getNodeType(node);
let errors: MiniFailure[] = [];
if (allowedNodeTypes.length > 0 && !allowedNodeTypes.includes(nodeType)) {
errors.push({
message: [
`Got node of type "${nodeType}" but expected one of {${allowedNodeTypes}}`,
],
path: "",
});
nodeType = allowedNodeTypes[0];
}
let nodeSubType: null | AutomationNodeSubtype = null;
try {
nodeSubType = getNodeSubType(node);
} catch (err) {
errors.push({ message: [`Failed to identifiy subtype`], path: "" });
}
if (nodeSubType) {
const failures = getFailures(node, AllValidators[nodeType][nodeSubType]);
if (failures) {
errors = errors.concat(failures);
}
let nodeSubType: null | AutomationNodeSubtype = null;
try {
nodeSubType = getNodeSubType(node);
}
if (errors.length > 0) {
return errors;
} else {
return null;
}
};
} catch (err) {
errors.push(
{ "message": [`Failed to identifiy subtype`], path: "" }
)
export const getEntityDomains = (entityIds: string | string[]): string[] => {
if (typeof entityIds === "string") {
return [entityIds.toLowerCase().split(".")[0] ?? ""];
} else {
const all = new Set<string>();
entityIds.forEach((eid) =>
getEntityDomains(eid).forEach((domain) => all.add(domain))
);
return Array.from(all.keys());
}
};
export const binaryStateDomains = [
"binary_sensor",
"switch",
"light",
"automation",
"input_boolean",
"script",
];
export const entityDomainsAreBinary = (domains: string[]): boolean => {
if (domains.length === 1) {
return binaryStateDomains.includes(domains[0]);
} else {
for (const domain of domains) {
if (!entityDomainsAreBinary([domain])) {
return false;
}
}
if (nodeSubType) {
const failures = getFailures(node, AllValidators[nodeType][nodeSubType]);
if (failures) {
errors = errors.concat(failures)
}
}
if (errors.length > 0) {
return errors
} else {
return null
}
}
return true;
}
};