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 1281 additions and 454 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)
## [0.1.21] - Service Editor
- first version of service editor
- reloading automations on save
## [0.1.20] - UI Bugfixes
- Using MUI elements for input time
+1 -1
View File
@@ -1,5 +1,5 @@
name: Shortumation
version: v0.1.20
version: v0.1.21
slug: shortumation
image: asosnovsky/shortumation-{arch}
url: "https://github.com/asosnovsky/Shortumation"
+3 -3
View File
@@ -5,7 +5,7 @@ import { AutomationAPI } from './automations';
export const useDefaultApiState = () => useState<ApiState>({
automations: {ready: false},
automations: { ready: false },
});
export const makeReloadAutomations = (
@@ -21,8 +21,8 @@ export const makeReloadAutomations = (
const resp = await automationAPI.list(params);
setState({
...state, automations: {
ready: true,
...resp,
ready: true,
...resp,
}
});
}
@@ -46,6 +46,7 @@ export const AutomationEditor: FC<Props> = ({
if (dims.flipped !== flipped) {
setFlipped(dims.flipped)
}
// eslint-disable-next-line
}, [dims.flipped])
// render
@@ -18,7 +18,12 @@ export type Props = {
}
const useAutomationListBoxState = () => {
const [cookies, setCookies, _] = useCookies(['albSearchText', 'albSelected']);
const [
cookies,
setCookies,
// eslint-disable-next-line
_
] = useCookies(['albSearchText', 'albSelected']);
let initialSelected = [];
try {
initialSelected = JSON.parse(cookies.albSelected)
+19 -4
View File
@@ -14,6 +14,7 @@ import { makeTagDB } from "./TagDB";
import LinearProgress from "@mui/material/LinearProgress";
import CircularProgress from "@mui/material/CircularProgress";
import { useCookies } from 'react-cookie';
import { useHA } from "haService";
interface AutomationListParams {
@@ -26,11 +27,15 @@ interface AutomationListParams {
}
export const useAutomationListState = () => {
const [cookies, setCookies, _] = useCookies(['alCurrent']);
const [
cookies,
setCookies,
// eslint-disable-next-line
_
] = useCookies(['alCurrent']);
let initialCurrent = 0;
try {
initialCurrent = Number(cookies.alCurrent ?? '0');
// eslint-disable-next-line
} catch (_) { }
const [hideList, setHideList] = useState(false);
@@ -109,11 +114,21 @@ export const ConnectedAutomationList: FC<ConnectedAutomationListParams> = ({
state: {
automations,
},
removeAutomation,
updateAutomation,
...methods
},
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) {
return <div className="automation-list--root loading">
<LinearProgress />
+190 -138
View File
@@ -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<T extends Option<any>> = {
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<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>
}
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<T extends Option>(
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) {
props.onChange(cleanValue);
return (
<Badge badgeContent={tagValue.length} color="info">
{inner}
</Badge>
);
} else {
props.onChange(cleanValue[cleanValue.length - 1])
}
}
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
}
}
return inner;
}
}}
/>
);
}
+55 -35
View File
@@ -1,21 +1,26 @@
import { FC } from "react";
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<T extends string> {
current: T;
export type Props<T extends string | Object> = {
current?: T;
options: readonly T[];
onChange: (n: T) => void;
label: string;
id?: string;
className?: string;
prettyOptionLabels?: boolean;
}
export function InputList<T extends string>({
getKey?: (n: T) => string;
placeholder?: any;
title?: string;
helperText?: string;
endAdornment?: ReactNode;
};
export function InputList<T extends string | Object>({
current,
options,
onChange,
@@ -23,32 +28,47 @@ export function InputList<T extends string>({
id,
className,
prettyOptionLabels,
getKey = String,
placeholder,
title,
helperText,
endAdornment,
}: Props<T>) {
const invalidCurrent = current && !options.includes(current);
return <FormControl className={className} variant="filled" sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}>
<InputLabel>{label}</InputLabel>
<Select
autoWidth
id={id}
value={current}
onChange={(e) => {
onChange(e.target.value as T)
}}
label={label}
const invalidCurrent =
current && !options.map(getKey).includes(getKey(current));
return (
<FormControl
className={className}
variant="filled"
placeholder={label}
error={invalidCurrent}
sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}
>
{options.map((t, i) => (
<MenuItem
key={i}
value={t}
>
{prettyOptionLabels ? prettyName(t) : t}
</MenuItem>
))}
</Select>
<FormHelperText>{invalidCurrent ? `'${current}' is not a valid selection` : ''}</FormHelperText>
</FormControl>
<InputLabel>{label}</InputLabel>
<Select
title={title}
placeholder={placeholder ?? label}
endAdornment={endAdornment}
autoWidth
id={id}
value={current ? getKey(current) : ""}
onChange={(e) => {
const key = e.target.value;
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";
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 <TextField
variant="filled"
label={label}
value={value}
defaultValue={value}
onChange={e => onChange(Number(e.target.value ?? 0))}
disabled={disabled}
className={className}
InputProps={{
endAdornment: <InputAdornment position="end">
<IconButton onClick={() => onChange(disabled ? 0 : undefined)}>
{disabled ? <Edit /> : <Close />}
</IconButton>
</InputAdornment>,
inputProps: {
min, max, type: 'number'
}
}}
/>
const disabled = value === undefined || value === null;
return (
<TextField
variant="filled"
label={label}
value={value}
defaultValue={value}
onChange={(e) => onChange(Number(e.target.value ?? 0))}
disabled={disabled}
className={className}
placeholder={placeholder}
required={required}
InputProps={{
endAdornment: (
<InputAdornment position="end">
{unit}
<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 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<Props>) {
const tooltip = useToolTip();
const [isFocused, setIsFocused] = useState(false)
return <InputWrapper className={className} label="">
<TextField multiline={multiline} maxRows={maxRows} fullWidth inputMode="text" variant="filled" focused={isFocused} label={label} value={value}
onKeyDown={e => {
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}
</InputWrapper>
const [isFocused, setIsFocused] = useState(false);
return (
<InputWrapper className={className} label="">
<TextField
multiline={multiline}
maxRows={maxRows}
fullWidth
inputMode="text"
variant="filled"
focused={isFocused}
label={label}
value={value}
title={title}
helperText={helperText}
placeholder={placeholder}
InputProps={{
endAdornment,
}}
required={required}
onKeyDown={(e) => {
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}
</InputWrapper>
);
}
+2 -6
View File
@@ -5,13 +5,8 @@ import EditIcon from '@mui/icons-material/Edit';
import CloseIcon from "@mui/icons-material/Close";
import IconButton from "@mui/material/IconButton"
import { AutomationTime, AutomationTimeObject } from "types/automations/common";
import { convertAutomationTimeToTimeObject, convertObjectToAutomationTimeString, milisecondsToObject } from "utils/time";
import { convertStringToAutomationTimeObject, convertAutomationTimeToTimeString } from 'utils/time';
import { convertAutomationTimeToTimeObject, convertObjectToAutomationTimeString, convertAutomationTimeToTimeString } from 'utils/time';
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
const fields: Array<keyof AutomationTimeObject> = [
@@ -120,6 +115,7 @@ export const InputTime: FC<Props> = (props) => {
props.onChange(displayValue)
}
}
// eslint-disable-next-line
}, [disabled, displayValue])
@@ -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<ServiceAction> = {
defaultState: () => ({
@@ -10,29 +9,34 @@ export const ActionCallServiceState: OptionManager<ServiceAction> = {
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 <>
<InputService
value={service}
onChange={(service: string | null) => update({ service: service ?? "" })}
/>
<InputYaml
label="Target"
value={target}
onChange={target => update({ target })}
/>
<InputYaml
label="Data"
value={data}
onChange={data => update({ data })}
/>
</>
}
}
const serviceOption = services.getOption(service);
return (
<>
<InputService
value={service}
onChange={(service: string | null) =>
update({ service: service ?? "" })
}
/>
{serviceOption && (
<ServiceEditor
key={service}
serviceId={service}
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 { AutomationAction } from 'types/automations/actions';
import { AutomationCondition } from 'types/automations/conditions';
@@ -12,6 +12,7 @@ export type OptionManager<T> = {
state: T,
setState: (s: T) => void,
entities: HAEntitiesState,
services: HAServicesState,
}>
})
@@ -1,45 +1,61 @@
import { Dispatch, SetStateAction, useEffect, useState, Component } 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 InputBoolean from 'components/Inputs/InputBoolean';
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) => [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
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,
@@ -48,7 +64,7 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
subType,
subTypes,
optionManager,
} = createData(originalNode, currentNode, allowedTypes)
} = createData(originalNode, currentNode, allowedTypes);
// publuc
return {
nodeType,
@@ -60,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 = <InputText
key="alias"
label="Trigger ID"
value={(allState.node as any).id}
onChange={id => setState({
...allState.node,
id
} as any)}
/>
let aliasEditor = <></>;
if (nodeType === "trigger") {
aliasEditor = (
<InputText
key="alias"
label="Trigger ID"
value={(allState.node as any).id}
onChange={(id) =>
setState({
...allState.node,
id,
} as any)
}
/>
);
}
if (nodeType === 'action') {
aliasEditor = <InputText
key="alias"
label="Alias"
value={getDescriptionFromAutomationNode(allState.node, namer)}
onChange={alias => setState({
...allState.node,
alias
} as any)}
/>
if (nodeType === "action") {
aliasEditor = (
<InputText
key="alias"
label="Alias"
value={getDescriptionFromAutomationNode(allState.node, namer)}
onChange={(alias) =>
setState({
...allState.node,
alias,
} as any)
}
/>
);
}
if (yamlMode || allState.isErrored) {
return <>
{aliasEditor}
<InputYaml
label=''
value={currentNode}
onChange={setStateForManualYaml}
error={invalidManualYaml}
/>
</>
return (
<>
{aliasEditor}
<InputYaml
label=""
value={currentNode}
onChange={setStateForManualYaml}
error={invalidManualYaml}
/>
</>
);
}
return <>
{aliasEditor}
{('renderOptionList' in optionManager) ?
optionManager.renderOptionList(currentNode, setState, entities) :
<optionManager.Component state={currentNode} setState={setState} entities={entities} />}
</>;
return (
<>
{aliasEditor}
{"renderOptionList" in optionManager ? (
optionManager.renderOptionList(currentNode, setState, entities)
) : (
<optionManager.Component
state={currentNode}
setState={setState}
entities={entities}
services={services}
/>
)}
</>
);
},
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;
@@ -156,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,
@@ -173,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: <ul key={'error'} className="node-editor--error">
{errors.map(({ message, path }, i) => <li key={i}>
<b>{path}</b>: {message}
</li>)}
</ul>
}
invalidManualYaml: (
<ul key={"error"} className="node-editor--error">
{errors.map(({ message, path }, i) => (
<li key={i}>
<b>{path}</b>: {message}
</li>
))}
</ul>
),
};
} else {
return {
node,
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 { DeviceRegistryItem } from "./types";
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,
label: string,
} & T)
} & T
export type Option<T = {}> = string | BaseOption<T>;
export type EntityOption = Option<{ domain: string; }>
export type HAEntitiesState = ReturnType<typeof 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 = () => {
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 []
@@ -90,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);
@@ -107,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
}
@@ -165,6 +198,48 @@ export const useHA = () => {
const entities = useHAEntities();
const devices = useHADeviceRegistry();
const services = useHAServices();
const conn = useHAConnection();
const { enqueueSnackbar } = useSnackbar();
const callService = async (
domain: string,
service: string,
data: any = {},
target: any = {},
) => {
if (conn.status === 'loaded') {
try {
const result = await conn.connection.sendMessagePromise({
"type": "call_service",
domain,
service,
target,
service_data: data
})
enqueueSnackbar(`Successfully called ${domain}.${service}`, {
"variant": "success",
})
return result
} catch (err: any) {
let msg = JSON.stringify(err)
if ('message' in err) {
msg = err.message
}
enqueueSnackbar(`Failed to call ${domain}.${service} because '${msg}'`, {
"variant": "error",
})
return
}
} if (conn.status === 'error') {
enqueueSnackbar(`Failed to call service because connection is '${conn.status}' -- ${conn.error}`, {
"variant": "error"
})
} else {
enqueueSnackbar(`Failed to call service because connection is '${conn.status}'`, {
"variant": "error"
})
}
}
const namer: Namer = {
getDeviceName(device_id) {
@@ -186,5 +261,7 @@ export const useHA = () => {
devices,
services,
namer,
callService,
reloadAutomations: () => callService("automation", "reload")
}
}
+157 -78
View File
@@ -1,80 +1,155 @@
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 { useHAServices } from "haService";
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 = useHAServices();
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<string, Record<string, { total: number, domains: string[], values: Set<string> }>> = {}
const fields: Record<string, Record<string, { total: number, values: Set<string> }>> = {}
const target: Record<string, Record<string, { total: number, values: Set<string> }>> = {}
// 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<string, Record<string, { total: number, domains: string[], values: Set<string> }>> = {}
// const fields: Record<string, Record<string, { total: number, values: Set<string> }>> = {}
// const target: Record<string, Record<string, { total: number, values: Set<string> }>> = {}
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(() => {
setSecCurrent(suboptions[0] ?? "")
}, [current, setSecCurrent])
const [domain, setDomain] = useState(options[0] ?? "");
const domains = Object.keys(data[domain] ?? "").sort();
return <div style={{ overflow: 'auto', maxHeight: '100vh' }}>
<ul>
const [service, setService] = useState(domains[0] ?? "");
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}>
<b>{k}</b> <ul>
{Object.keys(summary[k]).map(t => <li key={k + t}>
@@ -89,7 +164,10 @@ const Test: FC = () => {
</li>)}
</ul>
<h1>Fields</h1>
<ul>
<ul style={{
maxHeight: '20vh',
overflow: 'auto',
}}>
{Object.keys(fields).map(k => <li key={k}>
<b>{k}</b> <ul>
{Object.keys(fields[k]).map(t => <li key={k + t}>
@@ -104,7 +182,10 @@ const Test: FC = () => {
</li>)}
</ul>
<h1>Targets</h1>
<ul>
<ul style={{
maxHeight: '20vh',
overflow: 'auto',
}}>
{Object.keys(target).map(k => <li key={k}>
<b>{k}</b> <ul>
{Object.keys(target[k]).map(t => <li key={k + t}>
@@ -117,24 +198,22 @@ const Test: FC = () => {
</li>)}
</ul>
</li>)}
</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={() => { }} />
</ul> */}
</div>
}
);
};
export default {
title: 'Services/HA Service',
component: Test,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
}
} as ComponentMeta<typeof Test>
title: "Services/HA Service",
component: Test,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof Test>;
export const Base: ComponentStory<typeof Test> = props => {
return <Page>
<Test {...props} />
export const Base: ComponentStory<typeof Test> = (props) => {
return (
<Page>
<Test {...props} />
</Page>
};
);
};