From 4c3b34195a6cc262a8ff9f4fa20692b7612832ca Mon Sep 17 00:00:00 2001 From: Ari Date: Mon, 6 Jun 2022 22:37:34 -0400 Subject: [PATCH] service autocomplete --- ...nputEntities.css => InputAutoComplete.css} | 14 +- .../components/Inputs/InputAutoComplete.tsx | 153 ++++++++++++++++++ .../components/Inputs/InputDevice.stories.tsx | 2 +- webapp/src/components/Inputs/InputDevice.tsx | 117 ++------------ .../src/components/Inputs/InputEntities.tsx | 134 ++------------- .../Inputs/InputService.stories.tsx | 36 +++++ webapp/src/components/Inputs/InputService.tsx | 19 +++ .../OptionManager/ActionService.tsx | 7 +- .../components/NodeEditor/index.stories.tsx | 11 ++ webapp/src/haService/connection.stories.tsx | 27 ---- webapp/src/haService/index.ts | 45 +++++- webapp/src/haService/services.stories.tsx | 140 ++++++++++++++++ webapp/src/utils/formatting.test.ts | 3 + webapp/src/utils/formatting.ts | 3 +- 14 files changed, 437 insertions(+), 274 deletions(-) rename webapp/src/components/Inputs/{InputEntities.css => InputAutoComplete.css} (57%) create mode 100644 webapp/src/components/Inputs/InputAutoComplete.tsx create mode 100644 webapp/src/components/Inputs/InputService.stories.tsx create mode 100644 webapp/src/components/Inputs/InputService.tsx delete mode 100644 webapp/src/haService/connection.stories.tsx create mode 100644 webapp/src/haService/services.stories.tsx diff --git a/webapp/src/components/Inputs/InputEntities.css b/webapp/src/components/Inputs/InputAutoComplete.css similarity index 57% rename from webapp/src/components/Inputs/InputEntities.css rename to webapp/src/components/Inputs/InputAutoComplete.css index db5637e..80d4ec0 100644 --- a/webapp/src/components/Inputs/InputEntities.css +++ b/webapp/src/components/Inputs/InputAutoComplete.css @@ -1,26 +1,26 @@ -.input-entities .BaseBadge-root { +.input-autocomplete .BaseBadge-root { max-width: 100%; } -.input-entities--chip>span { +.input-autocomplete--chip>span { display: flex; flex-direction: row; gap: 0.15em; } -.input-entities--chip>span>small::before { +.input-autocomplete--chip>span>small::before { content: "/ "; } -.input-entities--chip>span>small { +.input-autocomplete--chip>span>small { size: 0.15em; } -.input-entities--errors { +.input-autocomplete--errors { margin-top: 0.75em; } -.input-entities--errors ul { +.input-autocomplete--errors ul { padding: 0 0 0 1em; margin: 0; max-height: 2.5em; @@ -28,7 +28,7 @@ overflow-x: hidden; } -.input-entities--tags { +.input-autocomplete--tags { max-height: 5em; max-width: 100%; overflow: auto; diff --git a/webapp/src/components/Inputs/InputAutoComplete.tsx b/webapp/src/components/Inputs/InputAutoComplete.tsx new file mode 100644 index 0000000..bbd7cdb --- /dev/null +++ b/webapp/src/components/Inputs/InputAutoComplete.tsx @@ -0,0 +1,153 @@ +import "./InputAutoComplete.css"; +import { FC } from "react"; +import { Option } 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 { Badge } from "@mui/material"; +import { SearchItem } from "./extras"; + +export type InputAutoCompleteProps> = { + validateOption?: (v: string[]) => string[] | null; + groupBy?: (opt: T) => string; + options: T[]; + getLabel: (opt: T) => string; + getID: (opt: T) => string; +} & InputAutoCompletePropsBase; + +export type InputAutoCompletePropsBase = { + label?: string; +} & ({ + value: string | null; + multiple?: false; + onChange: (v: string | null) => void; +} | { + value: string | string[]; + multiple: true; + onChange: (v: string[]) => void; +}) + +export const InputAutoComplete: FC> = props => { + // processing of inputs + const value = Array.isArray(props.value) ? props.value : !!props.value ? [props.value] : []; + const errors = props.validateOption ? props.validateOption(value) : null; + const options = props.options.sort((a, b) => { + return props.getID(a) > props.getID(b) ? 1 : -1; + }); + + // 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().trim(); + if (!searchTerm) { + return opts; + } + return opts.map(opt => { + let similarityScore = 0; + const eid = props.getID(opt); + if (eid.toLocaleLowerCase().includes(searchTerm)) { + similarityScore = Math.abs(eid.length - searchTerm.length) + } + const name = props.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={props.groupBy} + renderOption={(listProps, option, { inputValue }) => { + const label = props.getLabel(option); + const id = props.getID(option); + + return + }} + renderInput={params => } + renderTags={(tagValue, getTagProps) => { + const inner =
+ {tagValue.map((option, index) => { + const label = props.getLabel(option); + const id = props.getID(option); + const tagProps = getTagProps({ index }); + tagProps.className += ' input-autocomplete--chip' + return ( + + {(id === label) ? {label} : {label}} + {(id !== label) && {id}} + } + {...tagProps} + /> + ) + })} +
+ if (props.multiple) { + return + {inner} + + } else { + return inner + } + } + } + /> +} + diff --git a/webapp/src/components/Inputs/InputDevice.stories.tsx b/webapp/src/components/Inputs/InputDevice.stories.tsx index ded1769..c3eab70 100644 --- a/webapp/src/components/Inputs/InputDevice.stories.tsx +++ b/webapp/src/components/Inputs/InputDevice.stories.tsx @@ -32,5 +32,5 @@ export const Single = Template.bind({}) Single.args = { ...Single.args, multiple: false, - value: 'sensor.bathroom' + value: 'sensor.humidity_bathroom' } as any diff --git a/webapp/src/components/Inputs/InputDevice.tsx b/webapp/src/components/Inputs/InputDevice.tsx index f092560..1d4c221 100644 --- a/webapp/src/components/Inputs/InputDevice.tsx +++ b/webapp/src/components/Inputs/InputDevice.tsx @@ -1,117 +1,18 @@ -import "./InputEntities.css"; import { FC } from "react"; import { 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'; +import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete'; -export type InputEntityProps = { - label?: string, -} & ({ - value: string | null; - multiple?: false; - onChange: (v: string | null) => void; -} | { - value: EntityId; - multiple: true; - onChange: (v: string[]) => void; -}) +export type InputDeviceProps = InputAutoCompletePropsBase & { multiple?: false }; -export const InputDevice: FC = props => { +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} - /> - ) - })} -
-
- } + return } diff --git a/webapp/src/components/Inputs/InputEntities.tsx b/webapp/src/components/Inputs/InputEntities.tsx index a37cc94..c3ba54b 100644 --- a/webapp/src/components/Inputs/InputEntities.tsx +++ b/webapp/src/components/Inputs/InputEntities.tsx @@ -1,138 +1,22 @@ -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 { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete'; import { prettyName } from "utils/formatting"; -import { EntityId } from 'types/automations/common'; -import { Badge } from "@mui/material"; -import { SearchItem } from "./extras"; -export type InputEntityProps = { +export type InputEntityProps = InputAutoCompletePropsBase & { 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 - }) - }} + return entities.validateOptions(v, props.restrictToDomain)} + options={entities.getOptions(props.restrictToDomain)} + getID={entities.getID} + getLabel={entities.getLabel} 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} - /> - ) - })} -
-
- } /> } diff --git a/webapp/src/components/Inputs/InputService.stories.tsx b/webapp/src/components/Inputs/InputService.stories.tsx new file mode 100644 index 0000000..f6d2db9 --- /dev/null +++ b/webapp/src/components/Inputs/InputService.stories.tsx @@ -0,0 +1,36 @@ +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { Page } from "components/Page"; +import { useState } from "react"; + +import { InputService } from "./InputService"; + +export default { + title: 'Inputs/InputService', + component: InputService, + 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: '' +} as any diff --git a/webapp/src/components/Inputs/InputService.tsx b/webapp/src/components/Inputs/InputService.tsx new file mode 100644 index 0000000..793e9cc --- /dev/null +++ b/webapp/src/components/Inputs/InputService.tsx @@ -0,0 +1,19 @@ +import { FC } from "react"; +import { ServiceOption, useHAServices } from 'haService'; +import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete'; +import { prettyName } from 'utils/formatting'; + +export type InputServiceProps = InputAutoCompletePropsBase & { multiple?: false }; + +export const InputService: FC = props => { + const services = useHAServices(); + return (typeof opt !== 'string') ? prettyName(opt.domain) : ''} + /> +} + diff --git a/webapp/src/components/NodeEditor/OptionManager/ActionService.tsx b/webapp/src/components/NodeEditor/OptionManager/ActionService.tsx index e13a122..bf4ed15 100644 --- a/webapp/src/components/NodeEditor/OptionManager/ActionService.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/ActionService.tsx @@ -1,3 +1,4 @@ +import { InputService } from "components/Inputs/InputService"; import InputText from "components/Inputs/InputText"; import InputYaml from 'components/Inputs/InputYaml'; import { ServiceAction } from "types/automations/actions"; @@ -19,11 +20,9 @@ export const ActionCallServiceState: OptionManager = { const { service, target, data } = state; const update = updateActionData(state, setState); return <> - update({ service })} + onChange={(service: string | null) => update({ service: service ?? "" })} /> = props => { }; + + +export const ServiceExample = Action.bind({}) +ServiceExample.args = { + ...ServiceExample.args, + node: { + "target": {}, + "data": {}, + "service": "", + }, +} diff --git a/webapp/src/haService/connection.stories.tsx b/webapp/src/haService/connection.stories.tsx deleted file mode 100644 index 807430a..0000000 --- a/webapp/src/haService/connection.stories.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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/index.ts b/webapp/src/haService/index.ts index 4648496..44c939e 100644 --- a/webapp/src/haService/index.ts +++ b/webapp/src/haService/index.ts @@ -74,10 +74,48 @@ export const useHAEntities = () => { } } +export type ServiceOption = Option<{ domain: string, action: string, description: string }>; export const useHAServices = () => { const services = useHassCollection(servicesColl); + const methods = { + getOptions(): ServiceOption[] { + if (!services.ready) { + return [] + } + return Object.keys(services.collection.state).reduce((all, domain) => { + const opts = Object.keys(services.collection.state[domain]).map( + action => ({ + id: `${domain}.${action}`, + label: services.collection.state[domain][action].name ?? `${domain}.${action}`, + description: services.collection.state[domain][action].description ?? "", + domain, + action, + }) + ) + 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: DeviceRegistryOption): string => { + if (typeof opt === 'string') { + return opt + } + return opt.id + } + } - return services + return { ...services, ...methods } } export type DeviceRegistryOption = Option<{ manufacturer: string }>; @@ -126,6 +164,7 @@ export const useHAEntityRegistry = () => { export const useHA = () => { const entities = useHAEntities(); const devices = useHADeviceRegistry(); + const services = useHAServices(); const namer: Namer = { getDeviceName(device_id) { @@ -137,11 +176,15 @@ export const useHA = () => { } return entities.getLabel(entity_id) }, + getServiceName(service) { + return services.getLabel(service) + }, } return { entities, devices, + services, namer, } } \ No newline at end of file diff --git a/webapp/src/haService/services.stories.tsx b/webapp/src/haService/services.stories.tsx new file mode 100644 index 0000000..9b4bc02 --- /dev/null +++ b/webapp/src/haService/services.stories.tsx @@ -0,0 +1,140 @@ +import React, { FC, useEffect, useState } from "react"; +import { ComponentMeta, ComponentStory } from '@storybook/react'; +import { Page } from "components/Page"; +import { useHAServices } from "haService"; +import InputYaml from "components/Inputs/InputYaml"; +import { InputList } from "components/Inputs/InputList"; + +const Test: FC = () => { + const services = useHAServices(); + + const data = services.collection?.state ?? {}; + const options = Object.keys(data).sort(); + + const summary: Record }>> = {} + const fields: Record }>> = {} + const target: Record }>> = {} + + Object.keys(data).forEach(domain => + Object.keys(data[domain]).forEach( + action => { + const service = data[domain][action]; + Object.keys(service.fields).forEach(field => { + const value = service.fields[field]; + const valueType = `${typeof value}-${Array.isArray(value)}`; + fields[field] = fields[field] ?? {} + fields[field][valueType] = fields[field][valueType] ?? { + total: 0, + domains: [], + values: new Set() + } + fields[field][valueType].total += 1 + fields[field][valueType].values.add(JSON.stringify(value)) + + }) + Object.keys(service.target ?? {}).forEach(field => { + const value = (service.target as any)[field]; + const valueType = `${typeof value}-${Array.isArray(value)}`; + target[field] = target[field] ?? {} + target[field][valueType] = target[field][valueType] ?? { + total: 0, + domains: [], + values: new Set() + } + target[field][valueType].total += 1 + target[field][valueType].values.add(JSON.stringify(value)) + + }) + Object.keys(service).forEach(field => { + const value = (service as any)[field]; + const valueType = `${typeof value}-${Array.isArray(value)}`; + summary[field] = summary[field] ?? {} + summary[field][valueType] = summary[field][valueType] ?? { + total: 0, + domains: [], + values: new Set() + } + summary[field][valueType].total += 1 + summary[field][valueType].domains.push(`${domain}.${action}`) + summary[field][valueType].values.add(JSON.stringify(value)) + }) + } + ) + ) + + const [current, setCurrent] = useState(options[0] ?? ""); + + const suboptions = Object.keys(data[current] ?? "").sort(); + + const [secCurrent, setSecCurrent] = useState(suboptions[0] ?? ""); + + useEffect(() => { + setSecCurrent(suboptions[0] ?? "") + }, [current, setSecCurrent]) + + + return
+
    + {Object.keys(summary).map(k =>
  • + {k}
      + {Object.keys(summary[k]).map(t =>
    • + {t} ({summary[k][t].total}) +
        + {Array.from(summary[k][t].values.values()).sort().map((v, i) =>
      • + {v} +
      • )} +
      +
    • )} +
    +
  • )} +
+

Fields

+
    + {Object.keys(fields).map(k =>
  • + {k}
      + {Object.keys(fields[k]).map(t =>
    • + {t} ({fields[k][t].total}) +
        + {Array.from(fields[k][t].values.values()).sort().map((v, i) =>
      • + {v} +
      • )} +
      +
    • )} +
    +
  • )} +
+

Targets

+
    + {Object.keys(target).map(k =>
  • + {k}
      + {Object.keys(target[k]).map(t =>
    • + {t} ({target[k][t].total}) +
        + {Array.from(target[k][t].values.values()).sort().map((v, i) =>
      • + {v} +
      • )} +
      +
    • )} +
    +
  • )} +
+ + + { }} /> +
+} + +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/utils/formatting.test.ts b/webapp/src/utils/formatting.test.ts index f6c154d..5d45cf8 100644 --- a/webapp/src/utils/formatting.test.ts +++ b/webapp/src/utils/formatting.test.ts @@ -5,6 +5,9 @@ const dummyNamer: Namer = { getDeviceName(device_id) { return device_id }, + getServiceName(service) { + return service + }, getEntityName(entity_id, maxEntities = 1) { if (Array.isArray(entity_id)) { return entity_id.slice(0, maxEntities).join(' and ') diff --git a/webapp/src/utils/formatting.ts b/webapp/src/utils/formatting.ts index 7793379..623e50d 100644 --- a/webapp/src/utils/formatting.ts +++ b/webapp/src/utils/formatting.ts @@ -5,6 +5,7 @@ import { AutomationTime } from "types/automations/common"; export interface Namer { getEntityName(entity_id: string | string[], maxEntities?: number): string; getDeviceName(device_id: string): string; + getServiceName(service: string): string; } export const convertTimeToString = (t: AutomationTime) => { @@ -101,7 +102,7 @@ export const getDescriptionFromAutomationNode = ( } } if ('service' in node) { - return node.service + return namer.getServiceName(node.service) } if ('repeat' in node) { return 'Repeat ' + node.repeat.count