From 7b816c3fbfbd27e180ea5040b4db9ec34cd3b519 Mon Sep 17 00:00:00 2001 From: Ari Date: Tue, 14 Jun 2022 15:06:02 -0400 Subject: [PATCH] v1 of service editor --- .../components/Inputs/InputAutoComplete.tsx | 328 ++++++++++-------- webapp/src/components/Inputs/InputList.tsx | 89 +++-- webapp/src/components/Inputs/InputNumber.tsx | 68 ++-- webapp/src/components/Inputs/InputText.tsx | 99 ++++-- .../OptionManager/ActionService.tsx | 58 ++-- .../NodeEditor/OptionManager/OptionManager.ts | 3 +- .../NodeEditor/OptionManager/index.tsx | 240 ++++++++----- .../ServiceEditor/ServiceEditorField.css | 5 + .../ServiceEditor/ServiceEditorField.tsx | 77 ++++ webapp/src/components/ServiceEditor/index.css | 31 ++ .../ServiceEditor/index.stories.tsx | 44 +++ webapp/src/components/ServiceEditor/index.tsx | 184 ++++++++++ .../src/components/ServiceEditor/options.ts | 52 +++ webapp/src/haService/fieldTypes.ts | 83 +++++ webapp/src/haService/index.ts | 39 ++- webapp/src/haService/services.stories.tsx | 220 ++++++++---- 16 files changed, 1185 insertions(+), 435 deletions(-) create mode 100644 webapp/src/components/ServiceEditor/ServiceEditorField.css create mode 100644 webapp/src/components/ServiceEditor/ServiceEditorField.tsx create mode 100644 webapp/src/components/ServiceEditor/index.css create mode 100644 webapp/src/components/ServiceEditor/index.stories.tsx create mode 100644 webapp/src/components/ServiceEditor/index.tsx create mode 100644 webapp/src/components/ServiceEditor/options.ts create mode 100644 webapp/src/haService/fieldTypes.ts diff --git a/webapp/src/components/Inputs/InputAutoComplete.tsx b/webapp/src/components/Inputs/InputAutoComplete.tsx index eb88c92..83a8cb0 100644 --- a/webapp/src/components/Inputs/InputAutoComplete.tsx +++ b/webapp/src/components/Inputs/InputAutoComplete.tsx @@ -1,152 +1,204 @@ 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 { Option } from "haService"; +import Autocomplete from "@mui/material/Autocomplete"; +import TextField from "@mui/material/TextField"; +import Chip from "@mui/material/Chip"; 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; + className?: string; + validateOption?: (v: string[]) => string[] | null; + groupBy?: (opt: T) => string; + options: T[]; + getLabel?: (opt: T) => string; + getID?: (opt: T) => string; + helperText?: 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} -
  • )}
-
- } + label?: string; +} & ( + | { + value: string | null; + multiple?: false; + onChange: (v: string | null) => void; } - // 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]; + | { + value: string | string[]; + multiple: true; + onChange: (v: string[]) => void; + } +); + +export function InputAutoComplete( + props: InputAutoCompleteProps +) { + // aliases + const getID = (opt: T): string => { + if (props.getID) { + return props.getID(opt); + } + if (typeof opt === "string") { + return opt; + } + return opt.id; + }; + const getLabel = (opt: T): string => { + if (props.getLabel) { + return props.getLabel(opt); + } + if (typeof opt === "string") { + return opt; + } + return opt.label; + }; + // 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 getID(a) > getID(b) ? 1 : -1; + }); + + // processing of errors + let helperText = props.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 = 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, + }; + }) + .filter((opt) => opt.similarityScore > 0) + .sort((a, b) => { + return a.similarityScore > b.similarityScore ? 1 : -1; + }) as any; + }} + groupBy={props.groupBy} + renderOption={(listProps, option, { inputValue }) => { + const label = getLabel(option); + const id = getID(option); + + return ( + + ); + }} + renderInput={(params) => ( + + )} + renderTags={(tagValue, getTagProps) => { + const inner = ( +
+ {tagValue.map((option, index) => { + const label = getLabel(option); + const id = getID(option); + const tagProps = getTagProps({ index }); + tagProps.className += " input-autocomplete--chip"; + return ( + + {id === label ? {label} : {label}} + {id !== label && {id}} + + } + {...tagProps} + /> + ); + })} +
+ ); if (props.multiple) { - props.onChange(cleanValue); + return ( + + {inner} + + ); } 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 - } - } + return inner; } + }} /> + ); } - diff --git a/webapp/src/components/Inputs/InputList.tsx b/webapp/src/components/Inputs/InputList.tsx index 379bb75..5b52dfc 100644 --- a/webapp/src/components/Inputs/InputList.tsx +++ b/webapp/src/components/Inputs/InputList.tsx @@ -1,20 +1,26 @@ -import FormHelperText from '@mui/material/FormHelperText'; -import InputLabel from '@mui/material/InputLabel'; -import MenuItem from '@mui/material/MenuItem'; -import FormControl from '@mui/material/FormControl'; -import Select from '@mui/material/Select'; +import FormHelperText from "@mui/material/FormHelperText"; +import InputLabel from "@mui/material/InputLabel"; +import MenuItem from "@mui/material/MenuItem"; +import FormControl from "@mui/material/FormControl"; +import Select from "@mui/material/Select"; import { prettyName } from "utils/formatting"; +import { ReactNode } from "react"; -export interface Props { - current: T; +export type Props = { + current?: T; options: readonly T[]; onChange: (n: T) => void; label: string; id?: string; className?: string; prettyOptionLabels?: boolean; -} -export function InputList({ + getKey?: (n: T) => string; + placeholder?: any; + title?: string; + helperText?: string; + endAdornment?: ReactNode; +}; +export function InputList({ current, options, onChange, @@ -22,32 +28,47 @@ export function InputList({ id, className, prettyOptionLabels, + getKey = String, + placeholder, + title, + helperText, + endAdornment, }: Props) { - const invalidCurrent = current && !options.includes(current); - return - {label} - - {invalidCurrent ? `'${current}' is not a valid selection` : ''} - + {label} + + + {invalidCurrent ? `'${current}' is not a valid selection` : helperText} + + + ); } diff --git a/webapp/src/components/Inputs/InputNumber.tsx b/webapp/src/components/Inputs/InputNumber.tsx index 1b34166..fd5d422 100644 --- a/webapp/src/components/Inputs/InputNumber.tsx +++ b/webapp/src/components/Inputs/InputNumber.tsx @@ -5,39 +5,57 @@ import InputAdornment from "@mui/material/InputAdornment"; import Edit from "@mui/icons-material/Edit"; export interface Props { - label: string; + label: string | JSX.Element; value: number | undefined; onChange: (v: number | undefined) => void; className?: string; - min?: number, - max?: number, - step?: number, + min?: number; + max?: number; + step?: number; + unit?: string; + placeholder?: any; + required?: boolean; } export default function InputNumber({ label, value = undefined, onChange, className = "", - min, max, step, + min, + max, + step, + unit, + placeholder, + required, }: Props) { - const disabled = (value === undefined) || (value === null); - return onChange(Number(e.target.value ?? 0))} - disabled={disabled} - className={className} - InputProps={{ - endAdornment: - onChange(disabled ? 0 : undefined)}> - {disabled ? : } - - , - inputProps: { - min, max, type: 'number' - } - }} - /> + const disabled = value === undefined || value === null; + return ( + onChange(Number(e.target.value ?? 0))} + disabled={disabled} + className={className} + placeholder={placeholder} + required={required} + InputProps={{ + endAdornment: ( + + {unit} + onChange(disabled ? 0 : undefined)}> + {disabled ? : } + + + ), + inputProps: { + min, + max, + type: "number", + step, + }, + }} + /> + ); } diff --git a/webapp/src/components/Inputs/InputText.tsx b/webapp/src/components/Inputs/InputText.tsx index c928037..8ac75ea 100644 --- a/webapp/src/components/Inputs/InputText.tsx +++ b/webapp/src/components/Inputs/InputText.tsx @@ -1,11 +1,11 @@ -import { PropsWithChildren, useState } from "react"; +import React, { PropsWithChildren, ReactNode, useState } from "react"; import { useToolTip } from "tooltip/context"; -import TextField from '@mui/material/TextField'; +import TextField from "@mui/material/TextField"; import InputWrapper from "./InputWrapper"; export interface Props { textBoxFor?: string; - label: string; + label: string | JSX.Element; value: string; onChange: (v: string) => void; onEnter?: () => void; @@ -13,50 +13,77 @@ export interface Props { multiline?: boolean; maxRows?: number; className?: string; + placeholder?: any; + title?: string; + helperText?: string; + endAdornment?: ReactNode; + required?: boolean; } export default function InputText({ label, + title, + helperText, textBoxFor, value = "", onChange, - onEnter = () => { }, + endAdornment, + onEnter = () => {}, additionalTooltipFilters = {}, multiline = false, maxRows = 4, children, className, + placeholder, + required, }: PropsWithChildren) { const tooltip = useToolTip(); - const [isFocused, setIsFocused] = useState(false) - return - { - if (e.key === 'Enter') { - onEnter(); - } - }} - onChange={e => { - e.preventDefault(); - onChange(e.target.value) - }} - onBlur={() => { - setIsFocused(false) - }} - onFocus={e => { - setIsFocused(true) - if (textBoxFor) { - tooltip.setFocus( - e.target.getBoundingClientRect(), - { - searchObject: textBoxFor, - searchText: value, - filterObjects: additionalTooltipFilters, - }, - onChange - ) - } - }} - /> - {children} - + const [isFocused, setIsFocused] = useState(false); + return ( + + { + if (e.key === "Enter") { + onEnter(); + } + }} + onChange={(e) => { + e.preventDefault(); + onChange(e.target.value); + }} + onBlur={() => { + setIsFocused(false); + }} + onFocus={(e) => { + setIsFocused(true); + if (textBoxFor) { + tooltip.setFocus( + e.target.getBoundingClientRect(), + { + searchObject: textBoxFor, + searchText: value, + filterObjects: additionalTooltipFilters, + }, + onChange + ); + } + }} + /> + {children} + + ); } diff --git a/webapp/src/components/NodeEditor/OptionManager/ActionService.tsx b/webapp/src/components/NodeEditor/OptionManager/ActionService.tsx index 80abdba..78e394b 100644 --- a/webapp/src/components/NodeEditor/OptionManager/ActionService.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/ActionService.tsx @@ -1,8 +1,7 @@ import { InputService } from "components/Inputs/InputService"; -import InputYaml from 'components/Inputs/InputYaml'; +import { ServiceEditor } from "components/ServiceEditor"; import { ServiceAction } from "types/automations/actions"; -import { OptionManager, updateActionData } from './OptionManager'; - +import { OptionManager, updateActionData } from "./OptionManager"; export const ActionCallServiceState: OptionManager = { defaultState: () => ({ @@ -10,29 +9,34 @@ export const ActionCallServiceState: OptionManager = { target: {}, data: {}, }), - isReady: ({ - service, - }) => ( - service !== '' - ), - renderOptionList: (state, setState) => { + isReady: ({ service }) => service !== "", + Component: ({ state, setState, services }) => { const { service, target, data } = state; const update = updateActionData(state, setState); - return <> - update({ service: service ?? "" })} - /> - update({ target })} - /> - update({ data })} - /> - - } -} + const serviceOption = services.getOption(service); + return ( + <> + + update({ service: service ?? "" }) + } + /> + {serviceOption && ( + + update({ + target, + data: field, + }) + } + /> + )} + + ); + }, +}; diff --git a/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts b/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts index 6bfa65d..e75a9d0 100644 --- a/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts +++ b/webapp/src/components/NodeEditor/OptionManager/OptionManager.ts @@ -1,4 +1,4 @@ -import { HAEntitiesState } from 'haService'; +import { HAEntitiesState, HAServicesState } from 'haService'; import { FC } from 'react'; import { AutomationAction } from 'types/automations/actions'; import { AutomationCondition } from 'types/automations/conditions'; @@ -12,6 +12,7 @@ export type OptionManager = { state: T, setState: (s: T) => void, entities: HAEntitiesState, + services: HAServicesState, }> }) diff --git a/webapp/src/components/NodeEditor/OptionManager/index.tsx b/webapp/src/components/NodeEditor/OptionManager/index.tsx index ff69cba..ce8a7c4 100644 --- a/webapp/src/components/NodeEditor/OptionManager/index.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/index.tsx @@ -1,44 +1,61 @@ -import { Dispatch, SetStateAction, useEffect, useState } from 'react'; -import { AutomationNode, AutomationNodeTypes } from 'types/automations'; -import { AutomationNodeSubtype } from 'types/automations'; -import { getOptionManager } from './getOptionManager'; -import { getNodeSubType, getSubTypeList, validateNode } from 'utils/automations'; -import InputYaml from 'components/Inputs/InputYaml'; -import InputText from 'components/Inputs/InputText'; -import { getDescriptionFromAutomationNode } from 'utils/formatting'; -import { useHA } from 'haService'; -import { Generic } from './Generic'; -import { getNodeTypeAndValidate } from 'utils/automations'; +import { Dispatch, SetStateAction, useEffect, useState } from "react"; +import { AutomationNode, AutomationNodeTypes } from "types/automations"; +import { AutomationNodeSubtype } from "types/automations"; +import { getOptionManager } from "./getOptionManager"; +import { + getNodeSubType, + getSubTypeList, + validateNode, +} from "utils/automations"; +import InputYaml from "components/Inputs/InputYaml"; +import InputText from "components/Inputs/InputText"; +import { getDescriptionFromAutomationNode } from "utils/formatting"; +import { useHA } from "haService"; +import { Generic } from "./Generic"; +import { getNodeTypeAndValidate } from "utils/automations"; -type UseState = (s: S) => [S, Dispatch>] +type UseState = (s: S) => [S, Dispatch>]; -export const useEditorNodeState = (originalNode: AutomationNode, isErrored: boolean, allowedTypes: AutomationNodeTypes[], uState: UseState = useState) => { +export const useEditorNodeState = ( + originalNode: AutomationNode, + isErrored: boolean, + allowedTypes: AutomationNodeTypes[], + uState: UseState = useState +) => { // state const [allState, setAllState] = uState({ yamlMode: false, isModified: false, - ...computeInvalidYaml(originalNode, allowedTypes) + ...computeInvalidYaml(originalNode, allowedTypes), }); - const { entities, namer } = useHA(); + const { entities, namer, services } = useHA(); // aliases - const { node: currentNode, isModified, yamlMode, invalidManualYaml } = allState; + const { + node: currentNode, + isModified, + yamlMode, + invalidManualYaml, + } = allState; // effects useEffect(() => { - setAllState({ ...allState, node: originalNode, isModified: false, }) + setAllState({ ...allState, node: originalNode, isModified: false }); // eslint-disable-next-line - }, [originalNode]) + }, [originalNode]); // function aliases - const setState = (node: AutomationNode) => setAllState(({ - ...allState, node, - isModified: JSON.stringify(node) !== JSON.stringify(originalNode), - })); - const setYamlMode = (yamlMode: boolean) => setAllState({ ...allState, yamlMode, }); + const setState = (node: AutomationNode) => + setAllState({ + ...allState, + node, + isModified: JSON.stringify(node) !== JSON.stringify(originalNode), + }); + const setYamlMode = (yamlMode: boolean) => + setAllState({ ...allState, yamlMode }); const setStateForManualYaml = (yaml: any) => { setAllState({ ...allState, - ...computeInvalidYaml(yaml, allowedTypes) - }) - } + ...computeInvalidYaml(yaml, allowedTypes), + }); + }; // value aliases const { originalNodeType, @@ -47,7 +64,7 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool subType, subTypes, optionManager, - } = createData(originalNode, currentNode, allowedTypes) + } = createData(originalNode, currentNode, allowedTypes); // publuc return { nodeType, @@ -59,91 +76,119 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool isErrored: allState.isErrored, get prettyNodeType() { if (nodeType) { - return `${nodeType.slice(0, 1).toUpperCase()}${nodeType.slice(1)} Type` + return `${nodeType.slice(0, 1).toUpperCase()}${nodeType.slice(1)} Type`; } else { - return 'n/a' + return "n/a"; } }, get yamlMode() { - return allState.isErrored || yamlMode + return allState.isErrored || yamlMode; }, get data() { - return currentNode + return currentNode; }, setEnabled(enabled: boolean) { setState({ ...currentNode, enabled, - }) + }); }, renderOptionList() { - let aliasEditor = <> - if (nodeType === 'trigger') { - aliasEditor = setState({ - ...allState.node, - id - } as any)} - /> + let aliasEditor = <>; + if (nodeType === "trigger") { + aliasEditor = ( + + setState({ + ...allState.node, + id, + } as any) + } + /> + ); } - if (nodeType === 'action') { - aliasEditor = setState({ - ...allState.node, - alias - } as any)} - /> + if (nodeType === "action") { + aliasEditor = ( + + setState({ + ...allState.node, + alias, + } as any) + } + /> + ); } if (yamlMode || allState.isErrored) { - return <> - {aliasEditor} - - + return ( + <> + {aliasEditor} + + + ); } - return <> - {aliasEditor} - {('renderOptionList' in optionManager) ? - optionManager.renderOptionList(currentNode, setState, entities) : - } - ; + return ( + <> + {aliasEditor} + {"renderOptionList" in optionManager ? ( + optionManager.renderOptionList(currentNode, setState, entities) + ) : ( + + )} + + ); }, isReady() { return optionManager.isReady(currentNode); }, setNodeType(newType: AutomationNodeTypes) { if (newType === originalNodeType) { - setState(originalNode) + setState(originalNode); } else { - setState(getOptionManager(newType, getSubTypeList(newType)[0]).defaultState()) + setState( + getOptionManager(newType, getSubTypeList(newType)[0]).defaultState() + ); } }, setSubType(newSubType: AutomationNodeSubtype) { if (newSubType === originalNodeSubType) { - setState(originalNode) + setState(originalNode); } else { if (nodeType) { - setState(getOptionManager(nodeType, newSubType as any).defaultState()) + setState( + getOptionManager(nodeType, newSubType as any).defaultState() + ); } else { - setState(getOptionManager(allowedTypes[0], newSubType as any).defaultState()) + setState( + getOptionManager(allowedTypes[0], newSubType as any).defaultState() + ); } } - } - } -} + }, + }; +}; - -const createData = (originalNode: AutomationNode, currentNode: AutomationNode, allowedTypes: AutomationNodeTypes[]) => { +const createData = ( + originalNode: AutomationNode, + currentNode: AutomationNode, + allowedTypes: AutomationNodeTypes[] +) => { let originalNodeType: AutomationNodeTypes = allowedTypes[0]; let originalNodeSubType: AutomationNodeSubtype | null = null; let nodeType: AutomationNodeTypes = originalNodeType; @@ -155,15 +200,15 @@ const createData = (originalNode: AutomationNode, currentNode: AutomationNode, a originalNodeType = getNodeTypeAndValidate(originalNode, allowedTypes); originalNodeSubType = getNodeSubType(originalNode); } catch (err) { - console.error(`ORIGINAL NODE ERROR ${JSON.stringify(originalNode)}`) + console.error(`ORIGINAL NODE ERROR ${JSON.stringify(originalNode)}`); } try { nodeType = getNodeTypeAndValidate(currentNode, allowedTypes); subType = getNodeSubType(currentNode); - subTypes = getSubTypeList(nodeType) + subTypes = getSubTypeList(nodeType); optionManager = getOptionManager(nodeType, subType as any); } catch (err) { - console.error(`CURRENT NODE ERROR ${JSON.stringify(currentNode)}`) + console.error(`CURRENT NODE ERROR ${JSON.stringify(currentNode)}`); } return { originalNodeType, @@ -172,27 +217,34 @@ const createData = (originalNode: AutomationNode, currentNode: AutomationNode, a subType, subTypes, optionManager, - } -} + }; +}; -const computeInvalidYaml = (node: AutomationNode, allowedNodeTypes: AutomationNodeTypes[]) => { +const computeInvalidYaml = ( + node: AutomationNode, + allowedNodeTypes: AutomationNodeTypes[] +) => { const errors = validateNode(node, allowedNodeTypes); if (errors) { - console.log({ errors }) + console.log({ errors }); return { node, isErrored: true, - invalidManualYaml:
    - {errors.map(({ message, path }, i) =>
  • - {path}: {message} -
  • )} -
- } + invalidManualYaml: ( +
    + {errors.map(({ message, path }, i) => ( +
  • + {path}: {message} +
  • + ))} +
+ ), + }; } else { return { node, isErrored: false, - invalidManualYaml: <> - } + invalidManualYaml: <>, + }; } -} \ No newline at end of file +}; diff --git a/webapp/src/components/ServiceEditor/ServiceEditorField.css b/webapp/src/components/ServiceEditor/ServiceEditorField.css new file mode 100644 index 0000000..521a833 --- /dev/null +++ b/webapp/src/components/ServiceEditor/ServiceEditorField.css @@ -0,0 +1,5 @@ +.service-editor--field { + display: flex; + flex-direction: row; + align-items: center; +} \ No newline at end of file diff --git a/webapp/src/components/ServiceEditor/ServiceEditorField.tsx b/webapp/src/components/ServiceEditor/ServiceEditorField.tsx new file mode 100644 index 0000000..5914700 --- /dev/null +++ b/webapp/src/components/ServiceEditor/ServiceEditorField.tsx @@ -0,0 +1,77 @@ +import "./ServiceEditorField.css"; +import { FC } from "react"; +import { ServiceEditorOption } from "./options"; +import InputText from "components/Inputs/InputText"; +import InputNumber from "components/Inputs/InputNumber"; +import { IconButton } from "@mui/material"; +import { RemoveCircle } from "@mui/icons-material"; + +export type ServiceEditorFieldProps = { + option: ServiceEditorOption; + value: any; + onChange: (v: any) => void; + onRemove?: () => void; +}; +export const ServiceEditorField: FC = ({ + option, + value, + onChange, + onRemove, +}) => { + const description = option.data.description ?? ""; + const isRequired = !onRemove; + const label = option.label; + let example = ""; + const removeIcon = !onRemove ? ( + <> + ) : ( + + + + ); + + let input = ( + + ); + if (option.type === "field") { + example = option.data.example ? `Example: ${option.data.example}` : ""; + if (option.data.selector?.number) { + return ( + + ); + } + return ( + + ); + } + + return input; +}; diff --git a/webapp/src/components/ServiceEditor/index.css b/webapp/src/components/ServiceEditor/index.css new file mode 100644 index 0000000..31101e5 --- /dev/null +++ b/webapp/src/components/ServiceEditor/index.css @@ -0,0 +1,31 @@ +.service-editor { + display: flex; + flex-direction: column; +} + +.service-editor h4 { + margin: 0; + padding: 0; +} + +.service-editor--name { + display: flex; + flex-direction: column; +} + +.service-editor--name span { + font-size: 0.75em; + text-overflow: clip; + margin-left: 0.25em; +} + +.service-editor--add { + flex: 1; + display: flex; + flex-direction: row; + align-items: center; +} + +.service-editor--add--list { + flex: 1; +} \ No newline at end of file diff --git a/webapp/src/components/ServiceEditor/index.stories.tsx b/webapp/src/components/ServiceEditor/index.stories.tsx new file mode 100644 index 0000000..c23b148 --- /dev/null +++ b/webapp/src/components/ServiceEditor/index.stories.tsx @@ -0,0 +1,44 @@ +import React, { FC, useEffect, useState } from "react"; +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { Page } from "components/Page"; +import { ServiceEditor } from "."; +import { TypedHassService } from "haService/fieldTypes"; + +export default { + title: "Services/ServiceEditor", + component: ServiceEditor, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: {}, +} as ComponentMeta; + +const Template: ComponentStory = (props) => { + return ( + + + {JSON.stringify(props.service)} + + ); +}; + +const makeExample = (service: TypedHassService) => { + const Eg = Template.bind({}); + Eg.args = { + ...Eg, + service, + }; + return Eg; +}; + +export const NumberSetValue = makeExample({ + name: "Set", + description: "Set the value of a Number entity.", + fields: { + value: { + name: "Value", + description: "The target value the entity should be set to.", + example: 42, + selector: { text: null }, + }, + }, + target: { entity: { domain: "number" } }, +}); diff --git a/webapp/src/components/ServiceEditor/index.tsx b/webapp/src/components/ServiceEditor/index.tsx new file mode 100644 index 0000000..359797f --- /dev/null +++ b/webapp/src/components/ServiceEditor/index.tsx @@ -0,0 +1,184 @@ +import "./index.css"; + +import { InputList } from "components/Inputs/InputList"; +import { cleanUpUndefined } from "components/NodeEditor/OptionManager/OptionManager"; +import { TypedHassService } from "haService/fieldTypes"; +import { FC, useState } from "react"; +import { + ServiceEditorOption, + splitUpOptions, + convertFieldToOption, + convertTargetToOption, +} from "./options"; +import { ServiceEditorField } from "./ServiceEditorField"; +import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; + +export type ServiceEditorData = { + field: Record; + target: Record; +}; +export type ServiceEditorProps = { + serviceId: string; + service: TypedHassService; + data: ServiceEditorData; + onUpdate: (d: ServiceEditorData) => void; +}; +export const ServiceEditor: FC = ({ + serviceId, + service, + data, + onUpdate, +}) => { + const options = splitUpOptions(service); + const [additionalFields, setAdditionalFields] = useState<{ + field: string[]; + target: string[]; + optionalList: ServiceEditorOption[]; + }>({ + field: [], + target: [], + optionalList: options.additional, + }); + + // aliases + const hasRequired = options.required.length > 0; + const hasOptional = + additionalFields.field.length + additionalFields.target.length > 0; + const hasNothing = + !hasRequired && !hasOptional && additionalFields.optionalList.length === 0; + + // render + return ( +
+
+ + {service.name} /{serviceId} + + {service.description} +
+ {hasNothing ? ( + This Service Requires no inputs + ) : ( + <> + {options.required.map((opt) => ( + + onUpdate({ + ...data, + [opt.type]: { + ...data[opt.type], + [opt.id]: v, + }, + }) + } + /> + ))} +
+ {additionalFields.field.map((key) => { + const serviceData = service.fields[key]; + const option = convertFieldToOption(key, serviceData); + return ( + { + setAdditionalFields({ + ...additionalFields, + field: additionalFields.field.filter((k) => k !== key), + optionalList: + additionalFields.optionalList.concat(option), + }); + onUpdate({ + ...data, + field: cleanUpUndefined({ + ...data.field, + [key]: undefined, + }), + }); + }} + onChange={(v) => + onUpdate({ + ...data, + field: { + ...data.field, + [key]: v, + }, + }) + } + /> + ); + })} + {additionalFields.target.map((key) => { + const targetData = (service.target as any)[key]; + const option = convertTargetToOption(key, targetData); + return ( + { + setAdditionalFields({ + ...additionalFields, + target: additionalFields.target.filter((k) => k !== key), + optionalList: + additionalFields.optionalList.concat(option), + }); + onUpdate({ + ...data, + target: cleanUpUndefined({ + ...data.target, + [key]: undefined, + }), + }); + }} + onChange={(v) => + onUpdate({ + ...data, + target: { + ...data.target, + [key]: v, + }, + }) + } + /> + ); + })} +
+ + )} +
+ {additionalFields.optionalList.length > 0 && ( +
+ { + const newField = additionalFields.optionalList.filter( + (opt) => opt.id === id + )[0]; + if (newField) { + setAdditionalFields({ + ...additionalFields, + [newField.type]: additionalFields[newField.type].concat([ + newField.id, + ]), + optionalList: additionalFields.optionalList.filter( + (opt) => + !(opt.type === newField.type && opt.id === newField.id) + ), + }); + } + }} + options={additionalFields.optionalList} + /> +
+ )} +
+ ); +}; diff --git a/webapp/src/components/ServiceEditor/options.ts b/webapp/src/components/ServiceEditor/options.ts new file mode 100644 index 0000000..83075ca --- /dev/null +++ b/webapp/src/components/ServiceEditor/options.ts @@ -0,0 +1,52 @@ +import { BaseOption, Option } from "haService"; +import { FieldData, TargetData, TypedHassService } from "haService/fieldTypes"; +import { prettyName } from "utils/formatting"; +export type ServiceEditorOption = BaseOption< + | { + type: "field"; + data: { + description: string; + } & FieldData; + } + | { + type: "target"; + data: { + description: string; + } & TargetData; + } +>; + +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) => { + const required: ServiceEditorOption[] = []; + const additional: ServiceEditorOption[] = []; + Object.keys(service.fields ?? {}).forEach((key) => { + const serviceData = service.fields[key]; + const opt = convertFieldToOption(key, serviceData); + if (serviceData.required) { + required.push(opt); + } else { + additional.push(opt); + } + }); + Object.keys(service.target ?? {}).forEach((key) =>{ + const serviceData = (service.target ?? ({} as any))[key]; + additional.push(convertTargetToOption(key, serviceData)) + }); + return { required, additional }; +}; diff --git a/webapp/src/haService/fieldTypes.ts b/webapp/src/haService/fieldTypes.ts new file mode 100644 index 0000000..da29ea1 --- /dev/null +++ b/webapp/src/haService/fieldTypes.ts @@ -0,0 +1,83 @@ +export interface TypedHassService { + name?: string; + description: string; + fields: Fields; + target?: Targets | null | undefined; +} + +export type Fields = Record +export interface Targets { + device?: TargetData; + entity?: TargetData; +} +export interface TargetData { + domain?: string; + integration?: string; +} + +export interface FieldData { + name?: string | undefined; + description: string; + required?: boolean; + example?: any; + selector?: FieldSelector; + advanced?: boolean; + default?: any; +} + +export interface FieldSelector { + text?: SelectorText | null; + select?: SelectorSelect; + number?: SelectorNumber; + boolean?: null; + object?: null; + theme?: null; + addon?: null; + entity?: TargetData; + icon?: null; + color_rgb?: null; + color_temp?: SelectorColorTemp | null; + time?: null; +} + +interface SelectorColorTemp { + min_mireds: number; + max_mireds: number; +} + +interface SelectorNumber { + min: number; + max: number; + unit_of_measurement?: UnitOfMeasurement; + mode?: Mode; + step?: number; +} + +enum Mode { + Box = "box", +} + +enum UnitOfMeasurement { + Days = "days", + Empty = "%", + K = "K", + Seconds = "seconds", + Times = "times", +} + +interface SelectorSelect { + options: OptionElement[]; +} + +type OptionElement = OptionClass | string; + +interface OptionClass { + label: string; + value: string; +} + +interface SelectorText { + multiline: boolean; +} + + diff --git a/webapp/src/haService/index.ts b/webapp/src/haService/index.ts index 9e537ac..af234f8 100644 --- a/webapp/src/haService/index.ts +++ b/webapp/src/haService/index.ts @@ -6,11 +6,13 @@ import { DeviceRegistryItem } from "./types"; import { useHassCollection } from "./useHassCollection" import { useHAConnection } from './connection'; import { useSnackbar } from "notistack"; +import { TypedHassService } from "./fieldTypes"; -export type Option = string | ({ +export type BaseOption = { id: string, label: string, -} & T) +} & T +export type Option = string | BaseOption; export type EntityOption = Option<{ domain: string; }> export type HAEntitiesState = ReturnType; export const useHAEntities = () => { @@ -76,10 +78,33 @@ export const useHAEntities = () => { } } -export type ServiceOption = Option<{ domain: string, action: string, description: string }>; +export type ServiceOption = Option<{ + domain: string, + action: string, + description: string, + data: TypedHassService, +}>; +export type HAServicesState = ReturnType; 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 + } + }, getOptions(): ServiceOption[] { if (!services.ready) { return [] @@ -92,6 +117,12 @@ export const useHAServices = () => { 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); @@ -109,7 +140,7 @@ export const useHAServices = () => { } return opt.label ?? opt.id }, - getID: (opt: DeviceRegistryOption): string => { + getID: (opt: ServiceOption): string => { if (typeof opt === 'string') { return opt } diff --git a/webapp/src/haService/services.stories.tsx b/webapp/src/haService/services.stories.tsx index 4bc07e0..0a72673 100644 --- a/webapp/src/haService/services.stories.tsx +++ b/webapp/src/haService/services.stories.tsx @@ -1,85 +1,152 @@ import React, { FC, useEffect, useState } from "react"; -import { ComponentMeta, ComponentStory } from '@storybook/react'; +import { ComponentMeta, ComponentStory } from "@storybook/react"; import { Page } from "components/Page"; import { useHA } from "haService"; import InputYaml from "components/Inputs/InputYaml"; import { InputList } from "components/Inputs/InputList"; import { Button } from "components/Inputs/Button"; +import { ServiceEditor } from "components/ServiceEditor"; const Test: FC = () => { - const { services, callService } = useHA(); + const { services, callService } = useHA(); - const data = services.collection?.state ?? {}; - const options = Object.keys(data).sort(); + const data = services.collection?.state ?? {}; + const options = Object.keys(data).sort(); - const summary: Record }>> = {} - const fields: Record }>> = {} - const target: Record }>> = {} + // const flattened: any[] = []; + // Object.keys(data).forEach(domain => { + // Object.keys(data[domain]).forEach( + // service_name => { + // const service = data[domain][service_name]; + // const all: any = { + // domain, service_name, + // } - 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)) + // flattened.push({ + // domain, service_name, + // fields: Object.keys(service.fields).map(k => ({ + // name: k, + // data: service.fields[k] + // })), + // target: Object.keys(service.target ?? {}).map(k => ({ + // name: k, + // data: (service.target as any)[k] + // })) + // }) + // } + // ) + // }) - }) - 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)) + // console.log(flattened) - }) - 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 summary: Record }>> = {} + // const fields: Record }>> = {} + // const target: Record }>> = {} - const [domain, setDomain] = useState(options[0] ?? ""); + // 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)) - const domains = Object.keys(data[domain] ?? "").sort(); + // }) + // 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)) - const [service, setService] = useState(domains[0] ?? ""); + // }) + // 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)) + // }) + // } + // ) + // ) - useEffect(() => { - setService(domains[0] ?? "") - }, [domain, setService]) + const [domain, setDomain] = useState(options[0] ?? ""); + const domains = Object.keys(data[domain] ?? "").sort(); - return
- - - - { }} /> -
    { + setService(domains[0] ?? ""); + }, [domain, setService]); + + let serviceEditElm = <>Failed to load; + + try { + if (service) { + serviceEditElm = ( +
    + {}} + /> +
    + ); + } + } catch (err) { + serviceEditElm = <>{JSON.stringify(err)}; + } + + return ( +
    + + + + {serviceEditElm} + {}} /> + {JSON.stringify(serviceDefn, null, 4)} + + {/*
      @@ -131,21 +198,22 @@ const Test: FC = () => { )}
    )} -
+ */}
-} + ); +}; export default { - title: 'Services/HA Service', - component: Test, - parameters: { actions: { argTypesRegex: '^on.*' } }, - args: { - } -} as ComponentMeta + title: "Services/HA Service", + component: Test, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: {}, +} as ComponentMeta; -export const Base: ComponentStory = props => { - - return - +export const Base: ComponentStory = (props) => { + return ( + + -}; \ No newline at end of file + ); +};