diff --git a/webapp/src/components/Inputs/InputDevice.stories.tsx b/webapp/src/components/Inputs/InputDevice.stories.tsx new file mode 100644 index 0000000..ded1769 --- /dev/null +++ b/webapp/src/components/Inputs/InputDevice.stories.tsx @@ -0,0 +1,36 @@ +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { Page } from "components/Page"; +import { useState } from "react"; + +import { InputDevice } from "./InputDevice"; + +export default { + title: 'Inputs/InputDevice', + component: InputDevice, + parameters: { actions: { argTypesRegex: '^on.*' } }, + argTypes: {} +} as ComponentMeta; + + + +const Template: ComponentStory = args => { + const [value, setValue] = useState(args.value) + return +
+ { + setValue(v) + args.onChange(v as any) + }} /> +
+
+ +} + +export const Single = Template.bind({}) +Single.args = { + ...Single.args, + multiple: false, + value: 'sensor.bathroom' +} as any diff --git a/webapp/src/components/Inputs/InputDevice.tsx b/webapp/src/components/Inputs/InputDevice.tsx new file mode 100644 index 0000000..8444bd6 --- /dev/null +++ b/webapp/src/components/Inputs/InputDevice.tsx @@ -0,0 +1,117 @@ +import "./InputEntities.css"; +import { FC } from "react"; +import { DeviceRegistryOption, useHADeviceRegistry } from 'haService'; +import Autocomplete from '@mui/material/Autocomplete'; +import TextField from '@mui/material/TextField'; +import Chip from '@mui/material/Chip'; +import { EntityId } from 'types/automations/common'; +import { Badge } from "@mui/material"; +import { SearchItem } from "./extras"; +import { prettyName } from 'utils/formatting'; + +export type InputEntityProps = { + label?: string, +} & ({ + value: string | null; + multiple?: false; + onChange: (v: string | null) => void; +} | { + value: EntityId; + multiple: true; + onChange: (v: string[]) => void; +}) + +export const InputDevice: FC = props => { + // state + const dr = useHADeviceRegistry(); + + // processing of inputs + const options = dr.getOptions(); + const value = Array.isArray(props.value) ? props.value : !!props.value ? [props.value] : []; + + // events + const onChange = (_e: any, v: any) => { + const cleanValue: string[] = v === null ? [] : + Array.isArray(v) ? v.map(opt => { + if (typeof opt === 'string') { + return opt + } + return opt.id + }) : [v]; + if (props.multiple) { + props.onChange(cleanValue); + } else { + props.onChange(cleanValue[cleanValue.length - 1]) + } + } + + return (typeof opt !== 'string') ? prettyName(opt.manufacturer) : ''} + filterOptions={(opts, s) => { + const searchTerm = s.inputValue.toLocaleLowerCase(); + return opts.map(opt => { + let similarityScore = 0; + const eid = dr.getID(opt); + if (eid.toLocaleLowerCase().includes(searchTerm)) { + similarityScore = Math.abs(eid.length - searchTerm.length) + } + const name = dr.getLabel(opt); + if (name.toLocaleLowerCase().includes(searchTerm)) { + similarityScore = Math.abs(eid.length - searchTerm.length) + } + return { + label: name, + id: eid, + similarityScore, + manufacturer: (typeof opt === 'string') ? '' : opt.manufacturer ?? "" + } + }).filter(opt => opt.similarityScore > 0).sort((a, b) => { + return (a.similarityScore > b.similarityScore) ? 1 : -1 + }) + }} + renderOption={(prop, option, { inputValue }) => { + const label = dr.getLabel(option); + const id = dr.getID(option); + + return + }} + renderInput={params => } + renderTags={(tagValue, getTagProps) => +
+ {tagValue.map((option, index) => { + const label = dr.getLabel(option); + const id = dr.getID(option); + const props = getTagProps({ index }); + props.className += ' input-entities--chip' + return ( + + {(id === label) ? {label} : {label}} + {(id !== label) && {id}} + } + {...props} + /> + ) + })} +
+
+ } + /> +} diff --git a/webapp/src/components/Inputs/InputEntities.css b/webapp/src/components/Inputs/InputEntities.css index 80e78f7..db5637e 100644 --- a/webapp/src/components/Inputs/InputEntities.css +++ b/webapp/src/components/Inputs/InputEntities.css @@ -2,13 +2,13 @@ max-width: 100%; } -.input-entities--list, .input-entities--chip>span { +.input-entities--chip>span { display: flex; flex-direction: row; gap: 0.15em; } -.input-entities--list>small::before, .input-entities--chip>span>small::before { +.input-entities--chip>span>small::before { content: "/ "; } diff --git a/webapp/src/components/Inputs/InputEntities.tsx b/webapp/src/components/Inputs/InputEntities.tsx index a56942a..a37cc94 100644 --- a/webapp/src/components/Inputs/InputEntities.tsx +++ b/webapp/src/components/Inputs/InputEntities.tsx @@ -5,10 +5,9 @@ import Autocomplete from '@mui/material/Autocomplete'; import TextField from '@mui/material/TextField'; import Chip from '@mui/material/Chip'; import { prettyName } from "utils/formatting"; -import parse from 'autosuggest-highlight/parse'; -import match from 'autosuggest-highlight/match'; import { EntityId } from 'types/automations/common'; import { Badge } from "@mui/material"; +import { SearchItem } from "./extras"; export type InputEntityProps = { restrictToDomain?: string[], @@ -137,45 +136,3 @@ export const InputEntity: FC = props => { /> } - -export const HighlightElm: FC<{ - text: string, - searchTerm: string -}> = ({ - text, - searchTerm -}) => { - const matches = match(text, searchTerm, { - "findAllOccurrences": true, - "insideWords": true - }); - const parts = parse(text, matches); - return <> - {parts.map((part, index) => ( - - {part.text} - - ))} - - } - -export const SearchItem: FC<{ - listProps: React.HTMLAttributes, - label: string, - id: string, - searchTerm: string, -}> = ({ - listProps, - label, - id, - searchTerm -}) =>
  • - - - -
  • \ No newline at end of file diff --git a/webapp/src/components/Inputs/InputEntityIDSearchItem.stories.tsx b/webapp/src/components/Inputs/extras-SearchItem.stories.tsx similarity index 86% rename from webapp/src/components/Inputs/InputEntityIDSearchItem.stories.tsx rename to webapp/src/components/Inputs/extras-SearchItem.stories.tsx index e682443..d01cea4 100644 --- a/webapp/src/components/Inputs/InputEntityIDSearchItem.stories.tsx +++ b/webapp/src/components/Inputs/extras-SearchItem.stories.tsx @@ -1,10 +1,10 @@ import { ComponentMeta, ComponentStory } from "@storybook/react"; import { Page } from "components/Page"; -import { SearchItem } from "./InputEntities"; +import { SearchItem } from "./extras"; export default { - title: 'Inputs/InputEntity/SearchItem', + title: 'Inputs/Extras/SearchItem', component: SearchItem, parameters: { actions: { argTypesRegex: '^on.*' } }, argTypes: {} diff --git a/webapp/src/components/Inputs/extras.css b/webapp/src/components/Inputs/extras.css new file mode 100644 index 0000000..634031c --- /dev/null +++ b/webapp/src/components/Inputs/extras.css @@ -0,0 +1,9 @@ +.input-extras--search-item--list { + display: flex; + flex-direction: row; + gap: 0.15em; +} + +.input-extras--search-item--list>small::before { + content: "/ "; +} \ No newline at end of file diff --git a/webapp/src/components/Inputs/extras.tsx b/webapp/src/components/Inputs/extras.tsx new file mode 100644 index 0000000..067f620 --- /dev/null +++ b/webapp/src/components/Inputs/extras.tsx @@ -0,0 +1,47 @@ +import "./extras.css"; +import { FC } from "react"; +import parse from 'autosuggest-highlight/parse'; +import match from 'autosuggest-highlight/match'; + + +export const HighlightElm: FC<{ + text: string, + searchTerm: string +}> = ({ + text, + searchTerm +}) => { + const matches = match(text, searchTerm, { + "findAllOccurrences": true, + "insideWords": true + }); + const parts = parse(text, matches); + return <> + {parts.map((part, index) => ( + + {part.text} + + ))} + + } + +export const SearchItem: FC<{ + listProps: React.HTMLAttributes, + label: string, + id: string, + searchTerm: string, +}> = ({ + listProps, + label, + id, + searchTerm +}) =>
  • + + + +
  • \ No newline at end of file diff --git a/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx b/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx index 543fd62..d6ba4fe 100644 --- a/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx @@ -1,3 +1,4 @@ +import { InputDevice } from "components/Inputs/InputDevice"; import { InputEntity } from "components/Inputs/InputEntities"; import InputText from "components/Inputs/InputText"; import { DeviceAction } from "types/automations/actions"; @@ -7,16 +8,16 @@ import { OptionManager, updateActionData } from './OptionManager'; export const ActionDeviceState: OptionManager = { defaultState: () => ({ alias: "", + device_id: "" }), isReady: () => true, - renderOptionList: (state, setState) => { + renderOptionList: (state, setState, entities) => { + console.log(entities.collection?.state) const update = updateActionData(state, setState); return <> - update({ device_id })} + onChange={device_id => update({ device_id: device_id ?? "" })} /> = { @@ -24,9 +25,9 @@ export const TriggerDevice: OptionManager = { ...state, subtype })} /> - setState({ + setState({ ...state, - device_id + device_id: device_id ?? "", })} /> setState({ ...state, diff --git a/webapp/src/haService/DeviceRegistry.ts b/webapp/src/haService/DeviceRegistry.ts new file mode 100644 index 0000000..9506829 --- /dev/null +++ b/webapp/src/haService/DeviceRegistry.ts @@ -0,0 +1,21 @@ +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 new file mode 100644 index 0000000..00757dd --- /dev/null +++ b/webapp/src/haService/EntityRegistry.ts @@ -0,0 +1,8 @@ +import { Connection, getCollection } from "home-assistant-js-websocket"; +import { HassDevices, 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 diff --git a/webapp/src/haService/dr.stories.tsx b/webapp/src/haService/dr.stories.tsx new file mode 100644 index 0000000..4feb3ca --- /dev/null +++ b/webapp/src/haService/dr.stories.tsx @@ -0,0 +1,42 @@ +import React, { FC } from "react"; +import { ComponentMeta, ComponentStory } from '@storybook/react'; +import { Page } from "components/Page"; +import { useHADeviceRegistry } from "haService"; +import InputYaml from "components/Inputs/InputYaml"; + +const Test: FC<{ onRender: () => void }> = ({ onRender }) => { + const conn = useHADeviceRegistry(); + onRender && onRender() + if (conn.ready) { + return
    + {Object.keys(conn.collection.state).length} items +
      + {Object.keys(conn.collection.state).map(k =>
    • + {k} + {/* {conn.collection.state[k].length > 1 ? conn.collection.state[k].length : ''} */} + { }} label={k} /> +
    • )} +
    +
    + } + return + Loading... + +} + +export default { + title: 'Services/Device Registry', + component: Test, + parameters: { actions: { argTypesRegex: '^on.*' } }, + args: {} +} as ComponentMeta + +export const Base: ComponentStory = props => { + + return + + +}; \ No newline at end of file diff --git a/webapp/src/haService/er.stories.tsx b/webapp/src/haService/er.stories.tsx new file mode 100644 index 0000000..ddc0133 --- /dev/null +++ b/webapp/src/haService/er.stories.tsx @@ -0,0 +1,45 @@ +import React, { FC } from "react"; +import { ComponentMeta, ComponentStory } from '@storybook/react'; +import { Page } from "components/Page"; +import { useHAEntityRegistry } from "haService"; +import InputYaml from "components/Inputs/InputYaml"; + +const Test: FC<{ onRender: () => void }> = ({ onRender }) => { + const conn = useHAEntityRegistry(); + onRender && onRender() + if (conn.ready) { + return
    + {conn.collection.state.length} +
      + {conn.collection.state.map((row, i) =>
    • + {/* {Object.keys(row).map(k => <> + + {k}: {JSON.stringify(row[k] as any)} +
      + )} */} + {/* { }} /> */} +
    • )} +
    +
    + } + return + Loading... + +} + +export default { + title: 'Services/Entity Registry', + component: Test, + parameters: { actions: { argTypesRegex: '^on.*' } }, + args: {} +} as ComponentMeta + +export const Base: ComponentStory = props => { + + return + + +}; \ No newline at end of file diff --git a/webapp/src/haService/index.ts b/webapp/src/haService/index.ts index 9a31e04..b927362 100644 --- a/webapp/src/haService/index.ts +++ b/webapp/src/haService/index.ts @@ -1,11 +1,14 @@ import { entitiesColl, servicesColl } from "home-assistant-js-websocket" +import { deviceRegistryColl } from "./DeviceRegistry"; +import { entityRegistryColl } from "./EntityRegistry"; +import { DeviceRegistryItem } from "./types"; import { useHassCollection } from "./useHassCollection" -export type Option = string | { +export type Option = string | ({ id: string, label: string, - domain: string, -} +} & T) +export type EntityOption = Option<{ domain: string; }> export type HAEntitiesState = ReturnType; export const useHAEntities = () => { const entities = useHassCollection(entitiesColl, state => ({ @@ -33,7 +36,7 @@ export const useHAEntities = () => { } return null }, - getOptions(restrictToDomain?: string[]): Option[] { + getOptions(restrictToDomain?: string[]): EntityOption[] { if (!entities.ready) { return [] } @@ -48,7 +51,7 @@ export const useHAEntities = () => { domain: key.split('.')[0] ?? "n/a", })) }, - getLabel: (opt: Option): string => { + getLabel: (opt: EntityOption): string => { if (typeof opt === 'string') { if (entities.ready) { return entities.collection.state[opt]?.attributes.friendly_name ?? opt; @@ -57,7 +60,7 @@ export const useHAEntities = () => { } return opt.label ?? opt.id }, - getID: (opt: Option): string => { + getID: (opt: EntityOption): string => { if (typeof opt === 'string') { return opt } @@ -74,4 +77,47 @@ export const useHAServices = () => { const services = useHassCollection(servicesColl); return services +} + +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 + } + } + return { ...dr, ...methods } +} +export const useHAEntityRegistry = () => { + const dr = useHassCollection(entityRegistryColl) + + return dr } \ No newline at end of file diff --git a/webapp/src/haService/types.ts b/webapp/src/haService/types.ts new file mode 100644 index 0000000..0256b36 --- /dev/null +++ b/webapp/src/haService/types.ts @@ -0,0 +1,40 @@ +export type EntityRegisteryItem = { + area_id: string | null; + config_entry_id: string | null; + device_id: string | null; + disabled_by: + | "integration" + | "user" + | "config_entry" + | string + | null + ; + entity_category: + | "diagnostic" + | "config" + | string + | null + ; + hidden_by: + | "integration" + | "user" + | string + | null + ; + icon: string | null; + name: string | null; + platform: string | null; +} + +export type DeviceRegistryItem = { + id: string; + name: string; + name_by_user: string | null; + manufacturer: string | null; + entry_type: 'service' | string | null; + disabled_by: EntityRegisteryItem['disabled_by']; + area_id: string | null; +} + +export type HassDevices = Array; +export type HassEntitiesRegistry = Array; \ No newline at end of file diff --git a/webapp/src/haService/useHassCollection.ts b/webapp/src/haService/useHassCollection.ts index d62c6ca..cf341fe 100644 --- a/webapp/src/haService/useHassCollection.ts +++ b/webapp/src/haService/useHassCollection.ts @@ -2,18 +2,21 @@ import { Collection, Connection } from "home-assistant-js-websocket"; import { useState, useEffect } from 'react'; import { useHAConnection } from "./connection"; -export type HACollectionState = { +type _HACollectionState = { ready: false, collection?: Collection, } | { ready: true, collection: Collection, } +export type HACollectionState = _HACollectionState & { + additional: Partial +} export const useHassCollection = ( getHACollection: (c: Connection) => Collection, updateAdditionalProps?: (n: T | {}) => D, -) => { - const [state, setState] = useState>({ +): HACollectionState => { + const [state, setState] = useState<_HACollectionState>({ ready: false }); const conn = useHAConnection(); diff --git a/webapp/src/utils/formatting.ts b/webapp/src/utils/formatting.ts index c0da063..1992ba2 100644 --- a/webapp/src/utils/formatting.ts +++ b/webapp/src/utils/formatting.ts @@ -104,7 +104,7 @@ export const getDescriptionFromAutomationNode = ( return `Trigger ${node.event}` } if ('device_id' in node) { - return `${node.type} on ${node.device_id}` + return `${node.type ?? ""} on ${node.device_id ?? ""}` } if ('choose' in node) { return "Choose"