diff --git a/webapp/src/components/DeviceEditor/index.tsx b/webapp/src/components/DeviceEditor/index.tsx index af8e0ac..24c45fd 100644 --- a/webapp/src/components/DeviceEditor/index.tsx +++ b/webapp/src/components/DeviceEditor/index.tsx @@ -5,11 +5,9 @@ import { import { InputDevice } from "components/Inputs/InputDevice"; import { InputDeviceCapabilties } from "components/Inputs/InputDeviceCapabilties"; 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"; diff --git a/webapp/src/components/Inputs/InputDayTime.tsx b/webapp/src/components/Inputs/InputDayTime.tsx index c4e1e9c..6e995a9 100644 --- a/webapp/src/components/Inputs/InputDayTime.tsx +++ b/webapp/src/components/Inputs/InputDayTime.tsx @@ -1,98 +1,98 @@ import "./InputTime.css"; import { useState, useEffect, FC } from "react"; -import TextField from '@mui/material/TextField'; -import EditIcon from '@mui/icons-material/Edit'; +import TextField from "@mui/material/TextField"; +import EditIcon from "@mui/icons-material/Edit"; import CloseIcon from "@mui/icons-material/Close"; -import IconButton from "@mui/material/IconButton" +import IconButton from "@mui/material/IconButton"; import { AutomationTime, AutomationTimeObject } from "types/automations/common"; -import { convertAutomationTimeToTimeObject, convertObjectToAutomationTimeString, milisecondsToObject } from "utils/time"; -import { convertStringToAutomationTimeObject, convertAutomationTimeToTimeString } from 'utils/time'; +import { + convertAutomationTimeToTimeObject, + convertObjectToAutomationTimeString, +} from "utils/time"; +import { convertAutomationTimeToTimeString } from "utils/time"; import { prettyName } from "utils/formatting"; -import FormControl from "@mui/material/FormControl"; -import InputLabel from '@mui/material/InputLabel'; -import Input from "@mui/material/Input"; -import FormHelperText from '@mui/material/FormHelperText'; +import InputLabel from "@mui/material/InputLabel"; // constants const fields: Array = [ - 'hours', - 'minutes', - 'seconds', - 'milliseconds' -] + "hours", + "minutes", + "seconds", + "milliseconds", +]; export interface Props { label: string; value?: AutomationTime; onChange: (v?: AutomationTimeObject) => void; } export const InputTime: FC = (props) => { - - // state - const [disabled, setDisabled] = useState(!props.value) - const [displayValue, setDisplayValue] = useState(convertAutomationTimeToTimeObject(props.value)) + const [disabled, setDisabled] = useState(!props.value); + const [displayValue, setDisplayValue] = useState( + convertAutomationTimeToTimeObject(props.value) + ); // process display input const updateOne = (k: keyof AutomationTimeObject) => (v: string) => { if (Number(v) < 0) { setDisplayValue({ ...displayValue, - [k]: 0 - }) + [k]: 0, + }); } else if (k === "hours") { setDisplayValue({ ...displayValue, - [k]: Number(v) - }) + [k]: Number(v), + }); } else if (k === "minutes") { let minutes = Number(v); - let { hours = 0 } = displayValue + let { hours = 0 } = displayValue; if (minutes > 59) { - const additonalHours = Math.floor(minutes / 60) - hours += additonalHours - minutes = minutes - additonalHours * 60 + const additonalHours = Math.floor(minutes / 60); + hours += additonalHours; + minutes = minutes - additonalHours * 60; } setDisplayValue({ ...displayValue, minutes, hours, - }) + }); } else if (k === "seconds") { let seconds = Number(v); - let { hours = 0, minutes = 0 } = displayValue + let { hours = 0, minutes = 0 } = displayValue; if (seconds > 59) { - const additonalHours = Math.floor(seconds / (60 * 60)) - hours += additonalHours - seconds = seconds - additonalHours * 60 + const additonalHours = Math.floor(seconds / (60 * 60)); + hours += additonalHours; + seconds = seconds - additonalHours * 60; } if (seconds > 59) { - const additionalMinutes = Math.floor(seconds / 60) - minutes += additionalMinutes - seconds = seconds - additionalMinutes * 60 + const additionalMinutes = Math.floor(seconds / 60); + minutes += additionalMinutes; + seconds = seconds - additionalMinutes * 60; } setDisplayValue({ ...displayValue, minutes, hours, seconds, - }) + }); } else if (k === "milliseconds") { let milliseconds = Number(v); - let { hours = 0, minutes = 0, seconds = 0 } = displayValue + let { hours = 0, minutes = 0, seconds = 0 } = displayValue; if (milliseconds > 1000) { - const additonalHours = Math.floor(milliseconds / (60 * 60 * 1000)) - hours += additonalHours - milliseconds = milliseconds - additonalHours * 60 * 60 * 1000 + const additonalHours = Math.floor(milliseconds / (60 * 60 * 1000)); + hours += additonalHours; + milliseconds = milliseconds - additonalHours * 60 * 60 * 1000; } if (milliseconds > 1000) { - const additionalMinutes = Math.floor(milliseconds / (60 * 1000)) - minutes += additionalMinutes - milliseconds = milliseconds - additionalMinutes * 60 * 1000 + const additionalMinutes = Math.floor(milliseconds / (60 * 1000)); + minutes += additionalMinutes; + milliseconds = milliseconds - additionalMinutes * 60 * 1000; } if (milliseconds > 1000) { - const additionalSeconds = Math.floor(milliseconds / 1000) - seconds += additionalSeconds - milliseconds = milliseconds - additionalSeconds * 1000 + const additionalSeconds = Math.floor(milliseconds / 1000); + seconds += additionalSeconds; + milliseconds = milliseconds - additionalSeconds * 1000; } setDisplayValue({ ...displayValue, @@ -100,49 +100,50 @@ export const InputTime: FC = (props) => { hours, seconds, milliseconds, - }) + }); } - } - + }; // effect useEffect(() => { if (disabled && !props.value) { - return + return; } if (disabled) { - props.onChange(undefined) + props.onChange(undefined); } else { const pVal = convertAutomationTimeToTimeString(props.value); const cVal = convertObjectToAutomationTimeString(displayValue); if (pVal !== cVal) { - props.onChange(displayValue) + props.onChange(displayValue); } } - }, [disabled, displayValue]) + // eslint-disable-next-line + }, [disabled, displayValue]); - - return
- {props.label} -
- {fields.map(name => - updateOne(name)(e.target.value)} - /> - )} - setDisabled(!disabled)}> - {disabled ? : } - + return ( +
+ {props.label} +
+ {fields.map((name) => ( + updateOne(name)(e.target.value)} + /> + ))} + setDisabled(!disabled)}> + {disabled ? : } + +
-
-} + ); +}; diff --git a/webapp/src/components/Inputs/InputEntities.tsx b/webapp/src/components/Inputs/InputEntities.tsx index 2c10060..903ddcf 100644 --- a/webapp/src/components/Inputs/InputEntities.tsx +++ b/webapp/src/components/Inputs/InputEntities.tsx @@ -1,5 +1,5 @@ import { FC } from "react"; -import { useHAEntities } from "haService"; +import { useHAEntities } from "haService/HAEntities"; import { InputAutoComplete, InputAutoCompletePropsBase, @@ -8,13 +8,17 @@ import { prettyName } from "utils/formatting"; export type InputEntityProps = InputAutoCompletePropsBase & { restrictToDomain?: string[]; + restrictedIntegrations?: string[]; preSelectedEntityIds?: string[]; }; export const InputEntity: FC = (props) => { // state const entities = useHAEntities(); - let options = entities.getOptions(props.restrictToDomain); + let options = entities.getOptions( + props.restrictToDomain, + props.restrictedIntegrations + ); if (props.preSelectedEntityIds) { options = options.filter((opt) => props.preSelectedEntityIds?.includes(entities.getID(opt)) @@ -29,7 +33,13 @@ export const InputEntity: FC = (props) => { } }); } - errors.concat(entities.validateOptions(v, props.restrictToDomain) ?? []); + errors.concat( + entities.validateOptions( + v, + props.restrictToDomain, + props.restrictedIntegrations + ) ?? [] + ); if (errors.length > 0) { return errors; } @@ -42,7 +52,11 @@ export const InputEntity: FC = (props) => { options={options} getID={entities.getID} getLabel={entities.getLabel} - groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")} + groupBy={(opt) => + typeof opt !== "string" + ? `${prettyName(opt.integration)}/ ${prettyName(opt.domain)}` + : "" + } /> ); }; diff --git a/webapp/src/components/Inputs/InputYaml.tsx b/webapp/src/components/Inputs/InputYaml.tsx index 3fd4883..efcb850 100644 --- a/webapp/src/components/Inputs/InputYaml.tsx +++ b/webapp/src/components/Inputs/InputYaml.tsx @@ -1,7 +1,6 @@ import "./InputYaml.css"; import * as yaml from "js-yaml"; import { useEffect, useState, ReactNode } from "react"; -import { useDelayEffect } from "utils/useDelay"; import CodeMirror from "@uiw/react-codemirror"; import FormControl from "@mui/material/FormControl"; diff --git a/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts b/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts index f6dd471..e964565 100644 --- a/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts +++ b/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts @@ -1,4 +1,5 @@ -import { HAEntitiesState, HAService } from "haService"; +import { HAService } from "haService"; +import { HAEntitiesState } from "haService/HAEntities"; import { FC } from "react"; import { AutomationAction } from "types/automations/actions"; import { AutomationCondition } from "types/automations/conditions"; diff --git a/webapp/src/components/ServiceEditor/ServiceEditorField.tsx b/webapp/src/components/ServiceEditor/ServiceEditorField.tsx index 59cfa80..00f9bd6 100644 --- a/webapp/src/components/ServiceEditor/ServiceEditorField.tsx +++ b/webapp/src/components/ServiceEditor/ServiceEditorField.tsx @@ -1,5 +1,5 @@ import "./ServiceEditorField.css"; -import { FC } from "react"; +import { FC, useRef } from "react"; import { ServiceEditorOption } from "./options"; import InputText from "components/Inputs/InputText"; import InputNumber from "components/Inputs/InputNumber"; @@ -10,6 +10,8 @@ import { prettyName } from "utils/formatting"; import InputBoolean from "components/Inputs/InputBoolean"; import { SelectorNumber, SelectorText } from "haService/fieldTypes"; import InputYaml from "components/Inputs/InputYaml"; +import { useSnackbar } from "notistack"; +import { InputEntity } from "components/Inputs/InputEntities"; export type ServiceEditorFieldProps = { option: ServiceEditorOption; @@ -23,6 +25,8 @@ export const ServiceEditorField: FC = ({ onChange, onRemove, }) => { + const snackr = useSnackbar(); + const msgRef = useRef>({}); const description = option.data.description ?? ""; const isRequired = !onRemove; const label = option.label; @@ -97,6 +101,37 @@ export const ServiceEditorField: FC = ({ return ; } else if ("object" in option.data.selector) { return ; + } else if ("entity" in option.data.selector) { + const options = option.data.selector.entity ?? {}; + console.log(options); + return ( + + ); + } + } + if (option.data.selector) { + if (!msgRef.current[JSON.stringify(option.data.selector)]) { + msgRef.current[JSON.stringify(option.data.selector)] = true; + snackr.enqueueSnackbar( + + "{JSON.stringify(Object.keys(option.data.selector))}" is of a + unimplemented!
+ Please report this to the maintainers.{" "} + For now, we leave you with a generic textbox!
+ DEBUG="{JSON.stringify(option.data.selector)}" +
, + { + variant: "warning", + persist: true, + } + ); } } return ; diff --git a/webapp/src/components/ServiceEditor/index.stories.tsx b/webapp/src/components/ServiceEditor/index.stories.tsx index fa60e13..1495d37 100644 --- a/webapp/src/components/ServiceEditor/index.stories.tsx +++ b/webapp/src/components/ServiceEditor/index.stories.tsx @@ -439,6 +439,22 @@ export const LightTurnOn = makeExample({ }, }); +export const ZhaLight = makeExample({ + name: "Turn Light", + description: "", + fields: { + entity: { + description: "Light Entity", + selector: { + entity: { + domain: "light", + integration: "zha", + }, + }, + }, + }, +}); + export const UltimateService = makeExample({ name: "Ultimate Service", description: "Show a notification in the frontend.", diff --git a/webapp/src/haService/DeviceRegistry.ts b/webapp/src/haService/DeviceRegistry.ts deleted file mode 100644 index 9506829..0000000 --- a/webapp/src/haService/DeviceRegistry.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Connection, getCollection } from "home-assistant-js-websocket"; -import { DeviceRegistryItem, HassDevices } from './types'; - - -export const fetchDeviceRegistry = (conn: Connection): Promise> => - conn.sendMessagePromise({ - "type": "config/device_registry/list" - }).then( - data => - data.filter( - ({ disabled_by }) => !disabled_by - ).reduce>((all, n) => { - all[n.id] = n - return all - }, {} - )) -export const deviceRegistryColl = (conn: Connection) => getCollection>( - conn, - "_$drc", - fetchDeviceRegistry -) \ No newline at end of file diff --git a/webapp/src/haService/EntityRegistry.ts b/webapp/src/haService/EntityRegistry.ts deleted file mode 100644 index 224f876..0000000 --- a/webapp/src/haService/EntityRegistry.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Connection, getCollection } from "home-assistant-js-websocket"; -import { HassEntitiesRegistry } from './types'; - - -export const fetchEntityRegistry = (conn: Connection) => conn.sendMessagePromise({ - "type": "config/entity_registry/list" -}).then(data => data.filter(({ disabled_by }) => !disabled_by)) -export const entityRegistryColl = (conn: Connection) => getCollection(conn, "_$erc", fetchEntityRegistry) - diff --git a/webapp/src/haService/HAEntities.ts b/webapp/src/haService/HAEntities.ts new file mode 100644 index 0000000..ddf68e5 --- /dev/null +++ b/webapp/src/haService/HAEntities.ts @@ -0,0 +1,168 @@ +import { Option } from "components/Inputs/InputAutoComplete"; +import { useHassCollection } from "./useHassCollection"; +import { entitiesColl } from "home-assistant-js-websocket"; +import { useHAConnection } from "./connection"; +import { entitySourceColl } from "./additionalCollections"; + +export type EntityOption = Option<{ domain: string; integration: string }>; +export type HAEntitiesState = ReturnType; +export const useHAEntities = () => { + const entities = useHassCollection(entitiesColl, (state) => ({ + domains: Array.from( + new Set(Object.keys(state).map((x) => x.split(".")[0])).keys() + ).sort(), + })); + const entitySource = useHassCollection(entitySourceColl); + 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 = new Set(); + entityIds.forEach((entityId) => { + if (entities.collection.state[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 = 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 ?? []; + }, + validateOptions( + options: string[], + restrictedDomains?: string[], + restrictedIntegrations?: string[] + ): null | string[] { + let out = options; + if (restrictedDomains) { + const domains = restrictedDomains.map((x) => x.toLowerCase()); + const domainsStr = + domains.length > 1 + ? `one of "${domains.join(", ")}"` + : `"${domains[0]}"`; + out = out.reduce((all = [], key) => { + if (!domains.includes(key.toLowerCase().split(".")[0])) { + return [...all, `${methods.getLabel(key)} is not ${domainsStr}`]; + } + return all; + }, []); + } + if (restrictedIntegrations && entitySource.ready) { + const domains = restrictedIntegrations.map((x) => x.toLowerCase()); + const domainsStr = + domains.length > 1 + ? `one of "${domains.join(", ")}"` + : `"${domains[0]}"`; + out = out.reduce((all = [], key) => { + const integration = entitySource.collection.state[key].domain; + if (!domains.includes(integration.toLowerCase())) { + return [...all, `${methods.getLabel(key)} is not ${domainsStr}`]; + } + return all; + }, []); + } + if (out.length > 0) { + return out; + } + return null; + }, + getOptions( + restrictToDomain?: string[], + restrictedIntegrations?: string[] + ): EntityOption[] { + if (!entities.ready) { + return []; + } + let keys = Object.keys(entities.collection.state); + if (restrictToDomain) { + const domains = restrictToDomain.map((x) => x.toLowerCase()); + keys = keys.filter((key) => + domains.includes(key.toLowerCase().split(".")[0]) + ); + } + if (restrictedIntegrations && entitySource.ready) { + const integrations = restrictedIntegrations.map((x) => x.toLowerCase()); + console.log(entitySource); + keys = keys.filter((key) => { + const integration = ( + entitySource.collection.state[key]?.domain ?? "" + ).toLowerCase(); + console.log({ + [key]: integration, + domain: integrations[0], + include: integrations.includes(integration), + }); + return integrations.includes(integration); + }); + } + return keys.map((key) => ({ + id: key, + label: entities.collection.state[key].attributes.friendly_name ?? key, + domain: key.split(".")[0] ?? "n/a", + integration: entitySource.ready + ? entitySource.collection.state[key].domain ?? "n/a" + : "...", + })); + }, + getLabel: (opt: EntityOption): string => { + if (typeof opt === "string") { + if (entities.ready) { + return ( + entities.collection.state[opt]?.attributes.friendly_name ?? opt + ); + } + return opt; + } + return opt.label ?? opt.id; + }, + getID: (opt: EntityOption): string => { + if (typeof opt === "string") { + return opt; + } + return opt.id; + }, + }; + return { + ...entities, + ...methods, + }; +}; diff --git a/webapp/src/haService/additionalCollections.ts b/webapp/src/haService/additionalCollections.ts new file mode 100644 index 0000000..ceb8e71 --- /dev/null +++ b/webapp/src/haService/additionalCollections.ts @@ -0,0 +1,45 @@ +import { Connection, getCollection } from "home-assistant-js-websocket"; +import { + DeviceRegistryItem, + EntitySource, + HassDevices, + HassEntitiesRegistry, +} from "./types"; + +export const fetchDeviceRegistry = ( + conn: Connection +): Promise> => + conn + .sendMessagePromise({ + type: "config/device_registry/list", + }) + .then((data) => + data + .filter(({ disabled_by }) => !disabled_by) + .reduce>((all, n) => { + all[n.id] = n; + return all; + }, {}) + ); +export const deviceRegistryColl = (conn: Connection) => + getCollection>( + conn, + "_$drc", + fetchDeviceRegistry + ); + +export const fetchEntityRegistry = (conn: Connection) => + conn + .sendMessagePromise({ + type: "config/entity_registry/list", + }) + .then((data) => data.filter(({ disabled_by }) => !disabled_by)); +export const entityRegistryColl = (conn: Connection) => + getCollection(conn, "_$erc", fetchEntityRegistry); + +export const fetchEntitySource = (conn: Connection) => + conn.sendMessagePromise>({ + type: "entity/source", + }); +export const entitySourceColl = (conn: Connection) => + getCollection>(conn, "_$esc", fetchEntitySource); diff --git a/webapp/src/haService/entities.stories.tsx b/webapp/src/haService/entities.stories.tsx index c4fd842..4c57e1b 100644 --- a/webapp/src/haService/entities.stories.tsx +++ b/webapp/src/haService/entities.stories.tsx @@ -1,26 +1,25 @@ import React, { FC } from "react"; -import { ComponentMeta, ComponentStory } from '@storybook/react'; +import { ComponentMeta, ComponentStory } from "@storybook/react"; import { Page } from "components/Page"; -import { useHAEntities } from "haService"; +import { useHAEntities } from "haService/HAEntities"; const Test: FC<{ onRender: () => void }> = ({ onRender }) => { - const conn = useHAEntities(); - onRender && onRender() - return - {JSON.stringify(conn, null, 4)} - -} + const conn = useHAEntities(); + onRender && onRender(); + return {JSON.stringify(conn, null, 4)}; +}; export default { - title: 'Services/HA Entities', - component: Test, - parameters: { actions: { argTypesRegex: '^on.*' } }, - args: {} -} as ComponentMeta + title: "Services/HA Entities", + component: Test, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: {}, +} as ComponentMeta; -export const Base: ComponentStory = props => { - - return - +export const Base: ComponentStory = (props) => { + return ( + + -}; \ No newline at end of file + ); +}; diff --git a/webapp/src/haService/extras.ts b/webapp/src/haService/extras.ts index 4f7ac01..96651aa 100644 --- a/webapp/src/haService/extras.ts +++ b/webapp/src/haService/extras.ts @@ -10,8 +10,8 @@ import { HASendMessage, } from "./types"; -export const getDeviceExtraWsCalls = (callHA: HASendMessage) => { - const createUseThing = function ( +export const makeCreateUseThing = (callHA: HASendMessage) => + function ( convertArgsToMessage: (a: Args) => MessageBase, transformHAData: (ha: HAData) => STData, defaultSTData: STData @@ -41,6 +41,9 @@ export const getDeviceExtraWsCalls = (callHA: HASendMessage) => { return stData; }; }; + +export const getDeviceExtraWsCalls = (callHA: HASendMessage) => { + const createUseThing = makeCreateUseThing(callHA); const reduceDeviceThings = function < Raw extends { type: string; subtype?: string; entity_id?: string } >(raw: Raw[]) { diff --git a/webapp/src/haService/index.ts b/webapp/src/haService/index.ts index 64c02a9..7ab32b4 100644 --- a/webapp/src/haService/index.ts +++ b/webapp/src/haService/index.ts @@ -1,7 +1,9 @@ -import { entitiesColl, servicesColl } from "home-assistant-js-websocket"; +import { servicesColl } from "home-assistant-js-websocket"; import { Namer } from "utils/formatting"; -import { deviceRegistryColl } from "./DeviceRegistry"; -import { entityRegistryColl } from "./EntityRegistry"; +import { + deviceRegistryColl, + entityRegistryColl, +} from "./additionalCollections"; import { DeviceRegistryItem, HASendMessage } from "./types"; import { useHassCollection } from "./useHassCollection"; import { useHAConnection } from "./connection"; @@ -9,131 +11,7 @@ import { useSnackbar } from "notistack"; import { TypedHassService } from "./fieldTypes"; import { Option } from "components/Inputs/InputAutoComplete"; import { getDeviceExtraWsCalls } from "./extras"; - -export type EntityOption = Option<{ domain: string }>; -export type HAEntitiesState = ReturnType; -export const useHAEntities = () => { - const entities = useHassCollection(entitiesColl, (state) => ({ - domains: Array.from( - new Set(Object.keys(state).map((x) => x.split(".")[0])).keys() - ).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 = new Set(); - entityIds.forEach((entityId) => { - if (entities.collection.state[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 = 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 ?? []; - }, - validateOptions( - options: string[], - restrictedDomains?: string[] - ): null | string[] { - if (restrictedDomains) { - const domains = restrictedDomains.map((x) => x.toLowerCase()); - const domainsStr = - domains.length > 1 - ? `one of "${domains.join(", ")}"` - : `"${domains[0]}"`; - const out = options.reduce((all = [], key) => { - if (!domains.includes(key.toLowerCase().split(".")[0])) { - return [...all, `${methods.getLabel(key)} is not ${domainsStr}`]; - } - return all; - }, []); - if (out.length > 0) { - return out; - } - } - return null; - }, - getOptions(restrictToDomain?: string[]): EntityOption[] { - if (!entities.ready) { - return []; - } - let keys = Object.keys(entities.collection.state); - if (restrictToDomain) { - const domains = restrictToDomain.map((x) => x.toLowerCase()); - keys = keys.filter((key) => - domains.includes(key.toLowerCase().split(".")[0]) - ); - } - return keys.map((key) => ({ - id: key, - label: entities.collection.state[key].attributes.friendly_name ?? key, - domain: key.split(".")[0] ?? "n/a", - })); - }, - getLabel: (opt: EntityOption): string => { - if (typeof opt === "string") { - if (entities.ready) { - return ( - entities.collection.state[opt]?.attributes.friendly_name ?? opt - ); - } - return opt; - } - return opt.label ?? opt.id; - }, - getID: (opt: EntityOption): string => { - if (typeof opt === "string") { - return opt; - } - return opt.id; - }, - }; - return { - ...entities, - ...methods, - }; -}; +import { useHAEntities } from "./HAEntities"; export type ServiceOption = Option<{ domain: string; diff --git a/webapp/src/haService/types.ts b/webapp/src/haService/types.ts index 07930f1..e29d268 100644 --- a/webapp/src/haService/types.ts +++ b/webapp/src/haService/types.ts @@ -107,3 +107,10 @@ export interface HaFormBooleanSchema extends HaFormBaseSchema { export interface HaFormTimeSchema extends HaFormBaseSchema { type: "positive_time_period_dict"; } + +export interface EntitySource { + domain: string; + custom_component: boolean; + source: "config_entry" | "platform_config"; + config_entry?: string; +}