Compare commits

...
4 Commits
Author SHA1 Message Date
Ari Sosnovsky f6ca454999 Update config.yaml 2022-06-14 18:17:56 -04:00
Ari Sosnovsky cdc5aa16b0 Update CHANGELOG.md 2022-06-14 18:17:28 -04:00
ari 7b816c3fbf v1 of service editor 2022-06-14 15:06:02 -04:00
ari 0cecae5faa reloading autos 2022-06-13 19:26:55 -04:00
23 changed files with 1280 additions and 453 deletions

No files matched your search

+5
View File
@@ -1,5 +1,10 @@
# Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge) # Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge)
## [0.1.21] - Service Editor
- first version of service editor
- reloading automations on save
## [0.1.20] - UI Bugfixes ## [0.1.20] - UI Bugfixes
- Using MUI elements for input time - Using MUI elements for input time
+1 -1
View File
@@ -1,5 +1,5 @@
name: Shortumation name: Shortumation
version: v0.1.20 version: v0.1.21
slug: shortumation slug: shortumation
image: asosnovsky/shortumation-{arch} image: asosnovsky/shortumation-{arch}
url: "https://github.com/asosnovsky/Shortumation" url: "https://github.com/asosnovsky/Shortumation"
+3 -3
View File
@@ -5,7 +5,7 @@ import { AutomationAPI } from './automations';
export const useDefaultApiState = () => useState<ApiState>({ export const useDefaultApiState = () => useState<ApiState>({
automations: {ready: false}, automations: { ready: false },
}); });
export const makeReloadAutomations = ( export const makeReloadAutomations = (
@@ -21,8 +21,8 @@ export const makeReloadAutomations = (
const resp = await automationAPI.list(params); const resp = await automationAPI.list(params);
setState({ setState({
...state, automations: { ...state, automations: {
ready: true, ready: true,
...resp, ...resp,
} }
}); });
} }
@@ -46,6 +46,7 @@ export const AutomationEditor: FC<Props> = ({
if (dims.flipped !== flipped) { if (dims.flipped !== flipped) {
setFlipped(dims.flipped) setFlipped(dims.flipped)
} }
// eslint-disable-next-line
}, [dims.flipped]) }, [dims.flipped])
// render // render
@@ -18,7 +18,12 @@ export type Props = {
} }
const useAutomationListBoxState = () => { const useAutomationListBoxState = () => {
const [cookies, setCookies, _] = useCookies(['albSearchText', 'albSelected']); const [
cookies,
setCookies,
// eslint-disable-next-line
_
] = useCookies(['albSearchText', 'albSelected']);
let initialSelected = []; let initialSelected = [];
try { try {
initialSelected = JSON.parse(cookies.albSelected) initialSelected = JSON.parse(cookies.albSelected)
+19 -4
View File
@@ -14,6 +14,7 @@ import { makeTagDB } from "./TagDB";
import LinearProgress from "@mui/material/LinearProgress"; import LinearProgress from "@mui/material/LinearProgress";
import CircularProgress from "@mui/material/CircularProgress"; import CircularProgress from "@mui/material/CircularProgress";
import { useCookies } from 'react-cookie'; import { useCookies } from 'react-cookie';
import { useHA } from "haService";
interface AutomationListParams { interface AutomationListParams {
@@ -26,11 +27,15 @@ interface AutomationListParams {
} }
export const useAutomationListState = () => { export const useAutomationListState = () => {
const [cookies, setCookies, _] = useCookies(['alCurrent']); const [
cookies,
setCookies,
// eslint-disable-next-line
_
] = useCookies(['alCurrent']);
let initialCurrent = 0; let initialCurrent = 0;
try { try {
initialCurrent = Number(cookies.alCurrent ?? '0'); initialCurrent = Number(cookies.alCurrent ?? '0');
// eslint-disable-next-line
} catch (_) { } } catch (_) { }
const [hideList, setHideList] = useState(false); const [hideList, setHideList] = useState(false);
@@ -109,11 +114,21 @@ export const ConnectedAutomationList: FC<ConnectedAutomationListParams> = ({
state: { state: {
automations, automations,
}, },
removeAutomation, ...methods
updateAutomation,
}, },
dims dims
}) => { }) => {
const { reloadAutomations } = useHA();
const removeAutomation = async (args: any) => {
const resp = await methods.removeAutomation(args)
await reloadAutomations();
return resp
}
const updateAutomation = async (args: any) => {
const resp = await methods.updateAutomation(args)
await reloadAutomations();
return resp
}
if (!automations.ready) { if (!automations.ready) {
return <div className="automation-list--root loading"> return <div className="automation-list--root loading">
<LinearProgress /> <LinearProgress />
+190 -138
View File
@@ -1,152 +1,204 @@
import "./InputAutoComplete.css"; import "./InputAutoComplete.css";
import { FC } from "react"; import { Option } from "haService";
import { Option } from 'haService'; import Autocomplete from "@mui/material/Autocomplete";
import Autocomplete from '@mui/material/Autocomplete'; import TextField from "@mui/material/TextField";
import TextField from '@mui/material/TextField'; import Chip from "@mui/material/Chip";
import Chip from '@mui/material/Chip';
import { Badge } from "@mui/material"; import { Badge } from "@mui/material";
import { SearchItem } from "./extras"; import { SearchItem } from "./extras";
export type InputAutoCompleteProps<T extends Option<any>> = { export type InputAutoCompleteProps<T extends Option<any>> = {
validateOption?: (v: string[]) => string[] | null; className?: string;
groupBy?: (opt: T) => string; validateOption?: (v: string[]) => string[] | null;
options: T[]; groupBy?: (opt: T) => string;
getLabel: (opt: T) => string; options: T[];
getID: (opt: T) => string; getLabel?: (opt: T) => string;
getID?: (opt: T) => string;
helperText?: string;
} & InputAutoCompletePropsBase; } & InputAutoCompletePropsBase;
export type InputAutoCompletePropsBase = { export type InputAutoCompletePropsBase = {
label?: string; label?: string;
} & ({ } & (
value: string | null; | {
multiple?: false; value: string | null;
onChange: (v: string | null) => void; multiple?: false;
} | { onChange: (v: string | null) => void;
value: string | string[];
multiple: true;
onChange: (v: string[]) => void;
})
export const InputAutoComplete: FC<InputAutoCompleteProps<any>> = 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 = <Badge
className="input-autocomplete--errors"
badgeContent={errors.length} color="error"
>
<ul title={errors.join(', and')}>{errors.map((msg, i) => <li key={i}>
{msg}
</li>)}</ul>
</Badge>
}
} }
// events | {
const onChange = (_e: any, v: any) => { value: string | string[];
const cleanValue: string[] = v === null ? [] : multiple: true;
Array.isArray(v) ? v.map(opt => { onChange: (v: string[]) => void;
if (typeof opt === 'string') { }
return opt );
}
return opt.id export function InputAutoComplete<T extends Option>(
}) : [v]; props: InputAutoCompleteProps<T>
) {
// 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 = (
<Badge
className="input-autocomplete--errors"
badgeContent={errors.length}
color="error"
>
<ul title={errors.join(", and")}>
{errors.map((msg, i) => (
<li key={i}>{msg}</li>
))}
</ul>
</Badge>
);
}
}
// events
const onChange = (_e: any, v: any) => {
const cleanValue: string[] =
v === null
? []
: Array.isArray(v)
? v.map((opt) => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
})
: [v];
if (props.multiple) {
props.onChange(cleanValue);
} else {
props.onChange(cleanValue[cleanValue.length - 1]);
}
};
return (
<Autocomplete
className={["input-autocomplete", props.className ?? ""].join(" ")}
multiple={true}
freeSolo
value={value}
options={options}
onChange={onChange}
getOptionLabel={getLabel as any}
filterOptions={(opts, s) => {
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 (
<SearchItem
key={label + id}
listProps={listProps}
id={id}
label={label}
searchTerm={inputValue}
/>
);
}}
renderInput={(params) => (
<TextField
{...params}
variant="filled"
label={props.label ?? "Entity ID"}
helperText={helperText}
error={error}
/>
)}
renderTags={(tagValue, getTagProps) => {
const inner = (
<div className="input-autocomplete--tags">
{tagValue.map((option, index) => {
const label = getLabel(option);
const id = getID(option);
const tagProps = getTagProps({ index });
tagProps.className += " input-autocomplete--chip";
return (
<Chip
size="medium"
label={
<>
{id === label ? <span>{label}</span> : <b>{label}</b>}
{id !== label && <small>{id}</small>}
</>
}
{...tagProps}
/>
);
})}
</div>
);
if (props.multiple) { if (props.multiple) {
props.onChange(cleanValue); return (
<Badge badgeContent={tagValue.length} color="info">
{inner}
</Badge>
);
} else { } else {
props.onChange(cleanValue[cleanValue.length - 1]) return inner;
}
}
return <Autocomplete
className="input-autocomplete"
multiple={true}
freeSolo
value={value}
options={options}
onChange={onChange}
getOptionLabel={props.getLabel}
filterOptions={(opts, s) => {
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 <SearchItem
listProps={listProps}
id={id}
label={label}
searchTerm={inputValue}
/>
}}
renderInput={params => <TextField
{...params}
variant="filled"
label={props.label ?? "Entity ID"}
helperText={helperText}
error={error}
/>}
renderTags={(tagValue, getTagProps) => {
const inner = <div className="input-autocomplete--tags">
{tagValue.map((option, index) => {
const label = props.getLabel(option);
const id = props.getID(option);
const tagProps = getTagProps({ index });
tagProps.className += ' input-autocomplete--chip'
return (
<Chip
size="medium"
label={<>
{(id === label) ? <span>{label}</span> : <b>{label}</b>}
{(id !== label) && <small>{id}</small>}
</>}
{...tagProps}
/>
)
})}
</div>
if (props.multiple) {
return <Badge badgeContent={tagValue.length} color="info">
{inner}
</Badge>
} else {
return inner
}
}
} }
}}
/> />
);
} }
+55 -35
View File
@@ -1,21 +1,26 @@
import { FC } from "react"; import FormHelperText from "@mui/material/FormHelperText";
import FormHelperText from '@mui/material/FormHelperText'; import InputLabel from "@mui/material/InputLabel";
import InputLabel from '@mui/material/InputLabel'; import MenuItem from "@mui/material/MenuItem";
import MenuItem from '@mui/material/MenuItem'; import FormControl from "@mui/material/FormControl";
import FormControl from '@mui/material/FormControl'; import Select from "@mui/material/Select";
import Select from '@mui/material/Select';
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { ReactNode } from "react";
export interface Props<T extends string> { export type Props<T extends string | Object> = {
current: T; current?: T;
options: readonly T[]; options: readonly T[];
onChange: (n: T) => void; onChange: (n: T) => void;
label: string; label: string;
id?: string; id?: string;
className?: string; className?: string;
prettyOptionLabels?: boolean; prettyOptionLabels?: boolean;
} getKey?: (n: T) => string;
export function InputList<T extends string>({ placeholder?: any;
title?: string;
helperText?: string;
endAdornment?: ReactNode;
};
export function InputList<T extends string | Object>({
current, current,
options, options,
onChange, onChange,
@@ -23,32 +28,47 @@ export function InputList<T extends string>({
id, id,
className, className,
prettyOptionLabels, prettyOptionLabels,
getKey = String,
placeholder,
title,
helperText,
endAdornment,
}: Props<T>) { }: Props<T>) {
const invalidCurrent = current && !options.includes(current); const invalidCurrent =
return <FormControl className={className} variant="filled" sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}> current && !options.map(getKey).includes(getKey(current));
<InputLabel>{label}</InputLabel> return (
<Select <FormControl
autoWidth className={className}
id={id}
value={current}
onChange={(e) => {
onChange(e.target.value as T)
}}
label={label}
variant="filled" variant="filled"
placeholder={label} sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}
error={invalidCurrent}
> >
{options.map((t, i) => ( <InputLabel>{label}</InputLabel>
<MenuItem <Select
key={i} title={title}
value={t} placeholder={placeholder ?? label}
> endAdornment={endAdornment}
{prettyOptionLabels ? prettyName(t) : t} autoWidth
</MenuItem> id={id}
))} value={current ? getKey(current) : ""}
</Select> onChange={(e) => {
<FormHelperText>{invalidCurrent ? `'${current}' is not a valid selection` : ''}</FormHelperText> const key = e.target.value;
</FormControl> const option = options.filter((opt) => getKey(opt) === key)[0];
onChange(option);
}}
label={label}
variant="filled"
error={invalidCurrent}
fullWidth
>
{options.map((t, i) => (
<MenuItem key={i} value={getKey(t)}>
{prettyOptionLabels ? prettyName(getKey(t)) : getKey(t)}
</MenuItem>
))}
</Select>
<FormHelperText variant="filled" error={invalidCurrent}>
{invalidCurrent ? `'${current}' is not a valid selection` : helperText}
</FormHelperText>
</FormControl>
);
} }
+43 -25
View File
@@ -5,39 +5,57 @@ import InputAdornment from "@mui/material/InputAdornment";
import Edit from "@mui/icons-material/Edit"; import Edit from "@mui/icons-material/Edit";
export interface Props { export interface Props {
label: string; label: string | JSX.Element;
value: number | undefined; value: number | undefined;
onChange: (v: number | undefined) => void; onChange: (v: number | undefined) => void;
className?: string; className?: string;
min?: number, min?: number;
max?: number, max?: number;
step?: number, step?: number;
unit?: string;
placeholder?: any;
required?: boolean;
} }
export default function InputNumber({ export default function InputNumber({
label, label,
value = undefined, value = undefined,
onChange, onChange,
className = "", className = "",
min, max, step, min,
max,
step,
unit,
placeholder,
required,
}: Props) { }: Props) {
const disabled = (value === undefined) || (value === null); const disabled = value === undefined || value === null;
return <TextField return (
variant="filled" <TextField
label={label} variant="filled"
value={value} label={label}
defaultValue={value} value={value}
onChange={e => onChange(Number(e.target.value ?? 0))} defaultValue={value}
disabled={disabled} onChange={(e) => onChange(Number(e.target.value ?? 0))}
className={className} disabled={disabled}
InputProps={{ className={className}
endAdornment: <InputAdornment position="end"> placeholder={placeholder}
<IconButton onClick={() => onChange(disabled ? 0 : undefined)}> required={required}
{disabled ? <Edit /> : <Close />} InputProps={{
</IconButton> endAdornment: (
</InputAdornment>, <InputAdornment position="end">
inputProps: { {unit}
min, max, type: 'number' <IconButton onClick={() => onChange(disabled ? 0 : undefined)}>
} {disabled ? <Edit /> : <Close />}
}} </IconButton>
/> </InputAdornment>
),
inputProps: {
min,
max,
type: "number",
step,
},
}}
/>
);
} }
+63 -36
View File
@@ -1,11 +1,11 @@
import { PropsWithChildren, useState } from "react"; import React, { PropsWithChildren, ReactNode, useState } from "react";
import { useToolTip } from "tooltip/context"; import { useToolTip } from "tooltip/context";
import TextField from '@mui/material/TextField'; import TextField from "@mui/material/TextField";
import InputWrapper from "./InputWrapper"; import InputWrapper from "./InputWrapper";
export interface Props { export interface Props {
textBoxFor?: string; textBoxFor?: string;
label: string; label: string | JSX.Element;
value: string; value: string;
onChange: (v: string) => void; onChange: (v: string) => void;
onEnter?: () => void; onEnter?: () => void;
@@ -13,50 +13,77 @@ export interface Props {
multiline?: boolean; multiline?: boolean;
maxRows?: number; maxRows?: number;
className?: string; className?: string;
placeholder?: any;
title?: string;
helperText?: string;
endAdornment?: ReactNode;
required?: boolean;
} }
export default function InputText({ export default function InputText({
label, label,
title,
helperText,
textBoxFor, textBoxFor,
value = "", value = "",
onChange, onChange,
onEnter = () => { }, endAdornment,
onEnter = () => {},
additionalTooltipFilters = {}, additionalTooltipFilters = {},
multiline = false, multiline = false,
maxRows = 4, maxRows = 4,
children, children,
className, className,
placeholder,
required,
}: PropsWithChildren<Props>) { }: PropsWithChildren<Props>) {
const tooltip = useToolTip(); const tooltip = useToolTip();
const [isFocused, setIsFocused] = useState(false) const [isFocused, setIsFocused] = useState(false);
return <InputWrapper className={className} label=""> return (
<TextField multiline={multiline} maxRows={maxRows} fullWidth inputMode="text" variant="filled" focused={isFocused} label={label} value={value} <InputWrapper className={className} label="">
onKeyDown={e => { <TextField
if (e.key === 'Enter') { multiline={multiline}
onEnter(); maxRows={maxRows}
} fullWidth
}} inputMode="text"
onChange={e => { variant="filled"
e.preventDefault(); focused={isFocused}
onChange(e.target.value) label={label}
}} value={value}
onBlur={() => { title={title}
setIsFocused(false) helperText={helperText}
}} placeholder={placeholder}
onFocus={e => { InputProps={{
setIsFocused(true) endAdornment,
if (textBoxFor) { }}
tooltip.setFocus( required={required}
e.target.getBoundingClientRect(), onKeyDown={(e) => {
{ if (e.key === "Enter") {
searchObject: textBoxFor, onEnter();
searchText: value, }
filterObjects: additionalTooltipFilters, }}
}, onChange={(e) => {
onChange e.preventDefault();
) onChange(e.target.value);
} }}
}} onBlur={() => {
/> setIsFocused(false);
{children} }}
</InputWrapper> onFocus={(e) => {
setIsFocused(true);
if (textBoxFor) {
tooltip.setFocus(
e.target.getBoundingClientRect(),
{
searchObject: textBoxFor,
searchText: value,
filterObjects: additionalTooltipFilters,
},
onChange
);
}
}}
/>
{children}
</InputWrapper>
);
} }
+2 -6
View File
@@ -5,13 +5,8 @@ import EditIcon from '@mui/icons-material/Edit';
import CloseIcon from "@mui/icons-material/Close"; import CloseIcon from "@mui/icons-material/Close";
import IconButton from "@mui/material/IconButton" import IconButton from "@mui/material/IconButton"
import { AutomationTime, AutomationTimeObject } from "types/automations/common"; import { AutomationTime, AutomationTimeObject } from "types/automations/common";
import { convertAutomationTimeToTimeObject, convertObjectToAutomationTimeString, milisecondsToObject } from "utils/time"; import { convertAutomationTimeToTimeObject, convertObjectToAutomationTimeString, convertAutomationTimeToTimeString } from 'utils/time';
import { convertStringToAutomationTimeObject, convertAutomationTimeToTimeString } from 'utils/time';
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import FormControl from "@mui/material/FormControl";
import InputLabel from '@mui/material/InputLabel';
import Input from "@mui/material/Input";
import FormHelperText from '@mui/material/FormHelperText';
// constants // constants
const fields: Array<keyof AutomationTimeObject> = [ const fields: Array<keyof AutomationTimeObject> = [
@@ -120,6 +115,7 @@ export const InputTime: FC<Props> = (props) => {
props.onChange(displayValue) props.onChange(displayValue)
} }
} }
// eslint-disable-next-line
}, [disabled, displayValue]) }, [disabled, displayValue])
@@ -1,8 +1,7 @@
import { InputService } from "components/Inputs/InputService"; import { InputService } from "components/Inputs/InputService";
import InputYaml from 'components/Inputs/InputYaml'; import { ServiceEditor } from "components/ServiceEditor";
import { ServiceAction } from "types/automations/actions"; import { ServiceAction } from "types/automations/actions";
import { OptionManager, updateActionData } from './OptionManager'; import { OptionManager, updateActionData } from "./OptionManager";
export const ActionCallServiceState: OptionManager<ServiceAction> = { export const ActionCallServiceState: OptionManager<ServiceAction> = {
defaultState: () => ({ defaultState: () => ({
@@ -10,29 +9,34 @@ export const ActionCallServiceState: OptionManager<ServiceAction> = {
target: {}, target: {},
data: {}, data: {},
}), }),
isReady: ({ isReady: ({ service }) => service !== "",
service, Component: ({ state, setState, services }) => {
}) => (
service !== ''
),
renderOptionList: (state, setState) => {
const { service, target, data } = state; const { service, target, data } = state;
const update = updateActionData(state, setState); const update = updateActionData(state, setState);
return <> const serviceOption = services.getOption(service);
<InputService return (
value={service} <>
onChange={(service: string | null) => update({ service: service ?? "" })} <InputService
/> value={service}
<InputYaml onChange={(service: string | null) =>
label="Target" update({ service: service ?? "" })
value={target} }
onChange={target => update({ target })} />
/> {serviceOption && (
<InputYaml <ServiceEditor
label="Data" key={service}
value={data} serviceId={service}
onChange={data => update({ data })} service={serviceOption}
/> data={{ target, field: data }}
</> onUpdate={({ target, field }) =>
} update({
} target,
data: field,
})
}
/>
)}
</>
);
},
};
@@ -1,4 +1,4 @@
import { HAEntitiesState } from 'haService'; import { HAEntitiesState, HAServicesState } from 'haService';
import { FC } from 'react'; import { FC } from 'react';
import { AutomationAction } from 'types/automations/actions'; import { AutomationAction } from 'types/automations/actions';
import { AutomationCondition } from 'types/automations/conditions'; import { AutomationCondition } from 'types/automations/conditions';
@@ -12,6 +12,7 @@ export type OptionManager<T> = {
state: T, state: T,
setState: (s: T) => void, setState: (s: T) => void,
entities: HAEntitiesState, entities: HAEntitiesState,
services: HAServicesState,
}> }>
}) })
@@ -1,45 +1,61 @@
import { Dispatch, SetStateAction, useEffect, useState, Component } from 'react'; import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { AutomationNode, AutomationNodeTypes } from 'types/automations'; import { AutomationNode, AutomationNodeTypes } from "types/automations";
import { AutomationNodeSubtype } from 'types/automations'; import { AutomationNodeSubtype } from "types/automations";
import { getOptionManager } from './getOptionManager'; import { getOptionManager } from "./getOptionManager";
import { getNodeSubType, getSubTypeList, validateNode } from 'utils/automations'; import {
import InputYaml from 'components/Inputs/InputYaml'; getNodeSubType,
import InputText from 'components/Inputs/InputText'; getSubTypeList,
import { getDescriptionFromAutomationNode } from 'utils/formatting'; validateNode,
import { useHA } from 'haService'; } from "utils/automations";
import { Generic } from './Generic'; import InputYaml from "components/Inputs/InputYaml";
import { getNodeTypeAndValidate } from '../../../utils/automations'; import InputText from "components/Inputs/InputText";
import InputBoolean from 'components/Inputs/InputBoolean'; import { getDescriptionFromAutomationNode } from "utils/formatting";
import { useHA } from "haService";
import { Generic } from "./Generic";
import { getNodeTypeAndValidate } from "utils/automations";
type UseState = <S>(s: S) => [S, Dispatch<SetStateAction<S>>] type UseState = <S>(s: S) => [S, Dispatch<SetStateAction<S>>];
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 // state
const [allState, setAllState] = uState({ const [allState, setAllState] = uState({
yamlMode: false, yamlMode: false,
isModified: false, isModified: false,
...computeInvalidYaml(originalNode, allowedTypes) ...computeInvalidYaml(originalNode, allowedTypes),
}); });
const { entities, namer } = useHA(); const { entities, namer, services } = useHA();
// aliases // aliases
const { node: currentNode, isModified, yamlMode, invalidManualYaml } = allState; const {
node: currentNode,
isModified,
yamlMode,
invalidManualYaml,
} = allState;
// effects // effects
useEffect(() => { useEffect(() => {
setAllState({ ...allState, node: originalNode, isModified: false, }) setAllState({ ...allState, node: originalNode, isModified: false });
// eslint-disable-next-line // eslint-disable-next-line
}, [originalNode]) }, [originalNode]);
// function aliases // function aliases
const setState = (node: AutomationNode) => setAllState(({ const setState = (node: AutomationNode) =>
...allState, node, setAllState({
isModified: JSON.stringify(node) !== JSON.stringify(originalNode), ...allState,
})); node,
const setYamlMode = (yamlMode: boolean) => setAllState({ ...allState, yamlMode, }); isModified: JSON.stringify(node) !== JSON.stringify(originalNode),
});
const setYamlMode = (yamlMode: boolean) =>
setAllState({ ...allState, yamlMode });
const setStateForManualYaml = (yaml: any) => { const setStateForManualYaml = (yaml: any) => {
setAllState({ setAllState({
...allState, ...allState,
...computeInvalidYaml(yaml, allowedTypes) ...computeInvalidYaml(yaml, allowedTypes),
}) });
} };
// value aliases // value aliases
const { const {
originalNodeType, originalNodeType,
@@ -48,7 +64,7 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
subType, subType,
subTypes, subTypes,
optionManager, optionManager,
} = createData(originalNode, currentNode, allowedTypes) } = createData(originalNode, currentNode, allowedTypes);
// publuc // publuc
return { return {
nodeType, nodeType,
@@ -60,91 +76,119 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
isErrored: allState.isErrored, isErrored: allState.isErrored,
get prettyNodeType() { get prettyNodeType() {
if (nodeType) { if (nodeType) {
return `${nodeType.slice(0, 1).toUpperCase()}${nodeType.slice(1)} Type` return `${nodeType.slice(0, 1).toUpperCase()}${nodeType.slice(1)} Type`;
} else { } else {
return 'n/a' return "n/a";
} }
}, },
get yamlMode() { get yamlMode() {
return allState.isErrored || yamlMode return allState.isErrored || yamlMode;
}, },
get data() { get data() {
return currentNode return currentNode;
}, },
setEnabled(enabled: boolean) { setEnabled(enabled: boolean) {
setState({ setState({
...currentNode, ...currentNode,
enabled, enabled,
}) });
}, },
renderOptionList() { renderOptionList() {
let aliasEditor = <></> let aliasEditor = <></>;
if (nodeType === 'trigger') { if (nodeType === "trigger") {
aliasEditor = <InputText aliasEditor = (
key="alias" <InputText
label="Trigger ID" key="alias"
value={(allState.node as any).id} label="Trigger ID"
onChange={id => setState({ value={(allState.node as any).id}
...allState.node, onChange={(id) =>
id setState({
} as any)} ...allState.node,
/> id,
} as any)
}
/>
);
} }
if (nodeType === 'action') { if (nodeType === "action") {
aliasEditor = <InputText aliasEditor = (
key="alias" <InputText
label="Alias" key="alias"
value={getDescriptionFromAutomationNode(allState.node, namer)} label="Alias"
onChange={alias => setState({ value={getDescriptionFromAutomationNode(allState.node, namer)}
...allState.node, onChange={(alias) =>
alias setState({
} as any)} ...allState.node,
/> alias,
} as any)
}
/>
);
} }
if (yamlMode || allState.isErrored) { if (yamlMode || allState.isErrored) {
return <> return (
{aliasEditor} <>
<InputYaml {aliasEditor}
label='' <InputYaml
value={currentNode} label=""
onChange={setStateForManualYaml} value={currentNode}
error={invalidManualYaml} onChange={setStateForManualYaml}
/> error={invalidManualYaml}
</> />
</>
);
} }
return <> return (
{aliasEditor} <>
{('renderOptionList' in optionManager) ? {aliasEditor}
optionManager.renderOptionList(currentNode, setState, entities) : {"renderOptionList" in optionManager ? (
<optionManager.Component state={currentNode} setState={setState} entities={entities} />} optionManager.renderOptionList(currentNode, setState, entities)
</>; ) : (
<optionManager.Component
state={currentNode}
setState={setState}
entities={entities}
services={services}
/>
)}
</>
);
}, },
isReady() { isReady() {
return optionManager.isReady(currentNode); return optionManager.isReady(currentNode);
}, },
setNodeType(newType: AutomationNodeTypes) { setNodeType(newType: AutomationNodeTypes) {
if (newType === originalNodeType) { if (newType === originalNodeType) {
setState(originalNode) setState(originalNode);
} else { } else {
setState(getOptionManager(newType, getSubTypeList(newType)[0]).defaultState()) setState(
getOptionManager(newType, getSubTypeList(newType)[0]).defaultState()
);
} }
}, },
setSubType(newSubType: AutomationNodeSubtype) { setSubType(newSubType: AutomationNodeSubtype) {
if (newSubType === originalNodeSubType) { if (newSubType === originalNodeSubType) {
setState(originalNode) setState(originalNode);
} else { } else {
if (nodeType) { if (nodeType) {
setState(getOptionManager(nodeType, newSubType as any).defaultState()) setState(
getOptionManager(nodeType, newSubType as any).defaultState()
);
} else { } else {
setState(getOptionManager(allowedTypes[0], newSubType as any).defaultState()) setState(
getOptionManager(allowedTypes[0], newSubType as any).defaultState()
);
} }
} }
} },
} };
} };
const createData = (
const createData = (originalNode: AutomationNode, currentNode: AutomationNode, allowedTypes: AutomationNodeTypes[]) => { originalNode: AutomationNode,
currentNode: AutomationNode,
allowedTypes: AutomationNodeTypes[]
) => {
let originalNodeType: AutomationNodeTypes = allowedTypes[0]; let originalNodeType: AutomationNodeTypes = allowedTypes[0];
let originalNodeSubType: AutomationNodeSubtype | null = null; let originalNodeSubType: AutomationNodeSubtype | null = null;
let nodeType: AutomationNodeTypes = originalNodeType; let nodeType: AutomationNodeTypes = originalNodeType;
@@ -156,15 +200,15 @@ const createData = (originalNode: AutomationNode, currentNode: AutomationNode, a
originalNodeType = getNodeTypeAndValidate(originalNode, allowedTypes); originalNodeType = getNodeTypeAndValidate(originalNode, allowedTypes);
originalNodeSubType = getNodeSubType(originalNode); originalNodeSubType = getNodeSubType(originalNode);
} catch (err) { } catch (err) {
console.error(`ORIGINAL NODE ERROR ${JSON.stringify(originalNode)}`) console.error(`ORIGINAL NODE ERROR ${JSON.stringify(originalNode)}`);
} }
try { try {
nodeType = getNodeTypeAndValidate(currentNode, allowedTypes); nodeType = getNodeTypeAndValidate(currentNode, allowedTypes);
subType = getNodeSubType(currentNode); subType = getNodeSubType(currentNode);
subTypes = getSubTypeList(nodeType) subTypes = getSubTypeList(nodeType);
optionManager = getOptionManager(nodeType, subType as any); optionManager = getOptionManager(nodeType, subType as any);
} catch (err) { } catch (err) {
console.error(`CURRENT NODE ERROR ${JSON.stringify(currentNode)}`) console.error(`CURRENT NODE ERROR ${JSON.stringify(currentNode)}`);
} }
return { return {
originalNodeType, originalNodeType,
@@ -173,27 +217,34 @@ const createData = (originalNode: AutomationNode, currentNode: AutomationNode, a
subType, subType,
subTypes, subTypes,
optionManager, optionManager,
} };
} };
const computeInvalidYaml = (node: AutomationNode, allowedNodeTypes: AutomationNodeTypes[]) => { const computeInvalidYaml = (
node: AutomationNode,
allowedNodeTypes: AutomationNodeTypes[]
) => {
const errors = validateNode(node, allowedNodeTypes); const errors = validateNode(node, allowedNodeTypes);
if (errors) { if (errors) {
console.log({ errors }) console.log({ errors });
return { return {
node, node,
isErrored: true, isErrored: true,
invalidManualYaml: <ul key={'error'} className="node-editor--error"> invalidManualYaml: (
{errors.map(({ message, path }, i) => <li key={i}> <ul key={"error"} className="node-editor--error">
<b>{path}</b>: {message} {errors.map(({ message, path }, i) => (
</li>)} <li key={i}>
</ul> <b>{path}</b>: {message}
} </li>
))}
</ul>
),
};
} else { } else {
return { return {
node, node,
isErrored: false, isErrored: false,
invalidManualYaml: <></> invalidManualYaml: <></>,
} };
} }
} };
@@ -0,0 +1,5 @@
.service-editor--field {
display: flex;
flex-direction: row;
align-items: center;
}
@@ -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<ServiceEditorFieldProps> = ({
option,
value,
onChange,
onRemove,
}) => {
const description = option.data.description ?? "";
const isRequired = !onRemove;
const label = option.label;
let example = "";
const removeIcon = !onRemove ? (
<></>
) : (
<IconButton className="service-editor--field--remove" onClick={onRemove}>
<RemoveCircle />
</IconButton>
);
let input = (
<InputText
className="service-editor--field"
label={label}
value={value}
onChange={onChange}
endAdornment={removeIcon}
required={isRequired}
/>
);
if (option.type === "field") {
example = option.data.example ? `Example: ${option.data.example}` : "";
if (option.data.selector?.number) {
return (
<InputNumber
className="service-editor--field"
label={label}
value={value ?? option.data.default}
min={option.data.selector.number.min}
max={option.data.selector.number.max}
step={option.data.selector.number.step}
unit={option.data.selector.number.unit_of_measurement}
onChange={onChange}
required={isRequired}
placeholder={example}
/>
);
}
return (
<InputText
className="service-editor--field"
label={label}
title={description}
helperText={description}
value={value ?? option.data.default}
onChange={onChange}
placeholder={example}
required={isRequired}
endAdornment={removeIcon}
/>
);
}
return input;
};
@@ -0,0 +1,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;
}
@@ -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<typeof ServiceEditor>;
const Template: ComponentStory<typeof ServiceEditor> = (props) => {
return (
<Page>
<ServiceEditor {...props} />
<code>{JSON.stringify(props.service)}</code>
</Page>
);
};
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" } },
});
@@ -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<string, any>;
target: Record<string, any>;
};
export type ServiceEditorProps = {
serviceId: string;
service: TypedHassService;
data: ServiceEditorData;
onUpdate: (d: ServiceEditorData) => void;
};
export const ServiceEditor: FC<ServiceEditorProps> = ({
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 (
<div className="service-editor">
<div className="service-editor--name">
<b>
{service.name} /<span>{serviceId}</span>
</b>
<span>{service.description}</span>
</div>
{hasNothing ? (
<span>This Service Requires no inputs</span>
) : (
<>
{options.required.map((opt) => (
<ServiceEditorField
key={opt.type + opt.id}
option={opt}
value={data[opt.type][opt.id]}
onChange={(v) =>
onUpdate({
...data,
[opt.type]: {
...data[opt.type],
[opt.id]: v,
},
})
}
/>
))}
<div className="service-editor--used">
{additionalFields.field.map((key) => {
const serviceData = service.fields[key];
const option = convertFieldToOption(key, serviceData);
return (
<ServiceEditorField
key={"fields-" + key}
option={option}
value={data.field[key] ?? ""}
onRemove={() => {
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 (
<ServiceEditorField
key={"fields-" + key}
option={option}
value={data.target[key] ?? ""}
onRemove={() => {
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,
},
})
}
/>
);
})}
</div>
</>
)}
<hr style={{ width: "90%" }} />
{additionalFields.optionalList.length > 0 && (
<div className="service-editor--add">
<InputAutoComplete
label="Additional Field"
helperText="Include an additional none-optional fields from this list."
className="service-editor--add--list"
value={""}
onChange={(id) => {
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}
/>
</div>
)}
</div>
);
};
@@ -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 };
};
+83
View File
@@ -0,0 +1,83 @@
export interface TypedHassService {
name?: string;
description: string;
fields: Fields;
target?: Targets | null | undefined;
}
export type Fields = Record<string, FieldData>
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;
}
+81 -4
View File
@@ -4,11 +4,15 @@ import { deviceRegistryColl } from "./DeviceRegistry";
import { entityRegistryColl } from "./EntityRegistry"; import { entityRegistryColl } from "./EntityRegistry";
import { DeviceRegistryItem } from "./types"; import { DeviceRegistryItem } from "./types";
import { useHassCollection } from "./useHassCollection" import { useHassCollection } from "./useHassCollection"
import { useHAConnection } from './connection';
import { useSnackbar } from "notistack";
import { TypedHassService } from "./fieldTypes";
export type Option<T = {}> = string | ({ export type BaseOption<T = {}> = {
id: string, id: string,
label: string, label: string,
} & T) } & T
export type Option<T = {}> = string | BaseOption<T>;
export type EntityOption = Option<{ domain: string; }> export type EntityOption = Option<{ domain: string; }>
export type HAEntitiesState = ReturnType<typeof useHAEntities>; export type HAEntitiesState = ReturnType<typeof useHAEntities>;
export const useHAEntities = () => { export const useHAEntities = () => {
@@ -74,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<typeof useHAServices>;
export const useHAServices = () => { export const useHAServices = () => {
const services = useHassCollection(servicesColl); const services = useHassCollection(servicesColl);
const methods = { 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[] { getOptions(): ServiceOption[] {
if (!services.ready) { if (!services.ready) {
return [] return []
@@ -90,6 +117,12 @@ export const useHAServices = () => {
description: services.collection.state[domain][action].description ?? "", description: services.collection.state[domain][action].description ?? "",
domain, domain,
action, 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); return all.concat(opts);
@@ -107,7 +140,7 @@ export const useHAServices = () => {
} }
return opt.label ?? opt.id return opt.label ?? opt.id
}, },
getID: (opt: DeviceRegistryOption): string => { getID: (opt: ServiceOption): string => {
if (typeof opt === 'string') { if (typeof opt === 'string') {
return opt return opt
} }
@@ -165,6 +198,48 @@ export const useHA = () => {
const entities = useHAEntities(); const entities = useHAEntities();
const devices = useHADeviceRegistry(); const devices = useHADeviceRegistry();
const services = useHAServices(); const services = useHAServices();
const conn = useHAConnection();
const { enqueueSnackbar } = useSnackbar();
const callService = async (
domain: string,
service: string,
data: any = {},
target: any = {},
) => {
if (conn.status === 'loaded') {
try {
const result = await conn.connection.sendMessagePromise({
"type": "call_service",
domain,
service,
target,
service_data: data
})
enqueueSnackbar(`Successfully called ${domain}.${service}`, {
"variant": "success",
})
return result
} catch (err: any) {
let msg = JSON.stringify(err)
if ('message' in err) {
msg = err.message
}
enqueueSnackbar(`Failed to call ${domain}.${service} because '${msg}'`, {
"variant": "error",
})
return
}
} if (conn.status === 'error') {
enqueueSnackbar(`Failed to call service because connection is '${conn.status}' -- ${conn.error}`, {
"variant": "error"
})
} else {
enqueueSnackbar(`Failed to call service because connection is '${conn.status}'`, {
"variant": "error"
})
}
}
const namer: Namer = { const namer: Namer = {
getDeviceName(device_id) { getDeviceName(device_id) {
@@ -186,5 +261,7 @@ export const useHA = () => {
devices, devices,
services, services,
namer, namer,
callService,
reloadAutomations: () => callService("automation", "reload")
} }
} }
+156 -77
View File
@@ -1,80 +1,155 @@
import React, { FC, useEffect, useState } from "react"; 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 { Page } from "components/Page";
import { useHAServices } from "haService"; import { useHA } from "haService";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/InputYaml";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button";
import { ServiceEditor } from "components/ServiceEditor";
const Test: FC = () => { const Test: FC = () => {
const services = useHAServices(); const { services, callService } = useHA();
const data = services.collection?.state ?? {}; const data = services.collection?.state ?? {};
const options = Object.keys(data).sort(); const options = Object.keys(data).sort();
const summary: Record<string, Record<string, { total: number, domains: string[], values: Set<string> }>> = {} // const flattened: any[] = [];
const fields: Record<string, Record<string, { total: number, values: Set<string> }>> = {} // Object.keys(data).forEach(domain => {
const target: Record<string, Record<string, { total: number, values: Set<string> }>> = {} // Object.keys(data[domain]).forEach(
// service_name => {
// const service = data[domain][service_name];
// const all: any = {
// domain, service_name,
// }
Object.keys(data).forEach(domain => // flattened.push({
Object.keys(data[domain]).forEach( // domain, service_name,
action => { // fields: Object.keys(service.fields).map(k => ({
const service = data[domain][action]; // name: k,
Object.keys(service.fields).forEach(field => { // data: service.fields[k]
const value = service.fields[field]; // })),
const valueType = `${typeof value}-${Array.isArray(value)}`; // target: Object.keys(service.target ?? {}).map(k => ({
fields[field] = fields[field] ?? {} // name: k,
fields[field][valueType] = fields[field][valueType] ?? { // data: (service.target as any)[k]
total: 0, // }))
domains: [], // })
values: new Set() // }
} // )
fields[field][valueType].total += 1 // })
fields[field][valueType].values.add(JSON.stringify(value))
}) // console.log(flattened)
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 summary: Record<string, Record<string, { total: number, domains: string[], values: Set<string> }>> = {}
Object.keys(service).forEach(field => { // const fields: Record<string, Record<string, { total: number, values: Set<string> }>> = {}
const value = (service as any)[field]; // const target: Record<string, Record<string, { total: number, values: Set<string> }>> = {}
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] ?? ""); // 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 suboptions = Object.keys(data[current] ?? "").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 [secCurrent, setSecCurrent] = useState(suboptions[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(() => { const [domain, setDomain] = useState(options[0] ?? "");
setSecCurrent(suboptions[0] ?? "")
}, [current, setSecCurrent])
const domains = Object.keys(data[domain] ?? "").sort();
return <div style={{ overflow: 'auto', maxHeight: '100vh' }}> const [service, setService] = useState(domains[0] ?? "");
<ul> const serviceDefn = (data[domain] ?? {})[service] ?? {};
useEffect(() => {
setService(domains[0] ?? "");
}, [domain, setService]);
let serviceEditElm = <>Failed to load</>;
try {
if (service) {
serviceEditElm = (
<div
style={{
border: "1px solid var(--primary-accent)",
maxWidth: "100vw",
padding: "2.5em",
margin: "2.5em",
}}
>
<ServiceEditor
service={serviceDefn}
serviceId={`${domain}.${service}`}
data={{ field: {}, target: {} }}
onUpdate={() => {}}
/>
</div>
);
}
} catch (err) {
serviceEditElm = <>{JSON.stringify(err)}</>;
}
return (
<div style={{ overflow: "auto", maxHeight: "100vh" }}>
<InputList
label="Domains"
current={domain}
onChange={setDomain}
options={options}
/>
<InputList
label="Services"
current={service}
onChange={setService}
options={domains}
/>
<Button onClick={() => callService(domain, service)}>Call</Button>
{serviceEditElm}
<InputYaml label="Service Data" value={serviceDefn} onChange={() => {}} />
<code>{JSON.stringify(serviceDefn, null, 4)}</code>
{/* <ul style={{
maxHeight: '20vh',
overflow: 'auto',
}}>
{Object.keys(summary).map(k => <li key={k}> {Object.keys(summary).map(k => <li key={k}>
<b>{k}</b> <ul> <b>{k}</b> <ul>
{Object.keys(summary[k]).map(t => <li key={k + t}> {Object.keys(summary[k]).map(t => <li key={k + t}>
@@ -89,7 +164,10 @@ const Test: FC = () => {
</li>)} </li>)}
</ul> </ul>
<h1>Fields</h1> <h1>Fields</h1>
<ul> <ul style={{
maxHeight: '20vh',
overflow: 'auto',
}}>
{Object.keys(fields).map(k => <li key={k}> {Object.keys(fields).map(k => <li key={k}>
<b>{k}</b> <ul> <b>{k}</b> <ul>
{Object.keys(fields[k]).map(t => <li key={k + t}> {Object.keys(fields[k]).map(t => <li key={k + t}>
@@ -104,7 +182,10 @@ const Test: FC = () => {
</li>)} </li>)}
</ul> </ul>
<h1>Targets</h1> <h1>Targets</h1>
<ul> <ul style={{
maxHeight: '20vh',
overflow: 'auto',
}}>
{Object.keys(target).map(k => <li key={k}> {Object.keys(target).map(k => <li key={k}>
<b>{k}</b> <ul> <b>{k}</b> <ul>
{Object.keys(target[k]).map(t => <li key={k + t}> {Object.keys(target[k]).map(t => <li key={k + t}>
@@ -117,24 +198,22 @@ const Test: FC = () => {
</li>)} </li>)}
</ul> </ul>
</li>)} </li>)}
</ul> </ul> */}
<InputList label="Services" current={current} onChange={setCurrent} options={options} />
<InputList label="Domain" current={secCurrent} onChange={setSecCurrent} options={suboptions} />
<InputYaml label="Service Data" value={(data[current] ?? {})[secCurrent] ?? {}} onChange={() => { }} />
</div> </div>
} );
};
export default { export default {
title: 'Services/HA Service', title: "Services/HA Service",
component: Test, component: Test,
parameters: { actions: { argTypesRegex: '^on.*' } }, parameters: { actions: { argTypesRegex: "^on.*" } },
args: { args: {},
} } as ComponentMeta<typeof Test>;
} as ComponentMeta<typeof Test>
export const Base: ComponentStory<typeof Test> = props => { export const Base: ComponentStory<typeof Test> = (props) => {
return (
return <Page> <Page>
<Test {...props} /> <Test {...props} />
</Page> </Page>
);
}; };