input area

This commit is contained in:
ari committed 2022-06-16 17:24:31 -04:00
1 parent 0fc3ea6146
commit 15c97b81b4
16 files changed
+699 -416

No files matched your search

@@ -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<InputAreaProps> = (props) => {
// state
const areas = useHAAreas();
return (
<InputAutoComplete
{...props}
validateOption={(v) => areas.validateOptions(v, props.restrictToDomain)}
options={areas.getOptions(props.restrictToDomain)}
getID={areas.getID}
getLabel={areas.getLabel}
onlyShowLabel
/>
);
};
@@ -32,4 +32,10 @@
max-height: 5em;
max-width: 100%;
overflow: auto;
}
.input-autocomplete--chip small {
max-width: 7em;
text-overflow: ellipsis;
overflow: hidden;
}
@@ -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());
});
@@ -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<T = {}> = {
id: string;
label: string;
} & T;
export type Option<T = {}> = string | BaseOption<T>;
export type InputAutoCompleteProps<T extends Option<any>> = {
validateOption?: (v: string[]) => string[] | null;
groupBy?: (opt: T) => string;
@@ -18,7 +22,6 @@ export type InputAutoCompleteProps<T extends Option<any>> = {
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<T extends Option>(
props: InputAutoCompleteProps<T>
) {
@@ -120,32 +142,26 @@ export function InputAutoComplete<T extends Option>(
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<T extends Option>(
const id = getID(option);
return (
<SearchItem
key={label + id}
listProps={listProps}
id={id}
label={label}
searchTerm={inputValue}
onlyShowLabel={props.onlyShowLabel}
/>
<>
<SearchItem
key={label + id}
listProps={listProps}
id={id}
label={label}
searchTerm={inputValue}
onlyShowLabel={props.onlyShowLabel}
/>
</>
);
}}
renderInput={(params) => (
@@ -22,7 +22,6 @@ export default function InputAutoText({
endAdornment,
error,
}: InputAutoTextProps) {
console.log(options);
return (
<Autocomplete
freeSolo
+18 -13
View File
@@ -1,18 +1,23 @@
import { FC } from "react";
import { useHADeviceRegistry } from 'haService';
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete';
import { useHADeviceRegistry } from "haService";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
export type InputDeviceProps = InputAutoCompletePropsBase & { multiple?: false };
export type InputDeviceProps = InputAutoCompletePropsBase;
export const InputDevice: FC<InputDeviceProps> = props => {
// state
const dr = useHADeviceRegistry();
export const InputDevice: FC<InputDeviceProps> = (props) => {
// state
const dr = useHADeviceRegistry();
return <InputAutoComplete
{...props}
label={props.label ?? "Device ID"}
getID={dr.getID}
getLabel={dr.getLabel}
options={dr.getOptions()}
return (
<InputAutoComplete
{...props}
label={props.label ?? "Device ID"}
getID={dr.getID}
getLabel={dr.getLabel}
options={dr.getOptions()}
/>
}
);
};
@@ -226,7 +226,7 @@ const computeInvalidYaml = (
) => {
const errors = validateNode(node, allowedNodeTypes);
if (errors) {
console.log({ errors });
console.warn({ errors });
return {
node,
isErrored: true,
@@ -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<ServiceEditorFieldProps> = ({
required={isRequired}
/>
);
if (option.type === "field") {
example = option.data.example ? `Example: ${option.data.example}` : "";
if (option.data.selector?.number) {
return (
<InputNumber
className="service-editor--field"
label={label}
value={value ?? option.data.default}
min={option.data.selector.number.min}
max={option.data.selector.number.max}
step={option.data.selector.number.step}
unit={option.data.selector.number.unit_of_measurement}
onChange={onChange}
required={isRequired}
placeholder={example}
/>
);
}
if (option.data.selector?.select) {
return (
<InputAutoComplete
className="service-editor--field"
label={label}
value={value}
onChange={onChange}
endAdornment={removeIcon}
required={isRequired}
options={option.data.selector.select.options.map<Option>((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 (
<InputText
<InputNumber
className="service-editor--field"
label={label}
title={description}
helperText={description}
value={value ?? option.data.default}
min={option.data.selector.number.min}
max={option.data.selector.number.max}
step={option.data.selector.number.step}
unit={option.data.selector.number.unit_of_measurement}
onChange={onChange}
placeholder={example}
required={isRequired}
endAdornment={removeIcon}
placeholder={example}
/>
);
} else {
if (option.id === "entity") {
if ("domain" in option.data) {
return (
<InputEntity
value={value}
onChange={onChange}
className="service-editor--field"
multiple
restrictToDomain={
option.data.domain ? [option.data.domain] : undefined
}
/>
);
}
}
}
if (option.data.selector?.select) {
return (
<InputAutoComplete
className="service-editor--field"
label={label}
value={value}
onChange={onChange}
endAdornment={removeIcon}
required={isRequired}
options={option.data.selector.select.options.map<Option>((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 (
<InputText
className="service-editor--field"
label={label}
title={description}
helperText={description}
value={value ?? option.data.default}
onChange={onChange}
placeholder={example}
required={isRequired}
endAdornment={removeIcon}
/>
);
return input;
};
@@ -0,0 +1,10 @@
.service-editor--targets {
display: flex;
flex-direction: row;
gap: 1em;
padding-bottom: 0.5em;
}
.service-editor--targets>div {
flex: 1;
}
@@ -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<ServiceEditorTargetProps> = (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 (
<div className="service-editor--targets">
<InputEntity
label="Target Entities"
value={value.entity_id}
onChange={(entity_id) =>
props.onChange({
...(props.value || {}),
entity_id,
})
}
restrictToDomain={domainRestrictions}
multiple
/>
<InputDevice
label="Target Devices"
value={value.device_id}
onChange={(device_id) =>
props.onChange({
...(props.value || {}),
device_id,
})
}
multiple
/>
<InputArea
label="Target Areas"
value={value.area_id}
onChange={(area_id) =>
props.onChange({
...(props.value || {}),
area_id,
})
}
multiple
/>
</div>
);
};
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),
};
};
+17 -30
View File
@@ -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<ServiceEditorProps> = ({
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<ServiceEditorProps> = ({
<>
{options.required.map((opt) => (
<ServiceEditorField
key={opt.type + opt.id}
key={"field-" + opt.id}
option={opt}
value={data[opt.type][opt.id]}
value={data.field[opt.id]}
onChange={(v) =>
onUpdate({
...data,
[opt.type]: {
...data[opt.type],
field: {
...data.field,
[opt.id]: v,
},
})
@@ -75,28 +74,17 @@ export const ServiceEditor: FC<ServiceEditorProps> = ({
/>
))}
{hasTargets && (
<div className="service-editor--target">
{Object.keys(service.target ?? {}).map((key) => {
const targetData = (service.target as any)[key];
const option = convertTargetToOption(key, targetData);
return (
<ServiceEditorField
key={"fields-" + key}
option={option}
value={data.target[key] ?? ""}
onChange={(v) =>
onUpdate({
...data,
target: {
...data.target,
[key]: v,
},
})
}
/>
);
})}
</div>
<ServiceEditorTarget
key={"target-" + serviceId}
defn={service.target ?? {}}
value={data.target}
onChange={(target) =>
onUpdate({
...data,
target,
})
}
/>
)}
<div className="service-editor--used">
{additionalFields.field.map((key) => {
@@ -154,8 +142,7 @@ export const ServiceEditor: FC<ServiceEditorProps> = ({
...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)
),
});
}
+5 -25
View File
@@ -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<string, any>;
target: Record<string, any>;
};
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[] = [];
+142
View File
@@ -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<EntityRegisteryItem>;
}
>;
export const fetchAreaRegistry = (conn: Connection) =>
Promise.all([
conn.sendMessagePromise<AreaRegistryItem[]>({
type: "config/area_registry/list",
}),
conn.sendMessagePromise<HassEntitiesRegistry>({
type: "config/entity_registry/list",
}),
]).then(([areas, er]) => {
const areaDB = areas.reduce<AreaDB>((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<AreaDB>(conn, "_$earg", fetchAreaRegistry);
export type AreaOptionData = {
data: Partial<EntityRegisteryItem>;
};
export type AreaBaseOption = BaseOption<AreaOptionData>;
export type AreaOption = Option<AreaOptionData>;
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<string[]>((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;
};
+2 -1
View File
@@ -5,4 +5,5 @@ import { 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)
export const entityRegistryColl = (conn: Connection) => getCollection<HassEntitiesRegistry>(conn, "_$erc", fetchEntityRegistry)
+266 -238
View File
@@ -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<T = {}> = {
id: string,
label: string,
} & T
export type Option<T = {}> = string | BaseOption<T>;
export type EntityOption = Option<{ domain: string; }>
export type EntityOption = Option<{ domain: string }>;
export type HAEntitiesState = ReturnType<typeof useHAEntities>;
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<string[]>((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<string[]>((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<typeof useHAServices>;
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<ServiceOption[]>(
(all, domain) => {
const opts = Object.keys(
services.collection.state[domain]
).map<ServiceOption>((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<ServiceOption[]>((all, domain) => {
const opts = Object.keys(services.collection.state[domain]).map<ServiceOption>(
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")
}
}
return {
entities,
devices,
services,
namer,
callService,
reloadAutomations: () => callService("automation", "reload"),
};
};
+8 -7
View File
@@ -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 = {