From 15c97b81b4a5205a156ed9e8235afb4ce23584e9 Mon Sep 17 00:00:00 2001 From: Ari Date: Thu, 16 Jun 2022 17:24:31 -0400 Subject: [PATCH] input area --- webapp/src/components/Inputs/InputArea.tsx | 25 + .../components/Inputs/InputAutoComplete.css | 6 + .../Inputs/InputAutoComplete.test.ts | 13 + .../components/Inputs/InputAutoComplete.tsx | 70 ++- .../src/components/Inputs/InputAutoText.tsx | 1 - webapp/src/components/Inputs/InputDevice.tsx | 31 +- .../NodeEditor/OptionManager/index.tsx | 2 +- .../ServiceEditor/ServiceEditorField.tsx | 127 ++--- .../ServiceEditor/ServiceEditorTarget.css | 10 + .../ServiceEditor/ServiceEditorTarget.tsx | 89 ++++ webapp/src/components/ServiceEditor/index.tsx | 47 +- .../src/components/ServiceEditor/options.ts | 30 +- webapp/src/haService/AreaRegistry.ts | 142 +++++ webapp/src/haService/EntityRegistry.ts | 3 +- webapp/src/haService/index.ts | 504 +++++++++--------- webapp/src/haService/types.ts | 15 +- 16 files changed, 699 insertions(+), 416 deletions(-) create mode 100644 webapp/src/components/Inputs/InputArea.tsx create mode 100644 webapp/src/components/Inputs/InputAutoComplete.test.ts create mode 100644 webapp/src/components/ServiceEditor/ServiceEditorTarget.css create mode 100644 webapp/src/components/ServiceEditor/ServiceEditorTarget.tsx create mode 100644 webapp/src/haService/AreaRegistry.ts diff --git a/webapp/src/components/Inputs/InputArea.tsx b/webapp/src/components/Inputs/InputArea.tsx new file mode 100644 index 0000000..2a50114 --- /dev/null +++ b/webapp/src/components/Inputs/InputArea.tsx @@ -0,0 +1,25 @@ +import { FC } from "react"; +import { + InputAutoComplete, + InputAutoCompletePropsBase, +} from "./InputAutoComplete"; +import { useHAAreas } from "haService/AreaRegistry"; + +export type InputAreaProps = InputAutoCompletePropsBase & { + restrictToDomain?: string[]; +}; + +export const InputArea: FC = (props) => { + // state + const areas = useHAAreas(); + return ( + areas.validateOptions(v, props.restrictToDomain)} + options={areas.getOptions(props.restrictToDomain)} + getID={areas.getID} + getLabel={areas.getLabel} + onlyShowLabel + /> + ); +}; diff --git a/webapp/src/components/Inputs/InputAutoComplete.css b/webapp/src/components/Inputs/InputAutoComplete.css index 80d4ec0..3c70bf5 100644 --- a/webapp/src/components/Inputs/InputAutoComplete.css +++ b/webapp/src/components/Inputs/InputAutoComplete.css @@ -32,4 +32,10 @@ max-height: 5em; max-width: 100%; overflow: auto; +} + +.input-autocomplete--chip small { + max-width: 7em; + text-overflow: ellipsis; + overflow: hidden; } \ No newline at end of file diff --git a/webapp/src/components/Inputs/InputAutoComplete.test.ts b/webapp/src/components/Inputs/InputAutoComplete.test.ts new file mode 100644 index 0000000..dc92536 --- /dev/null +++ b/webapp/src/components/Inputs/InputAutoComplete.test.ts @@ -0,0 +1,13 @@ +import { computeSimilarity } from "./InputAutoComplete"; + +test("similarity score", () => { + const searchTerms = [ + "lught", + "light", + "light balcn", + "light bal", + "light balcony", + "Balcony lig", + ].map((x) => computeSimilarity(x, "light.balcony", "Balcony Light")); + expect(searchTerms).toStrictEqual(searchTerms.sort()); +}); diff --git a/webapp/src/components/Inputs/InputAutoComplete.tsx b/webapp/src/components/Inputs/InputAutoComplete.tsx index cf9efd2..0920ddc 100644 --- a/webapp/src/components/Inputs/InputAutoComplete.tsx +++ b/webapp/src/components/Inputs/InputAutoComplete.tsx @@ -1,5 +1,4 @@ import "./InputAutoComplete.css"; -import { Option } from "haService"; import Autocomplete from "@mui/material/Autocomplete"; import TextField from "@mui/material/TextField"; import Chip from "@mui/material/Chip"; @@ -7,6 +6,11 @@ import { Badge } from "@mui/material"; import { SearchItem } from "./extras"; import { ReactNode } from "react"; +export type BaseOption = { + id: string; + label: string; +} & T; +export type Option = string | BaseOption; export type InputAutoCompleteProps> = { validateOption?: (v: string[]) => string[] | null; groupBy?: (opt: T) => string; @@ -18,7 +22,6 @@ export type InputAutoCompleteProps> = { required?: boolean; onlyShowLabel?: boolean; } & InputAutoCompletePropsBase; - export type InputAutoCompletePropsBase = { label?: string; className?: string; @@ -35,6 +38,25 @@ export type InputAutoCompletePropsBase = { } ); +export function computeSimilarity( + text: string, + optId: string, + optLabel: string +) { + let similarityScore = 0; + const lowCaseId = optId.toLocaleLowerCase(); + const lowCaseLabel = optLabel.toLocaleLowerCase(); + for (const segment of text.toLocaleLowerCase().split(" ")) { + if (lowCaseId.includes(segment)) { + similarityScore += lowCaseId.length / lowCaseId.length; + } + if (lowCaseId.includes(segment)) { + similarityScore += lowCaseLabel.length / lowCaseLabel.length; + } + } + return similarityScore; +} + export function InputAutoComplete( props: InputAutoCompleteProps ) { @@ -120,32 +142,26 @@ export function InputAutoComplete( onChange={onChange} getOptionLabel={getLabel as any} filterOptions={(opts, s) => { - const searchTerm = s.inputValue.toLocaleLowerCase().trim(); + const searchTerm = s.inputValue; if (!searchTerm) { return opts; } return opts .map((opt) => { - let similarityScore = 0; - const eid = getID(opt); - if (eid.toLocaleLowerCase().includes(searchTerm)) { - similarityScore = Math.abs(eid.length - searchTerm.length); - } - const name = getLabel(opt); - if (name.toLocaleLowerCase().includes(searchTerm)) { - similarityScore = Math.abs(eid.length - searchTerm.length); - } return { - label: name, - id: eid, - domain: typeof opt === "string" ? "" : (opt as any).domain, - similarityScore, + opt, + similarityScore: computeSimilarity( + searchTerm, + getID(opt), + getLabel(opt) + ), }; }) .filter((opt) => opt.similarityScore > 0) .sort((a, b) => { - return a.similarityScore > b.similarityScore ? 1 : -1; - }) as any; + return a.similarityScore < b.similarityScore ? 1 : -1; + }) + .map(({ opt }) => opt); }} groupBy={props.groupBy} renderOption={(listProps, option, { inputValue }) => { @@ -153,14 +169,16 @@ export function InputAutoComplete( const id = getID(option); return ( - + <> + + ); }} renderInput={(params) => ( diff --git a/webapp/src/components/Inputs/InputAutoText.tsx b/webapp/src/components/Inputs/InputAutoText.tsx index ee3be35..ece099e 100644 --- a/webapp/src/components/Inputs/InputAutoText.tsx +++ b/webapp/src/components/Inputs/InputAutoText.tsx @@ -22,7 +22,6 @@ export default function InputAutoText({ endAdornment, error, }: InputAutoTextProps) { - console.log(options); return ( = props => { - // state - const dr = useHADeviceRegistry(); +export const InputDevice: FC = (props) => { + // state + const dr = useHADeviceRegistry(); - return -} + ); +}; diff --git a/webapp/src/components/NodeEditor/OptionManager/index.tsx b/webapp/src/components/NodeEditor/OptionManager/index.tsx index ce8a7c4..c7255be 100644 --- a/webapp/src/components/NodeEditor/OptionManager/index.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/index.tsx @@ -226,7 +226,7 @@ const computeInvalidYaml = ( ) => { const errors = validateNode(node, allowedNodeTypes); if (errors) { - console.log({ errors }); + console.warn({ errors }); return { node, isErrored: true, diff --git a/webapp/src/components/ServiceEditor/ServiceEditorField.tsx b/webapp/src/components/ServiceEditor/ServiceEditorField.tsx index d973d4f..ed8d800 100644 --- a/webapp/src/components/ServiceEditor/ServiceEditorField.tsx +++ b/webapp/src/components/ServiceEditor/ServiceEditorField.tsx @@ -5,10 +5,7 @@ import InputText from "components/Inputs/InputText"; import InputNumber from "components/Inputs/InputNumber"; import { IconButton } from "@mui/material"; import { RemoveCircle } from "@mui/icons-material"; -import { InputEntity } from "components/Inputs/InputEntities"; -import InputAutoText from "components/Inputs/InputAutoText"; -import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; -import { Option } from "haService"; +import { InputAutoComplete, Option } from "components/Inputs/InputAutoComplete"; import { prettyName } from "utils/formatting"; export type ServiceEditorFieldProps = { @@ -45,85 +42,67 @@ export const ServiceEditorField: FC = ({ required={isRequired} /> ); - if (option.type === "field") { - example = option.data.example ? `Example: ${option.data.example}` : ""; - if (option.data.selector?.number) { - return ( - - ); - } - if (option.data.selector?.select) { - return ( - ((opt) => { - if (typeof opt === "string") { - return { - id: opt, - label: prettyName(opt), - }; - } - return { - id: opt.value, - label: opt.label, - }; - })} - getLabel={(opt) => { - if (typeof opt === "string") { - return prettyName(opt); - } - return opt.label; - }} - onlyShowLabel - /> - ); - } + example = option.data.example ? `Example: ${option.data.example}` : ""; + if (option.data.selector?.number) { return ( - ); - } else { - if (option.id === "entity") { - if ("domain" in option.data) { - return ( - - ); - } - } } + if (option.data.selector?.select) { + return ( + ((opt) => { + if (typeof opt === "string") { + return { + id: opt, + label: prettyName(opt), + }; + } + return { + id: opt.value, + label: opt.label, + }; + })} + getLabel={(opt) => { + if (typeof opt === "string") { + return prettyName(opt); + } + return opt.label; + }} + onlyShowLabel + /> + ); + } + return ( + + ); return input; }; diff --git a/webapp/src/components/ServiceEditor/ServiceEditorTarget.css b/webapp/src/components/ServiceEditor/ServiceEditorTarget.css new file mode 100644 index 0000000..49d4627 --- /dev/null +++ b/webapp/src/components/ServiceEditor/ServiceEditorTarget.css @@ -0,0 +1,10 @@ +.service-editor--targets { + display: flex; + flex-direction: row; + gap: 1em; + padding-bottom: 0.5em; +} + +.service-editor--targets>div { + flex: 1; +} \ No newline at end of file diff --git a/webapp/src/components/ServiceEditor/ServiceEditorTarget.tsx b/webapp/src/components/ServiceEditor/ServiceEditorTarget.tsx new file mode 100644 index 0000000..d55a42e --- /dev/null +++ b/webapp/src/components/ServiceEditor/ServiceEditorTarget.tsx @@ -0,0 +1,89 @@ +import "./ServiceEditorTarget.css"; +import { InputDevice } from "components/Inputs/InputDevice"; +import { InputEntity } from "components/Inputs/InputEntities"; +import { Targets } from "haService/fieldTypes"; +import { FC } from "react"; +import { InputArea } from "components/Inputs/InputArea"; + +type RawTargetData = { + entity_id?: string[] | string; + area_id?: string[] | string; + device_id?: string[] | string; +}; +type CleanTargetData = { + entity_id: string[]; + area_id: string[]; + device_id: string[]; +}; + +export type ServiceEditorTargetProps = { + defn: Targets; + value: RawTargetData | null | undefined; + onChange: (v: any) => void; +}; +export const ServiceEditorTarget: FC = (props) => { + const value = cleanUpValue(props.value ?? {}); + const domainRestrictions: string[] = []; + + if (props.defn.entity) { + if (typeof props.defn.entity.domain === "string") { + domainRestrictions.push(props.defn.entity.domain); + } + } + + return ( +
+ + props.onChange({ + ...(props.value || {}), + entity_id, + }) + } + restrictToDomain={domainRestrictions} + multiple + /> + + props.onChange({ + ...(props.value || {}), + device_id, + }) + } + multiple + /> + + props.onChange({ + ...(props.value || {}), + area_id, + }) + } + multiple + /> +
+ ); +}; + +const cleanUpValue = (value: RawTargetData): CleanTargetData => { + const cleanOne = (v?: string[] | string): string[] => { + if (typeof v === "string") { + return [v]; + } + if (!v || !Array.isArray(v)) { + return []; + } + return v; + }; + return { + entity_id: cleanOne(value.entity_id), + device_id: cleanOne(value.device_id), + area_id: cleanOne(value.area_id), + }; +}; diff --git a/webapp/src/components/ServiceEditor/index.tsx b/webapp/src/components/ServiceEditor/index.tsx index d55a743..77a8edb 100644 --- a/webapp/src/components/ServiceEditor/index.tsx +++ b/webapp/src/components/ServiceEditor/index.tsx @@ -7,11 +7,11 @@ import { ServiceEditorOption, splitUpOptions, convertFieldToOption, - convertTargetToOption, ServiceEditorData, } from "./options"; import { ServiceEditorField } from "./ServiceEditorField"; import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; +import { ServiceEditorTarget } from "./ServiceEditorTarget"; export type ServiceEditorProps = { serviceId: string; @@ -26,7 +26,6 @@ export const ServiceEditor: FC = ({ onUpdate, }) => { const options = splitUpOptions(service, data); - console.log(service); const [additionalFields, setAdditionalFields] = useState<{ field: string[]; optionalList: ServiceEditorOption[]; @@ -60,14 +59,14 @@ export const ServiceEditor: FC = ({ <> {options.required.map((opt) => ( onUpdate({ ...data, - [opt.type]: { - ...data[opt.type], + field: { + ...data.field, [opt.id]: v, }, }) @@ -75,28 +74,17 @@ export const ServiceEditor: FC = ({ /> ))} {hasTargets && ( -
- {Object.keys(service.target ?? {}).map((key) => { - const targetData = (service.target as any)[key]; - const option = convertTargetToOption(key, targetData); - return ( - - onUpdate({ - ...data, - target: { - ...data.target, - [key]: v, - }, - }) - } - /> - ); - })} -
+ + onUpdate({ + ...data, + target, + }) + } + /> )}
{additionalFields.field.map((key) => { @@ -154,8 +142,7 @@ export const ServiceEditor: FC = ({ ...additionalFields, field: additionalFields.field.concat([newField.id]), optionalList: additionalFields.optionalList.filter( - (opt) => - !(opt.type === newField.type && opt.id === newField.id) + (opt) => !(opt.id === newField.id) ), }); } diff --git a/webapp/src/components/ServiceEditor/options.ts b/webapp/src/components/ServiceEditor/options.ts index 5c747b1..da2236e 100644 --- a/webapp/src/components/ServiceEditor/options.ts +++ b/webapp/src/components/ServiceEditor/options.ts @@ -1,41 +1,21 @@ -import { BaseOption } from "haService"; -import { FieldData, TargetData, TypedHassService } from "haService/fieldTypes"; +import { BaseOption } from "components/Inputs/InputAutoComplete"; +import { FieldData, TypedHassService } from "haService/fieldTypes"; import { prettyName } from "utils/formatting"; export type ServiceEditorData = { field: Record; target: Record; }; -export type ServiceEditorOption = BaseOption< - | { - type: "field"; - data: { - description: string; - } & FieldData; - } - | { - type: "target"; - data: { - description: string; - } & TargetData; - } ->; +export type ServiceEditorOption = BaseOption<{ + data: FieldData +}>; export const convertFieldToOption = (id: string, data: FieldData): ServiceEditorOption => ({ id, label: data.name ?? prettyName(id), - type: "field", data, }) -export const convertTargetToOption = (id: string, data: TargetData): ServiceEditorOption => ({ - id, - type: "target", - label: ((data ?? {}) as any).name ?? prettyName(id), - data: (data as any) ?? { - description: "", - }, -}) export const splitUpOptions = (service: TypedHassService, data: ServiceEditorData) => { const required: ServiceEditorOption[] = []; diff --git a/webapp/src/haService/AreaRegistry.ts b/webapp/src/haService/AreaRegistry.ts new file mode 100644 index 0000000..dd1defc --- /dev/null +++ b/webapp/src/haService/AreaRegistry.ts @@ -0,0 +1,142 @@ +import { Connection, getCollection } from "home-assistant-js-websocket"; +import { useHassCollection } from "./useHassCollection"; +import { Option, BaseOption } from "components/Inputs/InputAutoComplete"; +import { EntityRegisteryItem, HassEntitiesRegistry } from "./types"; +import { prettyName } from "utils/formatting"; + +export interface AreaRegistryItem { + area_id: string; + name: string; + picture: null | string; +} +export type AreaDB = Record< + string, + AreaRegistryItem & { + entity: Partial; + } +>; + +export const fetchAreaRegistry = (conn: Connection) => + Promise.all([ + conn.sendMessagePromise({ + type: "config/area_registry/list", + }), + conn.sendMessagePromise({ + type: "config/entity_registry/list", + }), + ]).then(([areas, er]) => { + const areaDB = areas.reduce((all, item) => { + return { + ...all, + [item.area_id]: { + ...item, + entity: {}, + }, + }; + }, {}); + er.forEach((eri) => { + if (eri.area_id) { + areaDB[eri.area_id].entity = eri; + } + }); + + return areaDB; + }); +export const areaRegistryColl = (conn: Connection) => + getCollection(conn, "_$earg", fetchAreaRegistry); + +export type AreaOptionData = { + data: Partial; +}; +export type AreaBaseOption = BaseOption; +export type AreaOption = Option; +export const useHAAreas = () => { + const areas = useHassCollection(areaRegistryColl); + + const methods = { + getAreaEntityDomain(areaId: string): null | string { + if (!areas.ready) { + return null; + } + const entityId = areas.collection.state[areaId].entity.entity_id; + if (entityId) { + return entityId.toLowerCase().split(".")[0] ?? null; + } + return null; + }, + 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 = [], areaId) => { + const domain = methods.getAreaEntityDomain(areaId) ?? ""; + if (!domains.includes(domain)) { + return [...all, `${methods.getLabel(areaId)} is not ${domainsStr}`]; + } + return all; + }, []); + if (out.length > 0) { + return out; + } + } + return null; + }, + getBaseOption(opt: AreaOption): AreaBaseOption { + if (!areas.ready) { + throw new Error("Not Ready!"); + } + if (typeof opt === "string") { + return { + id: opt, + label: areas.collection.state[opt].name ?? prettyName(opt), + data: areas.collection.state[opt], + }; + } + return opt; + }, + getOptions(restrictToDomain?: string[]): AreaOption[] { + if (!areas.ready) { + return []; + } + let keys = Object.keys(areas.collection.state); + if (restrictToDomain) { + const domains = restrictToDomain.map((x) => x.toLowerCase()); + keys = keys.filter((key) => { + const domain = methods.getAreaEntityDomain(key); + if (domain) { + return domains.includes(domain); + } + return false; + }); + } + return keys.map((key) => ({ + id: key, + label: areas.collection.state[key].name ?? prettyName(key), + data: areas.collection.state[key].entity, + })); + }, + getLabel: (opt: AreaOption): string => { + if (typeof opt === "string") { + if (areas.ready) { + return areas.collection.state[opt].name ?? prettyName(opt); + } + return opt; + } + return opt.label ?? opt.id; + }, + getID: (opt: AreaOption): string => { + if (typeof opt === "string") { + return opt; + } + return opt.id; + }, + }; + + return methods; +}; diff --git a/webapp/src/haService/EntityRegistry.ts b/webapp/src/haService/EntityRegistry.ts index e0d792c..224f876 100644 --- a/webapp/src/haService/EntityRegistry.ts +++ b/webapp/src/haService/EntityRegistry.ts @@ -5,4 +5,5 @@ 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) \ No newline at end of file +export const entityRegistryColl = (conn: Connection) => getCollection(conn, "_$erc", fetchEntityRegistry) + diff --git a/webapp/src/haService/index.ts b/webapp/src/haService/index.ts index af234f8..32e960a 100644 --- a/webapp/src/haService/index.ts +++ b/webapp/src/haService/index.ts @@ -1,267 +1,295 @@ -import { entitiesColl, servicesColl } from "home-assistant-js-websocket" +import { entitiesColl, servicesColl } from "home-assistant-js-websocket"; import { Namer } from "utils/formatting"; import { deviceRegistryColl } from "./DeviceRegistry"; import { entityRegistryColl } from "./EntityRegistry"; import { DeviceRegistryItem } from "./types"; -import { useHassCollection } from "./useHassCollection" -import { useHAConnection } from './connection'; +import { useHassCollection } from "./useHassCollection"; +import { useHAConnection } from "./connection"; import { useSnackbar } from "notistack"; import { TypedHassService } from "./fieldTypes"; +import { Option } from "components/Inputs/InputAutoComplete"; -export type BaseOption = { - id: string, - label: string, -} & T -export type Option = string | BaseOption; -export type EntityOption = Option<{ domain: string; }> +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 = { - 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]}"` - return options.reduce((all = [], key) => { - if (!domains.includes(key.toLowerCase().split('.')[0])) { - return [ - ...all, - `${methods.getLabel(key)} is not ${domainsStr}` - ] - } - return all - }, []) - } - 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 + const entities = useHassCollection(entitiesColl, (state) => ({ + domains: Array.from( + new Set(Object.keys(state).map((x) => x.split(".")[0])).keys() + ).sort(), + })); + const methods = { + 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 { - ...entities, - ...methods - } -} + } + 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, + }; +}; -export type ServiceOption = Option<{ - domain: string, - action: string, - description: string, - data: TypedHassService, +export type ServiceOption = Option<{ + domain: string; + action: string; + description: string; + data: TypedHassService; }>; export type HAServicesState = ReturnType; export const useHAServices = () => { - const services = useHassCollection(servicesColl); - const methods = { - getOption(name: string): TypedHassService | null { - if (!services.ready) { - return null; - } - try { - const [domain, action] = name.split('.'); - return { - name: services.collection.state[domain][action].name ?? `${domain}.${action}`, - description: services.collection.state[domain][action].description ?? "", - target: services.collection.state[domain][action].target, - fields: services.collection.state[domain][action].fields, - } - }catch(err: any) { - console.warn(err) - return null - } + const services = useHassCollection(servicesColl); + const methods = { + getOption(name: string): TypedHassService | null { + if (!services.ready) { + return null; + } + try { + const [domain, action] = name.split("."); + return { + name: + services.collection.state[domain][action].name ?? + `${domain}.${action}`, + description: + services.collection.state[domain][action].description ?? "", + target: services.collection.state[domain][action].target, + fields: services.collection.state[domain][action].fields, + }; + } catch (err: any) { + console.warn(err); + return null; + } + }, + getOptions(): ServiceOption[] { + if (!services.ready) { + return []; + } + return Object.keys(services.collection.state).reduce( + (all, domain) => { + const opts = Object.keys( + services.collection.state[domain] + ).map((action) => ({ + id: `${domain}.${action}`, + label: + services.collection.state[domain][action].name ?? + `${domain}.${action}`, + description: + services.collection.state[domain][action].description ?? "", + domain, + action, + data: { + name: + services.collection.state[domain][action].name ?? + `${domain}.${action}`, + description: + services.collection.state[domain][action].description ?? "", + target: services.collection.state[domain][action].target, + fields: services.collection.state[domain][action].fields, + }, + })); + return all.concat(opts); }, - getOptions(): ServiceOption[] { - if (!services.ready) { - return [] - } - return Object.keys(services.collection.state).reduce((all, domain) => { - const opts = Object.keys(services.collection.state[domain]).map( - action => ({ - id: `${domain}.${action}`, - label: services.collection.state[domain][action].name ?? `${domain}.${action}`, - description: services.collection.state[domain][action].description ?? "", - domain, - action, - data: { - name: services.collection.state[domain][action].name ?? `${domain}.${action}`, - description: services.collection.state[domain][action].description ?? "", - target: services.collection.state[domain][action].target, - fields: services.collection.state[domain][action].fields, - } - }) - ) - return all.concat(opts); - }, []) - }, - getLabel: (opt: ServiceOption): string => { - if (typeof opt === 'string') { - if (services.ready) { - try { - const [domain, action] = opt.split('.'); - return services.collection.state[domain][action].name ?? opt; - } catch (_) { } - } - return opt - } - return opt.label ?? opt.id - }, - getID: (opt: ServiceOption): string => { - if (typeof opt === 'string') { - return opt - } - return opt.id + [] + ); + }, + getLabel: (opt: ServiceOption): string => { + if (typeof opt === "string") { + if (services.ready) { + try { + const [domain, action] = opt.split("."); + return services.collection.state[domain][action].name ?? opt; + } catch (_) {} } - } + return opt; + } + return opt.label ?? opt.id; + }, + getID: (opt: ServiceOption): string => { + if (typeof opt === "string") { + return opt; + } + return opt.id; + }, + }; - return { ...services, ...methods } -} + return { ...services, ...methods }; +}; export type DeviceRegistryOption = Option<{ manufacturer: string }>; export const useHADeviceRegistry = () => { - const dr = useHassCollection(deviceRegistryColl) - const getLabelForItem = (item: DeviceRegistryItem) => item ? item.name_by_user ?? - item.name ?? - item.id : - ""; - const methods = { - getOptions(): DeviceRegistryOption[] { - if (!dr.ready) { - return [] - } - const keys = Object.keys(dr.collection.state); - return keys.map(key => ({ - id: key, - label: getLabelForItem(dr.collection.state[key]) ?? key, - manufacturer: dr.collection.state[key].manufacturer ?? "", - })) - }, - getLabel: (opt: DeviceRegistryOption): string => { - if (typeof opt === 'string') { - if (dr.ready) { - return getLabelForItem(dr.collection.state[opt]) ?? opt - } - return opt - } - return opt.label ?? opt.id - }, - getID: (opt: DeviceRegistryOption): string => { - if (typeof opt === 'string') { - return opt - } - return opt.id + const dr = useHassCollection(deviceRegistryColl); + const getLabelForItem = (item: DeviceRegistryItem) => + item ? item.name_by_user ?? item.name ?? item.id : ""; + const methods = { + getOptions(): DeviceRegistryOption[] { + if (!dr.ready) { + return []; + } + const keys = Object.keys(dr.collection.state); + return keys.map((key) => ({ + id: key, + label: getLabelForItem(dr.collection.state[key]) ?? key, + manufacturer: dr.collection.state[key].manufacturer ?? "", + })); + }, + getLabel: (opt: DeviceRegistryOption): string => { + if (typeof opt === "string") { + if (dr.ready) { + return getLabelForItem(dr.collection.state[opt]) ?? opt; } - } - return { ...dr, ...methods } -} + return opt; + } + return opt.label ?? opt.id; + }, + getID: (opt: DeviceRegistryOption): string => { + if (typeof opt === "string") { + return opt; + } + return opt.id; + }, + }; + return { ...dr, ...methods }; +}; export const useHAEntityRegistry = () => { - const dr = useHassCollection(entityRegistryColl) - - return dr -} + const dr = useHassCollection(entityRegistryColl); + return dr; +}; export const useHA = () => { - const entities = useHAEntities(); - const devices = useHADeviceRegistry(); - const services = useHAServices(); - const conn = useHAConnection(); - const { enqueueSnackbar } = useSnackbar(); + const entities = useHAEntities(); + const devices = useHADeviceRegistry(); + const services = useHAServices(); + const conn = useHAConnection(); + const { enqueueSnackbar } = useSnackbar(); - const callService = async ( - domain: string, - service: string, - data: any = {}, - target: any = {}, - ) => { - if (conn.status === 'loaded') { - try { - const result = await conn.connection.sendMessagePromise({ - "type": "call_service", - domain, - service, - target, - service_data: data - }) - enqueueSnackbar(`Successfully called ${domain}.${service}`, { - "variant": "success", - }) - return result - } catch (err: any) { - let msg = JSON.stringify(err) - if ('message' in err) { - msg = err.message - } - enqueueSnackbar(`Failed to call ${domain}.${service} because '${msg}'`, { - "variant": "error", - }) - return - } - } if (conn.status === 'error') { - enqueueSnackbar(`Failed to call service because connection is '${conn.status}' -- ${conn.error}`, { - "variant": "error" - }) - } else { - enqueueSnackbar(`Failed to call service because connection is '${conn.status}'`, { - "variant": "error" - }) + const callService = async ( + domain: string, + service: string, + data: any = {}, + target: any = {} + ) => { + if (conn.status === "loaded") { + try { + const result = await conn.connection.sendMessagePromise({ + type: "call_service", + domain, + service, + target, + service_data: data, + }); + enqueueSnackbar(`Successfully called ${domain}.${service}`, { + variant: "success", + }); + return result; + } catch (err: any) { + let msg = JSON.stringify(err); + if ("message" in err) { + msg = err.message; } + enqueueSnackbar( + `Failed to call ${domain}.${service} because '${msg}'`, + { + variant: "error", + } + ); + return; + } } + if (conn.status === "error") { + enqueueSnackbar( + `Failed to call service because connection is '${conn.status}' -- ${conn.error}`, + { + variant: "error", + } + ); + } else { + enqueueSnackbar( + `Failed to call service because connection is '${conn.status}'`, + { + variant: "error", + } + ); + } + }; - const namer: Namer = { - getDeviceName(device_id) { - return devices.getLabel(device_id) - }, - getEntityName(entity_id, maxEntities = 1) { - if (Array.isArray(entity_id)) { - return entity_id.slice(0, maxEntities).map(entities.getLabel).join(', ') - } - return entities.getLabel(entity_id) - }, - getServiceName(service) { - return services.getLabel(service) - }, - } + const namer: Namer = { + getDeviceName(device_id) { + return devices.getLabel(device_id); + }, + getEntityName(entity_id, maxEntities = 1) { + if (Array.isArray(entity_id)) { + return entity_id + .slice(0, maxEntities) + .map(entities.getLabel) + .join(", "); + } + return entities.getLabel(entity_id); + }, + getServiceName(service) { + return services.getLabel(service); + }, + }; - return { - entities, - devices, - services, - namer, - callService, - reloadAutomations: () => callService("automation", "reload") - } -} \ No newline at end of file + return { + entities, + devices, + services, + namer, + callService, + reloadAutomations: () => callService("automation", "reload"), + }; +}; diff --git a/webapp/src/haService/types.ts b/webapp/src/haService/types.ts index 0256b36..1a8b12d 100644 --- a/webapp/src/haService/types.ts +++ b/webapp/src/haService/types.ts @@ -1,8 +1,8 @@ export type EntityRegisteryItem = { - area_id: string | null; - config_entry_id: string | null; - device_id: string | null; - disabled_by: + area_id: null | string; + config_entry_id: null | string; + device_id: null | string; + disabled_by: | "integration" | "user" | "config_entry" @@ -21,9 +21,10 @@ export type EntityRegisteryItem = { | string | null ; - icon: string | null; - name: string | null; - platform: string | null; + entity_id: string; + icon: null | string; + name: null | string; + platform: string; } export type DeviceRegistryItem = {