device id

This commit is contained in:
ari committed 2022-05-30 19:48:55 -04:00
1 parent 8a90b56ac3
commit f1b24ec783
17 files changed
+438 -65

No files matched your search

@@ -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<typeof InputDevice>;
const Template: ComponentStory<typeof InputDevice> = args => {
const [value, setValue] = useState(args.value)
return <Page>
<div style={{
maxWidth: 200
}}>
<InputDevice {...args} value={value as any} onChange={(v: any) => {
setValue(v)
args.onChange(v as any)
}} />
</div>
</Page>
}
export const Single = Template.bind({})
Single.args = {
...Single.args,
multiple: false,
value: 'sensor.bathroom'
} as any
@@ -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<InputEntityProps> = 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 <Autocomplete
className="input-entities"
multiple={true}
freeSolo
value={value}
options={options}
onChange={onChange}
getOptionLabel={dr.getLabel}
groupBy={opt => (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 <SearchItem
listProps={prop}
id={id}
label={label}
searchTerm={inputValue}
/>
}}
renderInput={params => <TextField
{...params}
variant="filled"
label={props.label ?? "Device"}
/>}
renderTags={(tagValue, getTagProps) => <Badge badgeContent={tagValue.length} color="info">
<div className="input-entities--tags">
{tagValue.map((option, index) => {
const label = dr.getLabel(option);
const id = dr.getID(option);
const props = getTagProps({ index });
props.className += ' input-entities--chip'
return (
<Chip
size="medium"
label={<>
{(id === label) ? <span>{label}</span> : <b>{label}</b>}
{(id !== label) && <small>{id}</small>}
</>}
{...props}
/>
)
})}
</div>
</Badge>
}
/>
}
@@ -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: "/ ";
}
+1 -44
View File
@@ -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<InputEntityProps> = 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) => (
<span
key={index}
style={{
textDecoration: part.highlight ? 'underline' : 'unset'
}}
>
{part.text}
</span>
))}
</>
}
export const SearchItem: FC<{
listProps: React.HTMLAttributes<HTMLLIElement>,
label: string,
id: string,
searchTerm: string,
}> = ({
listProps,
label,
id,
searchTerm
}) => <li {...listProps} className={[listProps.className ?? "", 'input-entities--list'].join(' ')}>
<b><HighlightElm text={label} searchTerm={searchTerm} /></b> <small>
<HighlightElm text={id} searchTerm={searchTerm} />
</small>
</li>
@@ -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: {}
+9
View File
@@ -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: "/ ";
}
+47
View File
@@ -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) => (
<span
key={index}
style={{
textDecoration: part.highlight ? 'underline' : 'unset'
}}
>
{part.text}
</span>
))}
</>
}
export const SearchItem: FC<{
listProps: React.HTMLAttributes<HTMLLIElement>,
label: string,
id: string,
searchTerm: string,
}> = ({
listProps,
label,
id,
searchTerm
}) => <li {...listProps} className={[listProps.className ?? "", 'input-extras--search-item--list'].join(' ')}>
<b><HighlightElm text={label} searchTerm={searchTerm} /></b> <small>
<HighlightElm text={id} searchTerm={searchTerm} />
</small>
</li>
@@ -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<DeviceAction> = {
defaultState: () => ({
alias: "",
device_id: ""
}),
isReady: () => true,
renderOptionList: (state, setState) => {
renderOptionList: (state, setState, entities) => {
console.log(entities.collection?.state)
const update = updateActionData(state, setState);
return <>
<InputText
textBoxFor="device_id"
label="Device"
<InputDevice
value={state.device_id ?? ""}
onChange={device_id => update({ device_id })}
onChange={device_id => update({ device_id: device_id ?? "" })}
/>
<InputText
textBoxFor="type"
@@ -3,6 +3,7 @@ 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';
export const TriggerDevice: OptionManager<AutomationTriggerDevice> = {
@@ -24,9 +25,9 @@ export const TriggerDevice: OptionManager<AutomationTriggerDevice> = {
...state,
subtype
})} />
<InputText label="Device" value={state.device_id ?? ""} onChange={device_id => setState({
<InputDevice value={state.device_id ?? ""} onChange={device_id => setState({
...state,
device_id
device_id: device_id ?? "",
})} />
<InputEntity restrictToDomain={state.domain ? [state.domain] : undefined} value={state.entity_id ?? ""} multiple onChange={entity_id => setState({
...state,
+21
View File
@@ -0,0 +1,21 @@
import { Connection, getCollection } from "home-assistant-js-websocket";
import { DeviceRegistryItem, HassDevices } from './types';
export const fetchDeviceRegistry = (conn: Connection): Promise<Record<string, DeviceRegistryItem>> =>
conn.sendMessagePromise<HassDevices>({
"type": "config/device_registry/list"
}).then(
data =>
data.filter(
({ disabled_by }) => !disabled_by
).reduce<Record<string, DeviceRegistryItem>>((all, n) => {
all[n.id] = n
return all
}, {}
))
export const deviceRegistryColl = (conn: Connection) => getCollection<Record<string, DeviceRegistryItem>>(
conn,
"_$drc",
fetchDeviceRegistry
)
+8
View File
@@ -0,0 +1,8 @@
import { Connection, getCollection } from "home-assistant-js-websocket";
import { HassDevices, HassEntitiesRegistry } from './types';
export const fetchEntityRegistry = (conn: Connection) => conn.sendMessagePromise<HassEntitiesRegistry>({
"type": "config/entity_registry/list"
}).then(data => data.filter(({ disabled_by }) => !disabled_by))
export const entityRegistryColl = (conn: Connection) => getCollection<HassEntitiesRegistry>(conn, "_$erc", fetchEntityRegistry)
+42
View File
@@ -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 <div>
{Object.keys(conn.collection.state).length} items
<ul style={{
maxHeight: '100vh',
overflow: 'auto'
}}>
{Object.keys(conn.collection.state).map(k => <li key={k}>
<b>{k}</b>
{/* <u>{conn.collection.state[k].length > 1 ? conn.collection.state[k].length : ''}</u> */}
<InputYaml value={conn.collection.state[k]} onChange={() => { }} label={k} />
</li>)}
</ul>
</div>
}
return <code>
Loading...
</code>
}
export default {
title: 'Services/Device Registry',
component: Test,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {}
} as ComponentMeta<typeof Test>
export const Base: ComponentStory<typeof Test> = props => {
return <Page>
<Test {...props} />
</Page>
};
+45
View File
@@ -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 <div>
{conn.collection.state.length}
<ul style={{
maxHeight: '100vh',
overflow: 'auto'
}}>
{conn.collection.state.map((row, i) => <li key={i}>
{/* {Object.keys(row).map(k => <>
<span key={k}>
<b>{k}</b>: {JSON.stringify(row[k] as any)}
</span><br key={`${k}-br`} />
</>)} */}
{/* <InputYaml label={String(i)} value={row} onChange={() => { }} /> */}
</li>)}
</ul>
</div>
}
return <code>
Loading...
</code>
}
export default {
title: 'Services/Entity Registry',
component: Test,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {}
} as ComponentMeta<typeof Test>
export const Base: ComponentStory<typeof Test> = props => {
return <Page>
<Test {...props} />
</Page>
};
+52 -6
View File
@@ -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<T = {}> = string | ({
id: string,
label: string,
domain: string,
}
} & T)
export type EntityOption = Option<{ domain: string; }>
export type HAEntitiesState = ReturnType<typeof useHAEntities>;
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
}
+40
View File
@@ -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<DeviceRegistryItem>;
export type HassEntitiesRegistry = Array<EntityRegisteryItem>;
+6 -3
View File
@@ -2,18 +2,21 @@ import { Collection, Connection } from "home-assistant-js-websocket";
import { useState, useEffect } from 'react';
import { useHAConnection } from "./connection";
export type HACollectionState<T> = {
type _HACollectionState<T> = {
ready: false,
collection?: Collection<T>,
} | {
ready: true,
collection: Collection<T>,
}
export type HACollectionState<T, D = {}> = _HACollectionState<T> & {
additional: Partial<D>
}
export const useHassCollection = <T, D extends {} = {}>(
getHACollection: (c: Connection) => Collection<T>,
updateAdditionalProps?: (n: T | {}) => D,
) => {
const [state, setState] = useState<HACollectionState<T>>({
): HACollectionState<T, D> => {
const [state, setState] = useState<_HACollectionState<T>>({
ready: false
});
const conn = useHAConnection();
+1 -1
View File
@@ -104,7 +104,7 @@ export const getDescriptionFromAutomationNode = <N extends AutomationNodeTypes>(
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"