latest work

This commit is contained in:
ari committed 2022-06-12 16:42:44 -04:00
1 parent 651ba865b1
commit 240f8faef7
13 files changed
+323 -57

No files matched your search

@@ -0,0 +1,148 @@
import "./InputTime.css";
import { useState, useEffect, FC } from "react";
import TextField from '@mui/material/TextField';
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 { 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> = [
'hours',
'minutes',
'seconds',
'milliseconds'
]
export interface Props {
label: string;
value?: AutomationTime;
onChange: (v?: AutomationTimeObject) => void;
}
export const InputTime: FC<Props> = (props) => {
// state
const [disabled, setDisabled] = useState(!props.value)
const [displayValue, setDisplayValue] = useState(convertAutomationTimeToTimeObject(props.value))
// process display input
const updateOne = (k: keyof AutomationTimeObject) => (v: string) => {
if (Number(v) < 0) {
setDisplayValue({
...displayValue,
[k]: 0
})
} else if (k === "hours") {
setDisplayValue({
...displayValue,
[k]: Number(v)
})
} else if (k === "minutes") {
let minutes = Number(v);
let { hours = 0 } = displayValue
if (minutes > 59) {
const additonalHours = Math.floor(minutes / 60)
hours += additonalHours
minutes = minutes - additonalHours * 60
}
setDisplayValue({
...displayValue,
minutes,
hours,
})
} else if (k === "seconds") {
let seconds = Number(v);
let { hours = 0, minutes = 0 } = displayValue
if (seconds > 59) {
const additonalHours = Math.floor(seconds / (60 * 60))
hours += additonalHours
seconds = seconds - additonalHours * 60
}
if (seconds > 59) {
const additionalMinutes = Math.floor(seconds / 60)
minutes += additionalMinutes
seconds = seconds - additionalMinutes * 60
}
setDisplayValue({
...displayValue,
minutes,
hours,
seconds,
})
} else if (k === "milliseconds") {
let milliseconds = Number(v);
let { hours = 0, minutes = 0, seconds = 0 } = displayValue
if (milliseconds > 1000) {
const additonalHours = Math.floor(milliseconds / (60 * 60 * 1000))
hours += additonalHours
milliseconds = milliseconds - additonalHours * 60 * 60 * 1000
}
if (milliseconds > 1000) {
const additionalMinutes = Math.floor(milliseconds / (60 * 1000))
minutes += additionalMinutes
milliseconds = milliseconds - additionalMinutes * 60 * 1000
}
if (milliseconds > 1000) {
const additionalSeconds = Math.floor(milliseconds / 1000)
seconds += additionalSeconds
milliseconds = milliseconds - additionalSeconds * 1000
}
setDisplayValue({
...displayValue,
minutes,
hours,
seconds,
milliseconds,
})
}
}
// effect
useEffect(() => {
if (disabled && !props.value) {
return
}
if (disabled) {
props.onChange(undefined)
} else {
const pVal = convertAutomationTimeToTimeString(props.value);
const cVal = convertObjectToAutomationTimeString(displayValue);
if (pVal !== cVal) {
props.onChange(displayValue)
}
}
}, [disabled, displayValue])
return <div className="input-time">
<InputLabel >{props.label}</InputLabel>
<div className="input-time--inner">
{fields.map(name =>
<TextField
key={name}
variant="filled"
label={prettyName(name)}
defaultValue="00"
InputProps={{
disabled,
type: "number",
title: prettyName(name),
}}
value={displayValue[name] ?? 0}
onChange={e => updateOne(name)(e.target.value)}
/>
)}
<IconButton onClick={() => setDisabled(!disabled)}>
{disabled ? <EditIcon /> : <CloseIcon />}
</IconButton>
</div>
</div>
}
+9 -7
View File
@@ -4,6 +4,7 @@ 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";
export interface Props<T extends string> { export interface Props<T extends string> {
current: T; current: T;
@@ -12,25 +13,26 @@ export interface Props<T extends string> {
label: string; label: string;
id?: string; id?: string;
className?: string; className?: string;
prettyOptionLabels?: boolean;
} }
export const InputList: FC<Props<any>> = ({ export function InputList<T extends string>({
current, current,
options, options,
onChange, onChange,
label, label,
id, id,
className, className,
}) => { prettyOptionLabels,
}: Props<T>) {
const invalidCurrent = current && !options.includes(current); const invalidCurrent = current && !options.includes(current);
return <FormControl variant="filled" sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}> return <FormControl className={className} variant="filled" sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}>
<InputLabel id="demo-simple-select-filled-label">{label}</InputLabel> <InputLabel>{label}</InputLabel>
<Select <Select
className={className}
autoWidth autoWidth
id={id} id={id}
value={current} value={current}
onChange={(e) => { onChange={(e) => {
onChange(e.target.value) onChange(e.target.value as T)
}} }}
label={label} label={label}
variant="filled" variant="filled"
@@ -43,7 +45,7 @@ export const InputList: FC<Props<any>> = ({
key={i} key={i}
value={t} value={t}
> >
{t} {prettyOptionLabels ? prettyName(t) : t}
</MenuItem> </MenuItem>
))} ))}
</Select> </Select>
+3 -1
View File
@@ -12,6 +12,7 @@ export interface Props {
additionalTooltipFilters?: Record<string, string>; additionalTooltipFilters?: Record<string, string>;
multiline?: boolean; multiline?: boolean;
maxRows?: number; maxRows?: number;
className?: string;
} }
export default function InputText({ export default function InputText({
label, label,
@@ -23,10 +24,11 @@ export default function InputText({
multiline = false, multiline = false,
maxRows = 4, maxRows = 4,
children, children,
className,
}: PropsWithChildren<Props>) { }: PropsWithChildren<Props>) {
const tooltip = useToolTip(); const tooltip = useToolTip();
const [isFocused, setIsFocused] = useState(false) const [isFocused, setIsFocused] = useState(false)
return <InputWrapper label=""> return <InputWrapper className={className} label="">
<TextField multiline={multiline} maxRows={maxRows} fullWidth inputMode="text" variant="filled" focused={isFocused} label={label} value={value} <TextField multiline={multiline} maxRows={maxRows} fullWidth inputMode="text" variant="filled" focused={isFocused} label={label} value={value}
onKeyDown={e => { onKeyDown={e => {
if (e.key === 'Enter') { if (e.key === 'Enter') {
+3 -2
View File
@@ -24,6 +24,7 @@ export interface Props {
label: string; label: string;
value?: AutomationTime; value?: AutomationTime;
onChange: (v?: AutomationTimeObject) => void; onChange: (v?: AutomationTimeObject) => void;
className?: string;
} }
export const InputTime: FC<Props> = (props) => { export const InputTime: FC<Props> = (props) => {
@@ -122,8 +123,8 @@ export const InputTime: FC<Props> = (props) => {
}, [disabled, displayValue]) }, [disabled, displayValue])
return <div className="input-time"> return <div className={["input-time", props.className ?? ""].join(" ")}>
<InputLabel >{props.label}</InputLabel> {/* <InputLabel >{props.label}</InputLabel> */}
<div className="input-time--inner"> <div className="input-time--inner">
{fields.map(name => {fields.map(name =>
<TextField <TextField
+4 -2
View File
@@ -11,12 +11,14 @@ export interface Props<T extends {}> {
value: T; value: T;
onChange: (v: T) => void; onChange: (v: T) => void;
error?: JSX.Element | string, error?: JSX.Element | string,
className?: string;
} }
export default function InputYaml<T>({ export default function InputYaml<T extends {}>({
label, label,
error: incmError, error: incmError,
value = {} as any, value = {} as any,
onChange, onChange,
className,
}: Props<T>) { }: Props<T>) {
const [{ text, error }, setState] = useState<{ const [{ text, error }, setState] = useState<{
text: string, text: string,
@@ -50,7 +52,7 @@ export default function InputYaml<T>({
} }
} }
}, [text], 1000) }, [text], 1000)
return <InputWrapper label={label} error={error}> return <InputWrapper className={className} label={label} error={error}>
<CodeMirror <CodeMirror
theme={"dark"} theme={"dark"}
value={text} value={text}
@@ -0,0 +1,33 @@
.node-editor--action-wait {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.node-editor--action-wait .for {
flex: 2;
}
.node-editor--action-wait .for .input-time--inner {
justify-content: center;
}
.node-editor--action-wait .template {
margin: 0;
flex: 2;
}
.node-editor--action-wait .triggers {
width: 100%;
}
.node-editor--action-wait .wait-type {
flex: 1;
}
.node-editor--action-wait .wait-options {
width: 100%;
display: flex;
justify-content: space-evenly;
align-items: center;
}
@@ -1,41 +1,86 @@
import "./ActionWait.css";
import InputBoolean from "components/Inputs/InputBoolean"; import InputBoolean from "components/Inputs/InputBoolean";
import { InputList } from "components/Inputs/InputList";
import InputNumber from "components/Inputs/InputNumber";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/InputText";
import { WaitAction } from "types/automations/actions"; import { InputTime } from "components/Inputs/InputTime";
import { useState } from "react";
import { DelayAction, WaitAction } from "types/automations/actions";
import { OptionManager, updateActionData } from './OptionManager'; import { OptionManager, updateActionData } from './OptionManager';
import { getNodeSubType } from 'utils/automations';
import InputYaml from "components/Inputs/InputYaml";
type ThisAction = WaitAction | DelayAction;
type Option = 'delay' | 'template' | 'trigger'
const getCurrentOption = (node: ThisAction): Option => {
if (getNodeSubType(node) === 'delay') {
return 'delay'
} else {
return 'template'
}
}
export const ActionWaitState: OptionManager<WaitAction> = { export const ActionWaitState: OptionManager<ThisAction> = {
defaultState: () => ({ defaultState: () => ({
alias: "Wait", delay: "",
wait_template: "",
// timeout: 0,
continue_on_timeout: false,
}), }),
isReady: ({ isReady: () => true,
alias, wait_template Component: ({ state, setState }) => {
}) => ( // state
alias !== '' &&
wait_template !== ""
),
renderOptionList: (state, setState) => {
const update = updateActionData(state, setState); const update = updateActionData(state, setState);
return <> const [current, _setCurrent] = useState(getCurrentOption(state));
<InputText const setCurrent = (opt: Option) => {
textBoxFor="template" _setCurrent(opt)
label="Template" }
value={state.wait_template}
onChange={wait_template => update({ wait_template })} // determine options
/> let option: JSX.Element = <></>;
{/* <InputNumber if (current === "delay") {
label="Timeout" option = <>
value={state.timeout ?? 0} <InputTime className="for" label="for" value={(state as any).delay} onChange={delay => update({ delay })} />
onChange={(timeout = 0) => update({ timeout })} </>
/> */} } else if (current === 'template') {
<InputBoolean state = state as WaitAction;
label="Continue on Timeout" option = <>
value={state.continue_on_timeout ?? false} <InputText
onChange={continue_on_timeout => update({ continue_on_timeout })} label="Template"
/> className="template"
</> value={state.wait_template ?? ""}
onChange={wait_template => update({ wait_template })}
/>
</>
} else if (current === 'trigger') {
state = state as WaitAction;
option = <>
<InputYaml
className="triggers"
label="Triggers"
value={state.wait_for_trigger ?? []}
onChange={wait_for_trigger => update({ wait_for_trigger })}
/>
</>
}
// render
return <div className="node-editor--action-wait">
<InputList
className="wait-type"
label="Wait Type" prettyOptionLabels
options={["template", 'trigger', "delay"]}
current={current} onChange={setCurrent} />
{option}
{current !== 'delay' ? <div className="wait-options">
<InputNumber
label="Timeout"
value={(state as any).timeout ? Number((state as any).timeout) : 0}
onChange={(timeout = 0) => update({ timeout: String(timeout) })}
/>
<InputBoolean
label="Continue on Timeout"
value={(state as any).continue_on_timeout ?? false}
onChange={continue_on_timeout => update({ continue_on_timeout })}
/>
</div> : <></>}
</div>
} }
} }
@@ -1,11 +1,19 @@
import { HAEntitiesState } from 'haService'; import { HAEntitiesState } from 'haService';
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';
export interface OptionManager<T> { export type OptionManager<T> = {
defaultState(): T; defaultState(): T;
isReady(s: T): boolean; isReady(s: T): boolean;
} & ({
renderOptionList(s: T, set: (s: T) => void, entities: HAEntitiesState): JSX.Element; renderOptionList(s: T, set: (s: T) => void, entities: HAEntitiesState): JSX.Element;
} } | {
Component: FC<{
state: T,
setState: (s: T) => void,
entities: HAEntitiesState,
}>
})
export const updateConditionData = <T extends AutomationCondition>( export const updateConditionData = <T extends AutomationCondition>(
@@ -13,17 +21,17 @@ export const updateConditionData = <T extends AutomationCondition>(
) => ( ) => (
state: T, state: T,
data: Partial<T>, data: Partial<T>,
) => setState({ ) => setState({
...state, ...state,
...data, ...data,
}) })
export const updateActionData = <T extends AutomationAction>( export const updateActionData = <T extends AutomationAction>(
state: T, state: T,
setState: (s: T) => void setState: (s: T) => void
) => ( ) => (
data: Partial<T>, data: Partial<T>,
) => setState({ ) => setState({
...state, ...state,
...data, ...data,
}) })
@@ -1,4 +1,4 @@
import { Dispatch, SetStateAction, useEffect, useState } from 'react'; import { Dispatch, SetStateAction, useEffect, useState, Component } 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';
@@ -108,7 +108,9 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
} }
return <> return <>
{aliasEditor} {aliasEditor}
{optionManager.renderOptionList(currentNode, setState, entities)} {('renderOptionList' in optionManager) ?
optionManager.renderOptionList(currentNode, setState, entities) :
<optionManager.Component state={currentNode} setState={setState} entities={entities} />}
</>; </>;
}, },
isReady() { isReady() {
@@ -95,3 +95,12 @@ ServiceExample.args = {
"service": "", "service": "",
}, },
} }
export const DelayExample = Action.bind({})
DelayExample.args = {
...DelayExample.args,
node: {
"wait_template": "",
},
}
+2 -1
View File
@@ -1,5 +1,4 @@
import { AutomationSequenceNode } from "."; import { AutomationSequenceNode } from ".";
import { AutomationTime } from "./common";
import { AutomationCondition } from "./conditions"; import { AutomationCondition } from "./conditions";
import * as v from "types/validators/actions"; import * as v from "types/validators/actions";
import * as st from 'superstruct'; import * as st from 'superstruct';
@@ -15,6 +14,7 @@ export type RepeatAction = AutomationActionNodeBase<{
} }
}> }>
export type WaitAction = st.Infer<typeof v.WaitAction>; export type WaitAction = st.Infer<typeof v.WaitAction>;
export type DelayAction = st.Infer<typeof v.DelayAction>;
export type FireEventAction = st.Infer<typeof v.FireEventAction>; export type FireEventAction = st.Infer<typeof v.FireEventAction>;
export type DeviceAction = st.Infer<typeof v.DeviceAction>; export type DeviceAction = st.Infer<typeof v.DeviceAction>;
export type ChooseAction = AutomationActionNodeBase<{ export type ChooseAction = AutomationActionNodeBase<{
@@ -36,6 +36,7 @@ export type ActionType =
| 'service' | 'service'
| 'repeat' | 'repeat'
| 'wait' | 'wait'
| 'delay'
| 'event' | 'event'
| 'device' | 'device'
| 'choose' | 'choose'
+10 -1
View File
@@ -1,5 +1,6 @@
import * as st from 'superstruct' import * as st from 'superstruct'
import { AutomationTime } from './common'; import { AutomationTime } from './common';
import { AutomationTrigger } from './triggers';
export const AutomationActionNodeBase = st.type({ export const AutomationActionNodeBase = st.type({
@@ -29,9 +30,17 @@ export const RepeatAction = st.intersection([
export const WaitAction = st.intersection([ export const WaitAction = st.intersection([
AutomationActionNodeBase, AutomationActionNodeBase,
st.type({ st.type({
wait_template: st.string(),
timeout: st.optional(AutomationTime), timeout: st.optional(AutomationTime),
continue_on_timeout: st.optional(st.boolean()), continue_on_timeout: st.optional(st.boolean()),
wait_template: st.optional(st.string()),
wait_for_trigger: st.optional(st.array(AutomationTrigger)),
}),
]);
export const DelayAction = st.intersection([
AutomationActionNodeBase,
st.type({
delay: AutomationTime
}) })
]); ]);
+4
View File
@@ -31,6 +31,7 @@ export const getSubTypeList = <T extends AutomationNodeTypes>(nodeType: T): Auto
"service", "service",
"repeat", "repeat",
"wait", "wait",
"delay",
"device", "device",
"choose", "choose",
] as any ] as any
@@ -111,6 +112,8 @@ export const getNodeSubType = <T extends AutomationNodeTypes>(
return 'device' as any return 'device' as any
} else if ('choose' in node) { } else if ('choose' in node) {
return 'choose' as any return 'choose' as any
} else if ('delay' in node) {
return 'delay' as any
} else { } else {
throw new Error("Invalid node type!") throw new Error("Invalid node type!")
} }
@@ -138,6 +141,7 @@ const ActionValidators: Record<ActionType, any> = {
"repeat": v.actions.RepeatAction, "repeat": v.actions.RepeatAction,
"service": v.actions.ServiceAction, "service": v.actions.ServiceAction,
"wait": v.actions.WaitAction, "wait": v.actions.WaitAction,
"delay": v.actions.DelayAction,
} }
const ConditionValidators: Record<ConditionType, any> = { const ConditionValidators: Record<ConditionType, any> = {