device action builder

This commit is contained in:
ari committed 2022-06-17 13:37:25 -04:00
1 parent 6be6005531
commit 029df7932e
16 files changed
+725 -434

No files matched your search

@@ -11,3 +11,13 @@ test("similarity score", () => {
].map((x) => computeSimilarity(x, "light.balcony", "Balcony Light"));
expect(searchTerms).toStrictEqual(searchTerms.sort());
});
test("similarity score", () => {
expect(
computeSimilarity(
"li",
"6592b3d6d05d3de6fa26c3dbd2edecc2",
"Balcony Lights"
)
).toBeGreaterThan(0);
});
@@ -51,7 +51,7 @@ export function computeSimilarity(
if (lowCaseId.includes(segment)) {
similarityScore += lowCaseId.length / lowCaseId.length;
}
if (lowCaseId.includes(segment)) {
if (lowCaseLabel.includes(segment)) {
similarityScore += lowCaseLabel.length / lowCaseLabel.length;
}
}
+42 -16
View File
@@ -1,22 +1,48 @@
import { FC } from "react";
import { useHAEntities } from 'haService';
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete';
import { useHAEntities } from "haService";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { prettyName } from "utils/formatting";
export type InputEntityProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[],
}
restrictToDomain?: string[];
preSelectedEntityIds?: string[];
};
export const InputEntity: FC<InputEntityProps> = props => {
// state
const entities = useHAEntities();
return <InputAutoComplete
{...props}
validateOption={v => entities.validateOptions(v, props.restrictToDomain)}
options={entities.getOptions(props.restrictToDomain)}
getID={entities.getID}
getLabel={entities.getLabel}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''}
export const InputEntity: FC<InputEntityProps> = (props) => {
// state
const entities = useHAEntities();
let options = entities.getOptions(props.restrictToDomain);
if (props.preSelectedEntityIds) {
options = options.filter((opt) =>
props.preSelectedEntityIds?.includes(entities.getID(opt))
);
}
const validateOptions = (v: string[]): null | string[] => {
const errors: string[] = [];
if (props.preSelectedEntityIds) {
v.forEach((eid) => {
if (!props.preSelectedEntityIds?.includes(eid)) {
errors.push(`"${eid}" is not a valid selection`);
}
});
}
errors.concat(entities.validateOptions(v, props.restrictToDomain) ?? []);
if (errors.length > 0) {
return errors;
}
return null;
};
return (
<InputAutoComplete
{...props}
validateOption={validateOptions}
options={options}
getID={entities.getID}
getLabel={entities.getLabel}
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
/>
}
);
};
@@ -19,6 +19,7 @@ export type Props<T extends string | Object> = {
title?: string;
helperText?: string;
endAdornment?: ReactNode;
disabled?: boolean;
};
export function InputList<T extends string | Object>({
current,
@@ -33,6 +34,7 @@ export function InputList<T extends string | Object>({
title,
helperText,
endAdornment,
disabled,
}: Props<T>) {
const invalidCurrent =
current && !options.map(getKey).includes(getKey(current));
@@ -42,6 +44,7 @@ export function InputList<T extends string | Object>({
variant="filled"
sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}
fullWidth
disabled={disabled}
>
<InputLabel>{label}</InputLabel>
<Select
@@ -60,6 +63,7 @@ export function InputList<T extends string | Object>({
variant="filled"
error={invalidCurrent}
fullWidth
disabled={disabled}
>
{options.map((t, i) => (
<MenuItem key={i} value={getKey(t)}>
@@ -1,36 +1,83 @@
import { InputDevice } from "components/Inputs/InputDevice";
import { InputEntity } from "components/Inputs/InputEntities";
import { InputList } from "components/Inputs/InputList";
import InputText from "components/Inputs/InputText";
import { DeviceAction } from "types/automations/actions";
import { OptionManager, updateActionData } from './OptionManager';
import { prettyName } from "utils/formatting";
import { OptionManager, updateActionData } from "./OptionManager";
export const ActionDeviceState: OptionManager<DeviceAction> = {
defaultState: () => ({
alias: "",
device_id: ""
device_id: "",
}),
isReady: () => true,
renderOptionList: (state, setState, entities) => {
Component: ({ state, setState, ha }) => {
const update = updateActionData(state, setState);
return <>
<InputDevice
value={state.device_id ?? ""}
onChange={device_id => update({ device_id: device_id ?? "" })}
/>
<InputText
textBoxFor="type"
label="Action"
value={state.type ?? ""}
onChange={type => update({ type })}
/>
<InputEntity
value={state.entity_id ?? ""}
onChange={entity_id => update({
entity_id: entity_id ? entity_id : undefined,
domain: entity_id ? entity_id.split('.')[0] : ""
})}
/>
</>
}
}
const options = ha.deviceExtras.useDeviceActions(state.device_id);
const caps = ha.deviceExtras.useDeviceCapalities(state as any);
// aliases
let actions: DeviceAction[] = [];
if (options.length > 0 && state.type) {
const currentTypeOptions = options.filter(
({ type }) => type === state.type
);
if (currentTypeOptions.length > 0) {
actions = currentTypeOptions[0].actions;
}
}
const entities = actions
.map(({ entity_id }) => entity_id)
.filter((x) => !!x) as string[];
// render
return (
<>
<InputDevice
value={state.device_id ?? ""}
onChange={(device_id) => update({ device_id: device_id ?? "" })}
/>
{options.length > 0 && (
<InputList
key={"actions" + state.device_id}
label="Action"
current={state.type}
onChange={(type) =>
setState({
device_id: state.device_id,
...options.filter((opt) => type === opt.type)[0].actions[0],
})
}
options={options.map(({ type }) => type)}
/>
)}
{entities.length > 0 && (
<InputEntity
key={"entities" + state.device_id}
label="Entity"
value={state.entity_id ?? ""}
multiple={false}
onChange={(entity_id) =>
update({ entity_id: entity_id ?? undefined })
}
preSelectedEntityIds={entities}
/>
)}
{caps?.extra_fields &&
caps.extra_fields.map((field) => (
<InputText
key={"extra" + state.device_id + field.name}
label={prettyName(field.name)}
value={state[field.name] ?? ""}
onChange={(v) =>
update({
[field.name]: v,
})
}
/>
))}
{actions.length + options.length === 0 && (
<>This device has no actions.</>
)}
</>
);
},
};
@@ -10,7 +10,7 @@ export const ActionCallServiceState: OptionManager<ServiceAction> = {
data: {},
}),
isReady: ({ service }) => service !== "",
Component: ({ state, setState, services }) => {
Component: ({ state, setState, ha: { services } }) => {
const { service, target, data } = state;
const update = updateActionData(state, setState);
const serviceOption = services.getOption(service);
@@ -1,47 +1,53 @@
import { HAEntitiesState, HAServicesState } from 'haService';
import { FC } from 'react';
import { AutomationAction } from 'types/automations/actions';
import { AutomationCondition } from 'types/automations/conditions';
import { HAEntitiesState, HAService } from "haService";
import { FC } from "react";
import { AutomationAction } from "types/automations/actions";
import { AutomationCondition } from "types/automations/conditions";
export type OptionManager<T> = {
defaultState(): T;
isReady(s: T): boolean;
} & ({
renderOptionList(s: T, set: (s: T) => void, entities: HAEntitiesState): JSX.Element;
} | {
Component: FC<{
state: T,
setState: (s: T) => void,
entities: HAEntitiesState,
services: HAServicesState,
}>
})
} & (
| {
renderOptionList(
s: T,
set: (s: T) => void,
entities: HAEntitiesState
): JSX.Element;
}
| {
Component: FC<{
state: T;
setState: (s: T) => void;
ha: HAService;
}>;
}
);
export const cleanUpUndefined = (data: Record<string, any>): any => {
const clean: any = {};
Object.keys(data).forEach(k => {
if ((data[k] !== undefined) && (data[k] !== null)) {
clean[k] = data[k]
Object.keys(data).forEach((k) => {
if (data[k] !== undefined && data[k] !== null) {
clean[k] = data[k];
}
})
});
return clean;
}
};
export const updateConditionData = <T extends AutomationCondition>(
setState: (s: T) => void
) => (
state: T,
data: Partial<T>,
) => setState(cleanUpUndefined({
...state,
...data,
}))
export const updateConditionData =
<T extends AutomationCondition>(setState: (s: T) => void) =>
(state: T, data: Partial<T>) =>
setState(
cleanUpUndefined({
...state,
...data,
})
);
export const updateActionData = <T extends AutomationAction>(
state: T,
setState: (s: T) => void
) => (
data: Partial<T>,
) => setState(cleanUpUndefined({
...state,
...data,
}))
export const updateActionData =
<T extends AutomationAction>(state: T, setState: (s: T) => void) =>
(data: Partial<T>) =>
setState(
cleanUpUndefined({
...state,
...data,
})
);
@@ -15,7 +15,7 @@ export const TriggerState: OptionManager<AutomationTriggerState> = {
entity_id: "",
}),
isReady: () => true,
Component: ({ state, setState, entities }) => {
Component: ({ state, setState, ha: { entities } }) => {
const attributes = entities.getAttributes(state.entity_id);
const states = entities.getStates(state.entity_id, state.attribute);
return (
@@ -28,7 +28,7 @@ export const useEditorNodeState = (
isModified: false,
...computeInvalidYaml(originalNode, allowedTypes),
});
const { entities, namer, services } = useHA();
const ha = useHA();
// aliases
const {
node: currentNode,
@@ -115,7 +115,7 @@ export const useEditorNodeState = (
<InputText
key="alias"
label="Alias"
value={getDescriptionFromAutomationNode(allState.node, namer)}
value={getDescriptionFromAutomationNode(allState.node, ha.namer)}
onChange={(alias) =>
setState({
...allState.node,
@@ -142,13 +142,12 @@ export const useEditorNodeState = (
<>
{aliasEditor}
{"renderOptionList" in optionManager ? (
optionManager.renderOptionList(currentNode, setState, entities)
optionManager.renderOptionList(currentNode, setState, ha.entities)
) : (
<optionManager.Component
state={currentNode}
setState={setState}
entities={entities}
services={services}
ha={ha}
/>
)}
</>
@@ -123,3 +123,14 @@ StateTriggerExample.args = {
entity_id: "binary_sensor.door_main",
},
};
export const DeviceFilledExample = Action.bind({});
DeviceFilledExample.args = {
...DeviceFilledExample.args,
node: {
type: "toggle",
device_id: "29c3443815620745c4bf4100b11588fd",
entity_id: "light.switch_island",
domain: "light",
},
};