diff --git a/webapp/src/components/DeviceEditor/index.tsx b/webapp/src/components/DeviceEditor/index.tsx new file mode 100644 index 0000000..36b932b --- /dev/null +++ b/webapp/src/components/DeviceEditor/index.tsx @@ -0,0 +1,96 @@ +import { + BaseOption, + InputAutoComplete, +} from "components/Inputs/InputAutoComplete"; +import { InputDevice } from "components/Inputs/InputDevice"; +import { InputEntity } from "components/Inputs/InputEntities"; +import InputText from "components/Inputs/InputText"; +import { cleanUpUndefined } from "components/NodeEditor/OptionManager/OptionManager"; +import { DeviceBaseType, DeviceTypeCapability } from "haService/types"; +import { AutomationDeviceState } from "types/automations/common"; +import { prettyName } from "utils/formatting"; + +export type DeviceEditorProps = { + type: "action" | "condition" | "trigger"; + state: Partial; + setState: (n: Partial>) => void; + options: Record>; + caps: Partial; +}; +export function DeviceEditor({ + type, + state, + setState, + caps, + options, +}: DeviceEditorProps) { + // aliases + const update = (upd: Partial>) => + setState( + cleanUpUndefined({ + ...state, + ...upd, + }) + ); + const actionId = (state.type ?? "") + (state.subtype ?? ""); + const entities = ((options[actionId] ?? {}).data ?? []) + .map(({ entity_id }) => entity_id) + .filter((x) => !!x) as string[]; + // render + return ( + <> + setState({ device_id: device_id ?? "" })} + /> + options[k])} + disabled={Object.keys(options).length === 0} + onChange={(key) => { + if (key) { + const opt = options[key].data[0]; + const updateObj: any = { ...opt }; + delete updateObj["metadata"]; + setState(updateObj); + } else { + setState({ + device_id: state.device_id, + }); + } + }} + /> + {entities.length > 0 && ( + + update({ entity_id: entity_id ?? undefined }) + } + preSelectedEntityIds={entities} + /> + )} + {caps?.extra_fields && + caps.extra_fields.map((field) => ( + + update({ + [field.name]: v, + }) + } + /> + ))} + {Object.keys(options).length + entities.length === 0 && ( + <>This device has no {type}s. + )} + + ); +} diff --git a/webapp/src/components/Inputs/InputDeviceCapabilties.tsx b/webapp/src/components/Inputs/InputDeviceCapabilties.tsx new file mode 100644 index 0000000..fdcd54e --- /dev/null +++ b/webapp/src/components/Inputs/InputDeviceCapabilties.tsx @@ -0,0 +1,5 @@ +import { FC } from "react"; + +export const InputDeviceCapabilties: FC<{}> = () => { + return <>; +}; diff --git a/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx b/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx index ee007e6..e0e3766 100644 --- a/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx @@ -1,11 +1,6 @@ -import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; -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 { DeviceEditor } from "components/DeviceEditor"; import { DeviceAction } from "types/automations/actions"; -import { prettyName } from "utils/formatting"; -import { OptionManager, updateActionData } from "./OptionManager"; +import { OptionManager } from "./OptionManager"; export const ActionDeviceState: OptionManager = { defaultState: () => ({ alias: "", @@ -13,7 +8,6 @@ export const ActionDeviceState: OptionManager = { }), isReady: () => true, Component: ({ state, setState, ha }) => { - const update = updateActionData(state, setState); const options = ha.deviceExtras.useDeviceActions( state.device_id ? { @@ -24,67 +18,14 @@ export const ActionDeviceState: OptionManager = { const caps = ha.deviceExtras.useDeviceCapalities( state.device_id && state.type && state.domain ? (state as any) : undefined ); - // aliases - const actionId = (state.type ?? "") + (state.subtype ?? ""); - const entities = ((options[actionId] ?? {}).data ?? []) - .map(({ entity_id }) => entity_id) - .filter((x) => !!x) as string[]; - // render return ( - <> - setState({ device_id: device_id ?? "" })} - /> - options[k])} - disabled={Object.keys(options).length === 0} - onChange={(key) => { - if (key) { - const opt = options[key].data[0]; - const updateObj: any = { ...opt }; - delete updateObj["metadata"]; - setState(updateObj); - } else { - setState({ - device_id: state.device_id, - }); - } - }} - /> - {entities.length > 0 && ( - - update({ entity_id: entity_id ?? undefined }) - } - preSelectedEntityIds={entities} - /> - )} - {caps?.extra_fields && - caps.extra_fields.map((field) => ( - - update({ - [field.name]: v, - }) - } - /> - ))} - {Object.keys(options).length + entities.length === 0 && ( - <>This device has no actions. - )} - + ); }, }; diff --git a/webapp/src/components/NodeEditor/OptionManager/TriggerDevice.tsx b/webapp/src/components/NodeEditor/OptionManager/TriggerDevice.tsx index ebde520..4efb612 100644 --- a/webapp/src/components/NodeEditor/OptionManager/TriggerDevice.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/TriggerDevice.tsx @@ -1,16 +1,6 @@ import { OptionManager } from "./OptionManager"; import { AutomationTriggerDevice } from "types/automations/triggers"; -import InputText from "components/Inputs/InputText"; -import { InputEntity } from "components/Inputs/InputEntities"; -import InputTextBubble from "components/Inputs/InputTextBubble"; -import { InputDevice } from "components/Inputs/InputDevice"; -import InputAutoText from "components/Inputs/InputAutoText"; -import { - BaseOption, - InputAutoComplete, -} from "components/Inputs/InputAutoComplete"; -import { prettyName } from "utils/formatting"; -import { DeviceTypeTrigger } from "haService/extras"; +import { DeviceEditor } from "components/DeviceEditor"; export const TriggerDevice: OptionManager = { defaultState: () => ({ @@ -18,61 +8,31 @@ export const TriggerDevice: OptionManager = { }), isReady: () => true, Component: ({ state, setState, ha }) => { - const triggers: Record< - string, - BaseOption<{ - data: DeviceTypeTrigger; - }> - > = ha.deviceExtras - .useDeviceTriggers( - state.device_id - ? { - deviceId: state.device_id, - } - : undefined - ) - .reduce( - (all, opt) => ({ - ...all, - [opt.type + (opt.subtype ?? "")]: { - id: opt.type + (opt.subtype ?? ""), - label: - prettyName(opt.type) + (opt.subtype ? ` ${opt.subtype}` : ""), - data: opt, - }, - }), - {} - ); - return ( - <> - - setState({ device_id: device_id ?? "", platform: "device" }) + // state + const triggers = ha.deviceExtras.useDeviceTriggers( + state.device_id + ? { + deviceId: state.device_id, } - /> - triggers[k])} - disabled={Object.keys(triggers).length === 0} - onChange={(key) => { - if (key) { - const opt = triggers[key]; - const updateObj: any = { ...opt.data }; - delete updateObj["metadata"]; - setState(updateObj); - } else { - setState({ - device_id: state.device_id, - platform: state.platform, - }); - } - }} - /> - + : undefined + ); + const caps = ha.deviceExtras.useDeviceTriggerCapalities( + state.device_id && state.type && state.domain ? (state as any) : undefined + ); + + return ( + + setState({ + platform: "device", + ...s, + }) + } + options={triggers} + caps={caps} + /> ); }, }; diff --git a/webapp/src/components/NodeEditor/index.stories.tsx b/webapp/src/components/NodeEditor/index.stories.tsx index dc080d1..f4dc3d0 100644 --- a/webapp/src/components/NodeEditor/index.stories.tsx +++ b/webapp/src/components/NodeEditor/index.stories.tsx @@ -68,6 +68,7 @@ DeviceTriggerExample.args = { ...DeviceTriggerExample.args, node: { platform: "device", + device_id: "bd83b10cb1c7aa028c12dade5b4e87d5", }, }; diff --git a/webapp/src/haService/extras.ts b/webapp/src/haService/extras.ts index 3292af1..582b4a8 100644 --- a/webapp/src/haService/extras.ts +++ b/webapp/src/haService/extras.ts @@ -2,33 +2,13 @@ import { BaseOption } from "components/Inputs/InputAutoComplete"; import { MessageBase } from "home-assistant-js-websocket"; import { useEffect, useRef, useState } from "react"; import { prettyName } from "utils/formatting"; -import { HASendMessage } from "./types"; +import { + DeviceTriggerType, + DeviceTypeAction, + DeviceTypeCapability, + HASendMessage, +} from "./types"; -export type DeviceTypeAction = { - type: string; - subtype?: string; - entity_id?: string; - device_id?: string; - domain: string; -}; -export type DeviceTypeTrigger = { - type: string; - subtype?: string; - platform: string; - device_id: string; - entity_id?: string; - domain: string; - metadata: Record; -} & Record; - -export type DeviceTypeCapability = { - extra_fields: Array<{ - name: string; - required?: true; - optional?: true; - type: string; - }>; -}; export const getDeviceExtraWsCalls = (callHA: HASendMessage) => { const createUseThing = function ( convertArgsToMessage: (a: Args) => MessageBase, @@ -110,17 +90,29 @@ export const getDeviceExtraWsCalls = (callHA: HASendMessage) => { (data) => data, {} ), + useDeviceTriggerCapalities: createUseThing< + DeviceTypeAction, + DeviceTypeCapability, + Partial + >( + (trigger) => ({ + type: "device_automation/trigger/capabilities", + trigger, + }), + (data) => data, + {} + ), useDeviceTriggers: createUseThing< { deviceId: string }, - DeviceTypeTrigger[], - DeviceTypeTrigger[] + DeviceTriggerType[], + Record> >( ({ deviceId }) => ({ type: "device_automation/trigger/list", device_id: deviceId, }), - (data) => data, - [] + reduceDeviceThings, + {} ), }; }; diff --git a/webapp/src/haService/types.ts b/webapp/src/haService/types.ts index 199b22b..47d933e 100644 --- a/webapp/src/haService/types.ts +++ b/webapp/src/haService/types.ts @@ -1,4 +1,5 @@ import { MessageBase } from "home-assistant-js-websocket"; +import { AutomationDeviceState } from "types/automations/common"; export type EntityRegisteryItem = { area_id: null | string; @@ -26,3 +27,18 @@ export type DeviceRegistryItem = { export type HassDevices = Array; export type HassEntitiesRegistry = Array; export type HASendMessage = (sendMsg: MessageBase) => Promise; + +export type DeviceBaseType = AutomationDeviceState & { + metadata: Record; +} & Record; +export type DeviceTypeAction = DeviceBaseType; +export type DeviceTriggerType = DeviceBaseType & { + platform: string; +}; +export type DeviceTypeCapability = { + extra_fields: Array<{ + name: string; + required?: true; + type: string; + }>; +}; diff --git a/webapp/src/types/automations/common.ts b/webapp/src/types/automations/common.ts index b7a5352..cd972cd 100644 --- a/webapp/src/types/automations/common.ts +++ b/webapp/src/types/automations/common.ts @@ -1,7 +1,8 @@ -import * as st from 'superstruct' +import * as st from "superstruct"; import * as v from "types/validators/common"; -export type AutomationTime = st.Infer -export type AutomationTimeObject = st.Infer -export type AutomationTimeString = st.Infer -export type EntityId = st.Infer; \ No newline at end of file +export type AutomationTime = st.Infer; +export type AutomationTimeObject = st.Infer; +export type AutomationTimeString = st.Infer; +export type EntityId = st.Infer; +export type AutomationDeviceState = st.Infer; diff --git a/webapp/src/types/validators/actions.ts b/webapp/src/types/validators/actions.ts index 747dbbf..2a11f19 100644 --- a/webapp/src/types/validators/actions.ts +++ b/webapp/src/types/validators/actions.ts @@ -1,5 +1,5 @@ import * as st from "superstruct"; -import { AutomationTime } from "./common"; +import { AutomationDeviceState, AutomationTime } from "./common"; import { AutomationTrigger } from "./triggers"; export const AutomationActionNodeBase = st.type({ @@ -54,13 +54,7 @@ export const FireEventAction = st.intersection([ export const DeviceAction = st.intersection([ AutomationActionNodeBase, - st.type({ - type: st.optional(st.string()), - subtype: st.optional(st.string()), - device_id: st.optional(st.string()), - entity_id: st.optional(st.string()), - domain: st.optional(st.string()), - }), + st.partial(AutomationDeviceState), ]); export const ChooseAction = st.intersection([ diff --git a/webapp/src/types/validators/common.ts b/webapp/src/types/validators/common.ts index 7270bdc..e99e7fe 100644 --- a/webapp/src/types/validators/common.ts +++ b/webapp/src/types/validators/common.ts @@ -1,52 +1,57 @@ -import * as st from 'superstruct' +import * as st from "superstruct"; -export const EntityId = st.union([ - st.string(), - st.array(st.string()), -]) -export const AutomationTimeString = st.refine(st.string(), 'TimeString', (v, c) => { +export const EntityId = st.union([st.string(), st.array(st.string())]); +export const AutomationTimeString = st.refine( + st.string(), + "TimeString", + (v, c) => { // https://www.home-assistant.io/docs/automation/trigger/#time-string - const bits: string[] = v.split(':') - if ((bits.length !== 2) && (bits.length !== 3)) { - return { - "branch": c.branch, - "message": "Time string should be either in the form 'HH:MM' or 'HH:MM:SS' as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string", - "path": c.path, - } + const bits: string[] = v.split(":"); + if (bits.length !== 2 && bits.length !== 3) { + return { + branch: c.branch, + message: + "Time string should be either in the form 'HH:MM' or 'HH:MM:SS' as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string", + path: c.path, + }; } for (let i = 0; i < bits.length; i++) { - const b = bits[i]; - const num = Number(b); - if (Number.isInteger(num)) { - let max = 23; - if (i > 0) { - max = 59; - } - if ((num < 0) || (num > max)) { - return { - "branch": c.branch, - "message": `Time string should contain only positive numbers between 0-${max} as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`, - "path": c.path.concat( - bits.slice(0, i) - ).concat([`<<${b}>>`]) - } - } - } else { - return { - "branch": c.branch, - "message": `Time string should contain only positive numbers as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`, - "path": c.path.concat( - bits.slice(0, i) - ).concat([`<<${b}>>`]) - } + const b = bits[i]; + const num = Number(b); + if (Number.isInteger(num)) { + let max = 23; + if (i > 0) { + max = 59; } + if (num < 0 || num > max) { + return { + branch: c.branch, + message: `Time string should contain only positive numbers between 0-${max} as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`, + path: c.path.concat(bits.slice(0, i)).concat([`<<${b}>>`]), + }; + } + } else { + return { + branch: c.branch, + message: `Time string should contain only positive numbers as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`, + path: c.path.concat(bits.slice(0, i)).concat([`<<${b}>>`]), + }; + } } - return true -}) + return true; + } +); export const AutomationTimeObject = st.object({ - hours: st.optional(st.number()), - minutes: st.optional(st.number()), - seconds: st.optional(st.number()), - milliseconds: st.optional(st.number()), + hours: st.optional(st.number()), + minutes: st.optional(st.number()), + seconds: st.optional(st.number()), + milliseconds: st.optional(st.number()), +}); +export const AutomationTime = st.union([st.string(), AutomationTimeObject]); +export const AutomationDeviceState = st.type({ + subtype: st.optional(st.string()), + entity_id: st.optional(st.string()), + type: st.string(), + device_id: st.string(), + domain: st.string(), }); -export const AutomationTime = st.union([st.string(), AutomationTimeObject]) diff --git a/webapp/src/types/validators/triggers.ts b/webapp/src/types/validators/triggers.ts index cfa0f3b..64f3dff 100644 --- a/webapp/src/types/validators/triggers.ts +++ b/webapp/src/types/validators/triggers.ts @@ -1,119 +1,119 @@ -import * as st from 'superstruct' -import { AutomationTimeString, AutomationTime, EntityId } from './common' - +import * as st from "superstruct"; +import { + AutomationTimeString, + AutomationTime, + AutomationDeviceState, +} from "./common"; const AutomationTriggerBase = { - id: st.optional(st.string()), - enabled: st.optional(st.boolean()), -} + id: st.optional(st.string()), + enabled: st.optional(st.boolean()), +}; export const AutomationTriggerEvent = st.type({ - ...AutomationTriggerBase, - platform: st.literal('event'), - event_type: st.union([st.string(), st.array(st.string())]), - event_data: st.any(), - context: st.any(), -}) + ...AutomationTriggerBase, + platform: st.literal("event"), + event_type: st.union([st.string(), st.array(st.string())]), + event_data: st.any(), + context: st.any(), +}); export const AutomationTriggerHA = st.type({ - ...AutomationTriggerBase, - platform: st.literal('homeassistant'), - event: st.enums(['start', 'shutdown']), -}) + ...AutomationTriggerBase, + platform: st.literal("homeassistant"), + event: st.enums(["start", "shutdown"]), +}); export const AutomationTriggerMQTT = st.type({ - ...AutomationTriggerBase, - platform: st.literal('mqtt'), - topic: st.string(), - payload: st.string(), - value_template: st.string(), -}) + ...AutomationTriggerBase, + platform: st.literal("mqtt"), + topic: st.string(), + payload: st.string(), + value_template: st.string(), +}); export const AutomationTriggerNumericState = st.type({ - ...AutomationTriggerBase, - platform: st.literal('numeric_state'), - entity_id: st.union([st.string(), st.array(st.string())]), - attribute: st.optional(st.string()), - value_template: st.optional(st.string()), - above: st.optional(st.string()), - below: st.optional(st.string()), - for: st.optional(AutomationTime), -}) + ...AutomationTriggerBase, + platform: st.literal("numeric_state"), + entity_id: st.union([st.string(), st.array(st.string())]), + attribute: st.optional(st.string()), + value_template: st.optional(st.string()), + above: st.optional(st.string()), + below: st.optional(st.string()), + for: st.optional(AutomationTime), +}); export const AutomationTriggerState = st.type({ - ...AutomationTriggerBase, - platform: st.literal('state'), - entity_id: st.union([st.string(), st.array(st.string())]), - attribute: st.optional(st.string()), - from: st.optional(st.string()), - to: st.optional(st.string()), - for: st.optional(AutomationTime), -}) + ...AutomationTriggerBase, + platform: st.literal("state"), + entity_id: st.union([st.string(), st.array(st.string())]), + attribute: st.optional(st.string()), + from: st.optional(st.string()), + to: st.optional(st.string()), + for: st.optional(AutomationTime), +}); export const AutomationTriggerTag = st.type({ - ...AutomationTriggerBase, - platform: st.literal('tag'), - tag_id: st.string(), - device_id: st.union([st.string(), st.array(st.string())]), -}) + ...AutomationTriggerBase, + platform: st.literal("tag"), + tag_id: st.string(), + device_id: st.union([st.string(), st.array(st.string())]), +}); export const AutomationTriggerTemplate = st.type({ - ...AutomationTriggerBase, - platform: st.literal('template'), - value_template: st.string(), - for: st.optional(AutomationTime), -}) + ...AutomationTriggerBase, + platform: st.literal("template"), + value_template: st.string(), + for: st.optional(AutomationTime), +}); export const AutomationTriggerTime = st.type({ - ...AutomationTriggerBase, - platform: st.literal('time'), - at: AutomationTimeString, -}) + ...AutomationTriggerBase, + platform: st.literal("time"), + at: AutomationTimeString, +}); export const AutomationTriggerTimePattern = st.type({ - ...AutomationTriggerBase, - platform: st.literal('time_pattern'), - hours: st.optional(st.string()), - minutes: st.optional(st.string()), - seconds: st.optional(st.string()), -}) + ...AutomationTriggerBase, + platform: st.literal("time_pattern"), + hours: st.optional(st.string()), + minutes: st.optional(st.string()), + seconds: st.optional(st.string()), +}); export const AutomationTriggerWebhook = st.type({ - ...AutomationTriggerBase, - platform: st.literal('webhook'), - webhook_id: st.string(), -}) + ...AutomationTriggerBase, + platform: st.literal("webhook"), + webhook_id: st.string(), +}); export const AutomationTriggerZone = st.type({ - ...AutomationTriggerBase, - platform: st.literal('zone'), - entity_id: st.union([st.string(), st.array(st.string())]), - zone: st.string(), - event: st.enums(['enter', 'leave']) -}) + ...AutomationTriggerBase, + platform: st.literal("zone"), + entity_id: st.union([st.string(), st.array(st.string())]), + zone: st.string(), + event: st.enums(["enter", "leave"]), +}); -export const AutomationTriggerDevice = st.type({ +export const AutomationTriggerDevice = st.assign( + st.partial(AutomationDeviceState), + st.type({ ...AutomationTriggerBase, - platform: st.literal('device'), - entity_id: st.optional(EntityId), - device_id: st.optional(st.string()), - domain: st.optional(st.string()), - type: st.optional(st.string()), - subtype: st.optional(st.string()), -}) - + platform: st.literal("device"), + }) +); export const AutomationTrigger = st.union([ - AutomationTriggerEvent, - AutomationTriggerHA, - AutomationTriggerMQTT, - AutomationTriggerNumericState, - AutomationTriggerState, - AutomationTriggerTag, - AutomationTriggerTemplate, - AutomationTriggerTime, - AutomationTriggerTimePattern, - AutomationTriggerWebhook, - AutomationTriggerZone, - AutomationTriggerDevice -]) \ No newline at end of file + AutomationTriggerEvent, + AutomationTriggerHA, + AutomationTriggerMQTT, + AutomationTriggerNumericState, + AutomationTriggerState, + AutomationTriggerTag, + AutomationTriggerTemplate, + AutomationTriggerTime, + AutomationTriggerTimePattern, + AutomationTriggerWebhook, + AutomationTriggerZone, + AutomationTriggerDevice, +]);