From 996626f9af4f9f184f6e0cbe7e542e84d27aec3c Mon Sep 17 00:00:00 2001 From: Ari Date: Mon, 30 May 2022 15:05:54 -0400 Subject: [PATCH] input entities --- webapp/package.json | 4 +- .../ConditionEditor/editorRender.tsx | 5 +- .../src/components/Inputs/InputEntities.css | 35 ++++ .../src/components/Inputs/InputEntities.tsx | 181 ++++++++++++++++++ .../Inputs/InputEntityID.stories.tsx | 84 ++++++++ .../InputEntityIDSearchItem.stories.tsx | 28 +++ webapp/src/components/Inputs/InputList.tsx | 22 --- .../Inputs/InputTextBubble.stories.tsx | 12 +- .../src/components/Inputs/InputTextBubble.tsx | 30 ++- .../NodeEditor/OptionManager/ActionDevice.tsx | 5 +- .../NodeEditor/OptionManager/OptionManager.ts | 3 +- .../OptionManager/TriggerDevice.tsx | 16 +- .../OptionManager/TriggerNumericState.tsx | 3 +- .../NodeEditor/OptionManager/TriggerState.tsx | 3 +- .../NodeEditor/OptionManager/TriggerZone.tsx | 9 +- .../NodeEditor/OptionManager/index.tsx | 4 +- .../components/NodeEditor/index.stories.tsx | 8 + webapp/src/haService/connection.stories.tsx | 27 +++ webapp/src/haService/connection.ts | 46 ++++- webapp/src/haService/entities.stories.tsx | 26 +++ webapp/src/haService/index.ts | 76 +++++++- webapp/src/haService/useHassCollection.ts | 22 ++- webapp/src/types/automations/common.ts | 1 + webapp/src/types/validators/triggers.ts | 7 +- webapp/src/utils/formatting.test.ts | 9 +- webapp/src/utils/formatting.ts | 5 + webapp/yarn.lock | 17 ++ 27 files changed, 596 insertions(+), 92 deletions(-) create mode 100644 webapp/src/components/Inputs/InputEntities.css create mode 100644 webapp/src/components/Inputs/InputEntities.tsx create mode 100644 webapp/src/components/Inputs/InputEntityID.stories.tsx create mode 100644 webapp/src/components/Inputs/InputEntityIDSearchItem.stories.tsx create mode 100644 webapp/src/haService/connection.stories.tsx create mode 100644 webapp/src/haService/entities.stories.tsx diff --git a/webapp/package.json b/webapp/package.json index a04acca..eecb93b 100644 --- a/webapp/package.json +++ b/webapp/package.json @@ -13,6 +13,7 @@ "@types/react": "^17.0.0", "@types/react-dom": "^17.0.0", "@uiw/react-codemirror": "^4.7.0", + "autosuggest-highlight": "^3.2.1", "home-assistant-js-websocket": "^7.1.0", "jss": "^10.8.2", "react": "^17.0.2", @@ -78,6 +79,7 @@ "@testing-library/jest-dom": "^5.11.4", "@testing-library/react": "^11.1.0", "@testing-library/user-event": "^12.1.10", + "@types/autosuggest-highlight": "^3.2.0", "@types/chroma-js": "^2.1.3", "@types/js-yaml": "^4.0.5", "jest-environment-jsdom": "^27.5.1", @@ -87,4 +89,4 @@ "node_modules", "src" ] -} \ No newline at end of file +} diff --git a/webapp/src/components/ConditionEditor/editorRender.tsx b/webapp/src/components/ConditionEditor/editorRender.tsx index e33f65d..dc88075 100644 --- a/webapp/src/components/ConditionEditor/editorRender.tsx +++ b/webapp/src/components/ConditionEditor/editorRender.tsx @@ -2,7 +2,7 @@ import { FC } from "react"; import { AutomationCondition, LogicCondition, NumericCondition, StateCondition, TemplateCondition, TimeCondition, TriggerCondition, ZoneCondition } from 'types/automations/conditions'; import InputNumber from "components/Inputs/InputNumber"; import InputText from "components/Inputs/InputText"; -import { InputEntity } from "components/Inputs/InputTextBubble"; +import { InputEntity } from "components/Inputs/InputEntities"; import { ConditionNode } from "./ConditionNode"; import { genUpdateMethods } from "./nestedUpdater"; import InputTime from "components/Inputs/InputTime"; @@ -60,6 +60,7 @@ export const NumericStateEditor: Editor = ({ return <> onChange({ ...condition, entity_id @@ -120,6 +121,7 @@ export const StateEditor: Editor = ({ return <> onChange({ ...condition, entity_id @@ -196,6 +198,7 @@ export const ZoneEditor: Editor = ({ })} /> onChange({ ...condition, entity_id diff --git a/webapp/src/components/Inputs/InputEntities.css b/webapp/src/components/Inputs/InputEntities.css new file mode 100644 index 0000000..80e78f7 --- /dev/null +++ b/webapp/src/components/Inputs/InputEntities.css @@ -0,0 +1,35 @@ +.input-entities .BaseBadge-root { + max-width: 100%; +} + +.input-entities--list, .input-entities--chip>span { + display: flex; + flex-direction: row; + gap: 0.15em; +} + +.input-entities--list>small::before, .input-entities--chip>span>small::before { + content: "/ "; +} + +.input-entities--chip>span>small { + size: 0.15em; +} + +.input-entities--errors { + margin-top: 0.75em; +} + +.input-entities--errors ul { + padding: 0 0 0 1em; + margin: 0; + max-height: 2.5em; + overflow-y: auto; + overflow-x: hidden; +} + +.input-entities--tags { + max-height: 5em; + max-width: 100%; + overflow: auto; +} \ No newline at end of file diff --git a/webapp/src/components/Inputs/InputEntities.tsx b/webapp/src/components/Inputs/InputEntities.tsx new file mode 100644 index 0000000..a56942a --- /dev/null +++ b/webapp/src/components/Inputs/InputEntities.tsx @@ -0,0 +1,181 @@ +import "./InputEntities.css"; +import { FC } from "react"; +import { useHAEntities } from 'haService'; +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"; + +export type InputEntityProps = { + restrictToDomain?: string[], + label?: string, +} & ({ + value: string | null; + multiple?: false; + onChange: (v: string | null) => void; +} | { + value: EntityId; + multiple: true; + onChange: (v: string[]) => void; +}) + +export const InputEntity: FC = props => { + // state + const entities = useHAEntities(); + + // processing of inputs + const options = entities.getOptions(props.restrictToDomain); + const value = Array.isArray(props.value) ? props.value : !!props.value ? [props.value] : []; + const errors = entities.validateOptions(value, props.restrictToDomain); + + // processing of errors + let helperText = <>; + let error: boolean = false; + if (errors !== null) { + error = true + if (errors.length > 0) { + helperText = +
    {errors.map((msg, i) =>
  • + {msg} +
  • )}
+
+ } + } + // 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 { + const searchTerm = s.inputValue.toLocaleLowerCase(); + return opts.map(opt => { + let similarityScore = 0; + const eid = entities.getID(opt); + if (eid.toLocaleLowerCase().includes(searchTerm)) { + similarityScore = Math.abs(eid.length - searchTerm.length) + } + const name = entities.getLabel(opt); + if (name.toLocaleLowerCase().includes(searchTerm)) { + similarityScore = Math.abs(eid.length - searchTerm.length) + } + return { + label: name, + id: eid, + domain: (typeof opt === 'string') ? '' : opt.domain, + similarityScore + } + }).filter(opt => opt.similarityScore > 0).sort((a, b) => { + return (a.similarityScore > b.similarityScore) ? 1 : -1 + }) + }} + groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''} + renderOption={(prop, option, { inputValue }) => { + const label = entities.getLabel(option); + const id = entities.getID(option); + + return + }} + renderInput={params => } + renderTags={(tagValue, getTagProps) => +
+ {tagValue.map((option, index) => { + const label = entities.getLabel(option); + const id = entities.getID(option); + const props = getTagProps({ index }); + props.className += ' input-entities--chip' + return ( + + {(id === label) ? {label} : {label}} + {(id !== label) && {id}} + } + {...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/InputEntityID.stories.tsx b/webapp/src/components/Inputs/InputEntityID.stories.tsx new file mode 100644 index 0000000..7742541 --- /dev/null +++ b/webapp/src/components/Inputs/InputEntityID.stories.tsx @@ -0,0 +1,84 @@ +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { Page } from "components/Page"; +import { useState } from "react"; + +import { InputEntity } from "./InputEntities"; + +export default { + title: 'Inputs/InputEntity', + component: InputEntity, + 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 + +export const Many = Template.bind({}) +Many.args = { + ...Many.args, + multiple: true, + value: ['sensor.bathroom', 'person.ari'] +} as any + +export const ManyEmpty = Template.bind({}) +ManyEmpty.args = { + ...ManyEmpty.args, + multiple: true, + value: [] +} as any + + +export const ManyButGotSingle = Template.bind({}) +ManyButGotSingle.args = { + ...ManyButGotSingle.args, + multiple: true, + value: 'sensor.bathroom' +} as any + + +export const InvalidDomain = Template.bind({}) +InvalidDomain.args = { + ...InvalidDomain.args, + multiple: true, + value: 'sensor.bathroom', + restrictToDomain: ['zone'], +} as any + + +export const InvalidManyDomain = Template.bind({}) +InvalidManyDomain.args = { + ...InvalidManyDomain.args, + multiple: true, + value: 'sensor.bathroom', + restrictToDomain: ['zone', 'switch'], +} as any + +export const InvalidLots = Template.bind({}) +InvalidLots.args = { + ...InvalidLots.args, + multiple: true, + value: ['person.ari', 'sensor.bathroom', 'binary_sensor.ping_tv', 'device_tracker.phone'], + restrictToDomain: ['zone', 'switch'], +} as any diff --git a/webapp/src/components/Inputs/InputEntityIDSearchItem.stories.tsx b/webapp/src/components/Inputs/InputEntityIDSearchItem.stories.tsx new file mode 100644 index 0000000..e682443 --- /dev/null +++ b/webapp/src/components/Inputs/InputEntityIDSearchItem.stories.tsx @@ -0,0 +1,28 @@ +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { Page } from "components/Page"; + +import { SearchItem } from "./InputEntities"; + +export default { + title: 'Inputs/InputEntity/SearchItem', + component: SearchItem, + parameters: { actions: { argTypesRegex: '^on.*' } }, + argTypes: {} +} as ComponentMeta; + + + +const Template: ComponentStory = args => { + return + + + +} + +export const Simple = Template.bind({}) +Simple.args = { + id: "sensor.humidity_main_bedroom", + label: 'Main Bedroom Humidity', + searchTerm: "bedroom", + listProps: {}, +} as any diff --git a/webapp/src/components/Inputs/InputList.tsx b/webapp/src/components/Inputs/InputList.tsx index 7a837dc..6cf77b2 100644 --- a/webapp/src/components/Inputs/InputList.tsx +++ b/webapp/src/components/Inputs/InputList.tsx @@ -49,26 +49,4 @@ export const InputList: FC> = ({ {invalidCurrent ? `'${current}' is not a valid selection` : ''} - // return - // - // } diff --git a/webapp/src/components/Inputs/InputTextBubble.stories.tsx b/webapp/src/components/Inputs/InputTextBubble.stories.tsx index a2cace8..6ab4326 100644 --- a/webapp/src/components/Inputs/InputTextBubble.stories.tsx +++ b/webapp/src/components/Inputs/InputTextBubble.stories.tsx @@ -2,7 +2,7 @@ import { ComponentMeta, ComponentStory } from "@storybook/react"; import { Page } from "components/Page"; import { useState } from "react"; -import InputTextBubble, { InputEntity } from "./InputTextBubble"; +import InputTextBubble from "./InputTextBubble"; export default { title: 'Inputs/InputTextBubble', @@ -34,16 +34,6 @@ export const JustText: ComponentStory = args => { } - -export const EntityId: ComponentStory = args => { - - const [value, setValue] = useState(['sensor.bathroom']) - return - - -} - - export const ManyOptions: ComponentStory = args => { const [value, setValue] = useState('hello') diff --git a/webapp/src/components/Inputs/InputTextBubble.tsx b/webapp/src/components/Inputs/InputTextBubble.tsx index d91a1d6..fe10fbf 100644 --- a/webapp/src/components/Inputs/InputTextBubble.tsx +++ b/webapp/src/components/Inputs/InputTextBubble.tsx @@ -5,28 +5,36 @@ import { FC } from "react"; export interface Props { label: string; - value: string | string[]; + value?: string | string[]; options?: string[]; onChange: (v: string[]) => void; + maxAllowed?: number; } export default function InputTextBubble({ value = "", label, options = [], onChange, + maxAllowed, }: Props) { - const selected = Array.isArray(value) ? value : [value]; + const selected = Array.isArray(value) ? value : value ? [value] : []; return onChange( - v === null ? [] : + onChange={(_e, v) => { + let cleanValue = v === null ? [] : Array.isArray(v) ? v : [v] - )} + + if (maxAllowed) { + cleanValue = cleanValue.slice(0, maxAllowed); + } + + onChange(cleanValue) + }} renderInput={params => } - -export const InputEntity: FC<{ - value: string | string[]; - onChange: (v: string[]) => void; -}> = ({ - value, - onChange, -}) => diff --git a/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx b/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx index 8315e92..ebf5599 100644 --- a/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx @@ -1,3 +1,4 @@ +import { InputEntity } from "components/Inputs/InputEntities"; import InputText from "components/Inputs/InputText"; import { DeviceAction } from "types/automations/actions"; import { OptionManager, updateActionData } from './OptionManager'; @@ -39,9 +40,7 @@ export const ActionDeviceState: OptionManager = { value={state.type} onChange={type => update({ type })} /> - update({ entity_id, domain: entity_id.split('.')[0] })} /> diff --git a/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts b/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts index afcff06..4f40710 100644 --- a/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts +++ b/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts @@ -1,9 +1,10 @@ +import { HAEntitiesState } from 'haService'; import { AutomationAction } from 'types/automations/actions'; import { AutomationCondition } from 'types/automations/conditions'; export interface OptionManager { defaultState(): T; isReady(s: T): boolean; - renderOptionList(s: T, set: (s: T) => void): JSX.Element; + renderOptionList(s: T, set: (s: T) => void, entities: HAEntitiesState): JSX.Element; } diff --git a/webapp/src/components/NodeEditor/OptionManager/TriggerDevice.tsx b/webapp/src/components/NodeEditor/OptionManager/TriggerDevice.tsx index 6fdc7df..6a68e12 100644 --- a/webapp/src/components/NodeEditor/OptionManager/TriggerDevice.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/TriggerDevice.tsx @@ -1,24 +1,20 @@ import { OptionManager } from './OptionManager'; import { AutomationTriggerDevice } from 'types/automations/triggers'; import InputText from 'components/Inputs/InputText'; -import { InputEntity } from 'components/Inputs/InputTextBubble'; +import { InputEntity } from 'components/Inputs/InputEntities'; +import InputTextBubble from 'components/Inputs/InputTextBubble'; export const TriggerDevice: OptionManager = { defaultState: () => ({ "platform": 'device', - "domain": "", - "type": "", - "subtype": "", - "device_id": "", - "entity_id": "", }), isReady: () => true, - renderOptionList: (state, setState) => { + renderOptionList: (state, setState, { getDomainList }) => { return <> - setState({ + setState({ ...state, - domain + domain: domain ? domain[0] : "", })} /> setState({ ...state, @@ -32,7 +28,7 @@ export const TriggerDevice: OptionManager = { ...state, device_id })} /> - setState({ + setState({ ...state, entity_id })} /> diff --git a/webapp/src/components/NodeEditor/OptionManager/TriggerNumericState.tsx b/webapp/src/components/NodeEditor/OptionManager/TriggerNumericState.tsx index a3085c4..5bfc96e 100644 --- a/webapp/src/components/NodeEditor/OptionManager/TriggerNumericState.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/TriggerNumericState.tsx @@ -1,7 +1,7 @@ import { OptionManager } from './OptionManager'; import { AutomationTriggerNumericState } from 'types/automations/triggers'; import InputText from 'components/Inputs/InputText'; -import { InputEntity } from 'components/Inputs/InputTextBubble'; +import { InputEntity } from 'components/Inputs/InputEntities'; import InputNumber from 'components/Inputs/InputNumber'; import InputTime from 'components/Inputs/InputTime'; import InputYaml from 'components/Inputs/InputYaml'; @@ -17,6 +17,7 @@ export const TriggerNumericState: OptionManager = return <> setState({ ...state, entity_id diff --git a/webapp/src/components/NodeEditor/OptionManager/TriggerState.tsx b/webapp/src/components/NodeEditor/OptionManager/TriggerState.tsx index 2e46360..55f6b51 100644 --- a/webapp/src/components/NodeEditor/OptionManager/TriggerState.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/TriggerState.tsx @@ -1,7 +1,7 @@ import { OptionManager } from './OptionManager'; import { AutomationTriggerState } from 'types/automations/triggers'; import InputText from 'components/Inputs/InputText'; -import { InputEntity } from 'components/Inputs/InputTextBubble'; +import { InputEntity } from 'components/Inputs/InputEntities'; import InputTime from 'components/Inputs/InputTime'; @@ -15,6 +15,7 @@ export const TriggerState: OptionManager = { return <> setState({ ...state, entity_id diff --git a/webapp/src/components/NodeEditor/OptionManager/TriggerZone.tsx b/webapp/src/components/NodeEditor/OptionManager/TriggerZone.tsx index 9451b38..fd8390a 100644 --- a/webapp/src/components/NodeEditor/OptionManager/TriggerZone.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/TriggerZone.tsx @@ -1,8 +1,7 @@ import { OptionManager } from './OptionManager'; import { AutomationTriggerZone } from 'types/automations/triggers'; -import InputText from 'components/Inputs/InputText'; import { InputList } from 'components/Inputs/InputList'; -import { InputEntity } from 'components/Inputs/InputTextBubble'; +import { InputEntity } from 'components/Inputs/InputEntities'; export const TriggerZone: OptionManager = { @@ -15,9 +14,9 @@ export const TriggerZone: OptionManager = { isReady: () => true, renderOptionList: (state, setState) => { return <> - setState({ + setState({ ...state, - zone + zone: zone ?? "" })} /> = { })} /> setState({ ...state, diff --git a/webapp/src/components/NodeEditor/OptionManager/index.tsx b/webapp/src/components/NodeEditor/OptionManager/index.tsx index 253362b..49d93b3 100644 --- a/webapp/src/components/NodeEditor/OptionManager/index.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/index.tsx @@ -6,6 +6,7 @@ import { getNodeType, getNodeSubType, getSubTypeList, validateNode } from 'utils import InputYaml from 'components/Inputs/InputYaml'; import InputText from 'components/Inputs/InputText'; import { getDescriptionFromAutomationNode } from 'utils/formatting'; +import { useHAEntities } from 'haService'; type UseState = (s: S) => [S, Dispatch>] @@ -15,6 +16,7 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool isModified: false, ...computeInvalidYaml(originalNode) }); + const entities = useHAEntities(); const { node: currentNode, isModified, yamlMode, invalidManualYaml } = allState; useEffect(() => { setAllState({ ...allState, node: originalNode, isModified: false, }) @@ -93,7 +95,7 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool } return <> {aliasEditor} - {optionManager.renderOptionList(currentNode, setState)} + {optionManager.renderOptionList(currentNode, setState, entities)} ; }, isReady() { diff --git a/webapp/src/components/NodeEditor/index.stories.tsx b/webapp/src/components/NodeEditor/index.stories.tsx index 769bd08..f7e0f2c 100644 --- a/webapp/src/components/NodeEditor/index.stories.tsx +++ b/webapp/src/components/NodeEditor/index.stories.tsx @@ -65,6 +65,14 @@ UnSupported.args = { } as any, } +export const DeviceTriggerExample = Action.bind({}) +DeviceTriggerExample.args = { + ...DeviceTriggerExample.args, + node: { + "platform": 'device', + }, +} + export const InAModal: ComponentStory = props => { diff --git a/webapp/src/haService/connection.stories.tsx b/webapp/src/haService/connection.stories.tsx new file mode 100644 index 0000000..807430a --- /dev/null +++ b/webapp/src/haService/connection.stories.tsx @@ -0,0 +1,27 @@ +import React, { FC } from "react"; +import { ComponentMeta, ComponentStory } from '@storybook/react'; +import { Page } from "components/Page"; +import { useHAConnection } from './connection'; + +const Test: FC = () => { + const conn = useHAConnection(); + + return + {JSON.stringify(conn, null, 4)} + +} + +export default { + title: 'Services/HA Service', + 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/connection.ts b/webapp/src/haService/connection.ts index dcfb8ed..5a2105c 100644 --- a/webapp/src/haService/connection.ts +++ b/webapp/src/haService/connection.ts @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { getAuth, createConnection, @@ -6,8 +6,11 @@ import { createLongLivedTokenAuth, Auth, Connection, + ERR_CANNOT_CONNECT, + ERR_CONNECTION_LOST, + ERR_INVALID_AUTH, + ERR_INVALID_HTTPS_TO_HTTP, } from "home-assistant-js-websocket"; -import { useDelayEffect } from 'utils/useDelay'; const HASS_URL = process.env.REACT_APP_HASS_URL as string; const HASS_TOKEN = process.env.REACT_APP_HASS_TOKEN; @@ -24,6 +27,25 @@ let haConnection: HAConnection = { status: 'loading', }; +const translateErrorCodes = (errorCode: number) => { + if (errorCode === ERR_HASS_HOST_REQUIRED) { + return "Missing HASS host" + } + if (errorCode === ERR_CANNOT_CONNECT) { + return "Failed to connect" + } + if (errorCode === ERR_CONNECTION_LOST) { + return "Connection Lost" + } + if (errorCode === ERR_INVALID_AUTH) { + return "Invalid Host" + } + if (errorCode === ERR_INVALID_HTTPS_TO_HTTP) { + return "Invalid https to http" + } + return errorCode; +} + const createAuth = async () => { console.log("detecting auth") let auth: Auth @@ -61,7 +83,7 @@ async function startHAConnection() { } catch (error) { haConnection = { status: 'error', - error, + error: translateErrorCodes(error), } throw error } @@ -70,10 +92,24 @@ async function startHAConnection() { startHAConnection().then(console.log).catch(console.error); export const useHAConnection = (): HAConnection => { const [conn, setConn] = useState(haConnection); - useDelayEffect(() => { + const timeID = useRef(undefined); + console.log("connecting to HA") + useEffect(() => { + console.log('connection state', conn.status) if (conn.status !== haConnection.status) { setConn(haConnection); } - }, [conn], conn.status === 'loading' ? 500 : 50000); + const waiter = () => { + if (conn.status !== haConnection.status) { + console.log('setting status', conn.status, haConnection.status) + setConn(haConnection); + } + timeID.current = window.setTimeout(() => { + waiter() + }, conn.status === 'loading' ? 500 : 5000) + } + waiter() + return () => window.clearTimeout(timeID.current) + }, [conn, setConn]) return conn; }; \ No newline at end of file diff --git a/webapp/src/haService/entities.stories.tsx b/webapp/src/haService/entities.stories.tsx new file mode 100644 index 0000000..c4fd842 --- /dev/null +++ b/webapp/src/haService/entities.stories.tsx @@ -0,0 +1,26 @@ +import React, { FC } from "react"; +import { ComponentMeta, ComponentStory } from '@storybook/react'; +import { Page } from "components/Page"; +import { useHAEntities } from "haService"; + +const Test: FC<{ onRender: () => void }> = ({ onRender }) => { + const conn = useHAEntities(); + onRender && onRender() + return + {JSON.stringify(conn, null, 4)} + +} + +export default { + title: 'Services/HA Entities', + component: Test, + parameters: { actions: { argTypesRegex: '^on.*' } }, + args: {} +} as ComponentMeta + +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 0c4fc0a..9a31e04 100644 --- a/webapp/src/haService/index.ts +++ b/webapp/src/haService/index.ts @@ -1,13 +1,77 @@ import { entitiesColl, servicesColl } from "home-assistant-js-websocket" import { useHassCollection } from "./useHassCollection" +export type Option = string | { + id: string, + label: string, + 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[]): Option[] { + 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: Option): 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: Option): string => { + if (typeof opt === 'string') { + return opt + } + return opt.id + } + } + return { + ...entities, + ...methods + } +} -export const useHAService = () => { - const entities = useHassCollection(entitiesColl); +export const useHAServices = () => { const services = useHassCollection(servicesColl); - return { - entities, - services, - } + return services } \ No newline at end of file diff --git a/webapp/src/haService/useHassCollection.ts b/webapp/src/haService/useHassCollection.ts index 215d460..d62c6ca 100644 --- a/webapp/src/haService/useHassCollection.ts +++ b/webapp/src/haService/useHassCollection.ts @@ -9,7 +9,10 @@ export type HACollectionState = { ready: true, collection: Collection, } -export const useHassCollection = (getHACollection: (c: Connection) => Collection) => { +export const useHassCollection = ( + getHACollection: (c: Connection) => Collection, + updateAdditionalProps?: (n: T | {}) => D, +) => { const [state, setState] = useState>({ ready: false }); @@ -22,21 +25,32 @@ export const useHassCollection = (getHACollection: (c: Connection) => Collect ready: false, collection, }) - return collection.subscribe(d => { + const unsub = collection.subscribe(d => { if (d && !state.ready) { setState({ ready: true, collection, }) + unsub(); } else if (!d && state.ready) { setState({ ready: true, collection, }) + unsub(); } - }) + }); + return unsub } }, [conn, getHACollection, state.ready]); - return state; + return { + ...state, + get additional(): Partial { + if (state.ready && updateAdditionalProps) { + return updateAdditionalProps(state.collection.state) + } + return {} + } + } } \ No newline at end of file diff --git a/webapp/src/types/automations/common.ts b/webapp/src/types/automations/common.ts index 34c8e15..b7a5352 100644 --- a/webapp/src/types/automations/common.ts +++ b/webapp/src/types/automations/common.ts @@ -4,3 +4,4 @@ import * as v from "types/validators/common"; export type AutomationTime = st.Infer export type AutomationTimeObject = st.Infer export type AutomationTimeString = st.Infer +export type EntityId = st.Infer; \ No newline at end of file diff --git a/webapp/src/types/validators/triggers.ts b/webapp/src/types/validators/triggers.ts index 75b153a..cfa0f3b 100644 --- a/webapp/src/types/validators/triggers.ts +++ b/webapp/src/types/validators/triggers.ts @@ -4,6 +4,7 @@ import { AutomationTimeString, AutomationTime, EntityId } from './common' const AutomationTriggerBase = { id: st.optional(st.string()), + enabled: st.optional(st.boolean()), } export const AutomationTriggerEvent = st.type({ @@ -95,9 +96,9 @@ export const AutomationTriggerDevice = st.type({ ...AutomationTriggerBase, platform: st.literal('device'), entity_id: st.optional(EntityId), - device_id: st.string(), - domain: st.string(), - type: st.string(), + device_id: st.optional(st.string()), + domain: st.optional(st.string()), + type: st.optional(st.string()), subtype: st.optional(st.string()), }) diff --git a/webapp/src/utils/formatting.test.ts b/webapp/src/utils/formatting.test.ts index 6c431a8..1469f32 100644 --- a/webapp/src/utils/formatting.test.ts +++ b/webapp/src/utils/formatting.test.ts @@ -1,5 +1,5 @@ -import { convertTimeToString, getDescriptionFromAutomationNode } from "./formatting"; +import { convertTimeToString, getDescriptionFromAutomationNode, prettyName } from "./formatting"; test('converting time to a string', () => { expect(convertTimeToString({ hours: 1 })).toEqual('01:00:00:00') @@ -146,3 +146,10 @@ test('get State condition description', () => { state: "on" })).toEqual("switch.kitchen_light is 'on'") }) + + +test('pretty naming', () => { + expect(prettyName('sensor')).toEqual("Sensor") + expect(prettyName('sensor.phone')).toEqual("Sensor Phone") + expect(prettyName('device_tracker')).toEqual("Device Tracker") +}) \ No newline at end of file diff --git a/webapp/src/utils/formatting.ts b/webapp/src/utils/formatting.ts index 2945dad..c0da063 100644 --- a/webapp/src/utils/formatting.ts +++ b/webapp/src/utils/formatting.ts @@ -121,3 +121,8 @@ export const prettyEntityId = (entityId: string | string[]) => { return "..." } } + +export const prettyName = (n: string) => { + const clean = n.replaceAll(/[\.-_]/g, ' '); + return clean.split(' ').map(x => x.slice(0, 1).toUpperCase() + x.slice(1)).join(' ') +} \ No newline at end of file diff --git a/webapp/yarn.lock b/webapp/yarn.lock index 24d99e5..fbea1f2 100644 --- a/webapp/yarn.lock +++ b/webapp/yarn.lock @@ -3300,6 +3300,11 @@ resolved "https://registry.yarnpkg.com/@types/aria-query/-/aria-query-4.2.2.tgz#ed4e0ad92306a704f9fb132a0cfcf77486dbe2bc" integrity sha512-HnYpAE1Y6kRyKM/XkEuiRQhTHvkzMBurTHnpFLYLBGPIylZNPs9jJcuOOYWxPLJCSEtmZT0Y8rHDokKN7rRTig== +"@types/autosuggest-highlight@^3.2.0": + version "3.2.0" + resolved "https://registry.yarnpkg.com/@types/autosuggest-highlight/-/autosuggest-highlight-3.2.0.tgz#716a1408b8d987a6b636cf30048cba101d9f1cae" + integrity sha512-bTcsL4YYypjhKfPaImxuoMPiTyiUp7VGKytMr15/413IoazrOIfV/gca2ysI/IW0ftZYCPI5xppRm6IVX1Efqw== + "@types/babel__core@^7.0.0", "@types/babel__core@^7.1.7": version "7.1.19" resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.19.tgz#7b497495b7d1b4812bdb9d02804d0576f43ee460" @@ -4585,6 +4590,13 @@ autoprefixer@^9.6.1, autoprefixer@^9.8.6: postcss "^7.0.32" postcss-value-parser "^4.1.0" +autosuggest-highlight@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/autosuggest-highlight/-/autosuggest-highlight-3.2.1.tgz#0c1338deba395ab7552b0502f567ad369d7fea3c" + integrity sha512-PZk89g6W6cyE+fbnWF2CCIUAmP55o5wceKVqqL6oosgvbWHKa2Mes6nRC/PGj7OwqBgIy65Nd21Dw3h6qodOmg== + dependencies: + diacritic "0.0.2" + axe-core@^4.3.5: version "4.4.2" resolved "https://registry.yarnpkg.com/axe-core/-/axe-core-4.4.2.tgz#dcf7fb6dea866166c3eab33d68208afe4d5f670c" @@ -6589,6 +6601,11 @@ detect-port@^1.3.0: address "^1.0.1" debug "^2.6.0" +diacritic@0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/diacritic/-/diacritic-0.0.2.tgz#fc2a887b5a5bc0a0a854fb614c7c2f209061ee04" + integrity sha512-iQCeDkSPwkfwWPr+HZZ49WRrM2FSI9097Q9w7agyRCdLcF9Eh2Ek0sHKcmMWx2oZVBjRBE/sziGFjZu0uf1Jbg== + diff-sequences@^26.6.2: version "26.6.2" resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-26.6.2.tgz#48ba99157de1923412eed41db6b6d4aa9ca7c0b1"