Compare commits

..
44 Commits
Author SHA1 Message Date
ari 13ea3632e3 0.1.22 2022-06-19 14:20:16 -04:00
ari 465e5a4268 clean up 2022-06-19 14:02:16 -04:00
ari eeaa64a8e7 flipped cookies 2022-06-19 14:01:53 -04:00
ari 3a1cee61b8 fixed up unittest 2022-06-19 13:56:21 -04:00
ari 21dd880e37 updated choose name 2022-06-19 13:55:51 -04:00
ari 218972ed5d fixxed typo 2022-06-19 13:39:03 -04:00
ari 451b3638bf cleaned up styles a bit 2022-06-19 13:38:43 -04:00
ari 3acbaf576d fixerd up event 2022-06-19 03:14:06 -04:00
ari eaec599109 auto jump into new automation in mobile mode 2022-06-19 02:59:56 -04:00
ari c6c1efddae removing input area for now 2022-06-19 02:55:19 -04:00
ari ae352ff244 entity dispay 2022-06-19 02:11:25 -04:00
ari dde8d76772 entity filter by integration 2022-06-19 02:06:51 -04:00
ari 34a4bd93bd better saving for yaml editor 2022-06-19 01:04:02 -04:00
ari 7154f206b4 updated inputyaml 2022-06-19 00:53:01 -04:00
ari 19a2d10a2f fixed typing error 2022-06-19 00:31:54 -04:00
ari da699403df added boolean to serviceeditor
helpertext
2022-06-19 00:29:39 -04:00
ari 1496bc66ad device editor working with special caps 2022-06-18 23:23:08 -04:00
ari debe48f2b4 renamed unit test 2022-06-17 22:22:49 -04:00
ari 4bada614b9 better name for device trigger 2022-06-17 22:22:37 -04:00
ari 537bfe824b clean up unused 2022-06-17 17:47:03 -04:00
ari a25ec99cb1 fixed unittests 2022-06-17 17:46:31 -04:00
ari 8ac5bfdfed typing errror 2022-06-17 17:45:41 -04:00
ari 618a62affe added condition editor for device 2022-06-17 17:45:14 -04:00
ari 1ce934fd54 generic device editor 2022-06-17 16:56:51 -04:00
ari ab8ecfeefb updated zone condition 2022-06-17 16:26:54 -04:00
ari a32e365d86 target device & action device v2 2022-06-17 16:06:51 -04:00
ari 04f3e6194f generic ha extras 2022-06-17 14:57:14 -04:00
ari 0b183353d3 prettier names 2022-06-17 14:34:37 -04:00
ari 0c9b0ec6e6 clean up 2022-06-17 14:25:48 -04:00
ari 5bef962977 fixed up service editor 2022-06-17 14:23:15 -04:00
ari 029df7932e device action builder 2022-06-17 13:37:25 -04:00
ari 6be6005531 reordered what shows up 2022-06-16 21:25:21 -04:00
ari 326775848b trigger state autofill 2022-06-16 21:23:28 -04:00
ari 736a6053ef always pretty list 2022-06-16 20:39:11 -04:00
ari f4a41331b1 clean up 2022-06-16 17:25:34 -04:00
ari 15c97b81b4 input area 2022-06-16 17:24:31 -04:00
ari 0fc3ea6146 selector.select 2022-06-15 10:43:14 -04:00
ari 596c3363e7 fixed up unit of measure 2022-06-14 22:01:21 -04:00
ari 529b5599e4 input number unit 2022-06-14 21:57:39 -04:00
ari 184d8a8584 added entity input for service target 2022-06-14 21:57:39 -04:00
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
89 changed files with 7155 additions and 3671 deletions

No files matched your search

+16 -6
View File
@@ -1,5 +1,17 @@
# Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge)
## [0.1.22] - Many Visual improvements
- Deprecated several custom components in favor of mui.com
- Device Editor now has support for 99% of diplay types
- Condition Device is implemented
- Improved naming autogen for trigger & choose
## [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
@@ -15,9 +27,9 @@
## [0.1.17] - Websockets
- Connected to HA main websocket -- now we retrieve real-time information about
* Device names
* Entity names/ids
- Device names
- Entity names/ids
- Autocomplete for devices and entities
@@ -41,7 +53,6 @@
- Made the validators less strict in order to capture more edge cases that HA supports
- Nicer auto-generated descriptions for some trigger nodes
## [0.1.10] - More Bug Fixes
- Allowing null or undefined values for metadata fields
@@ -95,8 +106,7 @@
## [0.0.9] - First Working Version
- Instalable verion via github
- Initial POC done
- Initial POC done
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+1 -1
View File
@@ -1,5 +1,5 @@
name: Shortumation
version: v0.1.20
version: v0.1.22
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,
}
});
}
@@ -2,11 +2,11 @@ import "./AutoInfoBox.css";
import { AutomationMetadata } from "types/automations";
import { InputList } from "components/Inputs/InputList";
import InputText from "components/Inputs/InputText";
import { FC, ReactNode, useRef, useState } from 'react';
import { FC, ReactNode, useRef, useState } from "react";
import { AddIcon, TrashIcon } from "components/Icons";
import { Button } from "components/Inputs/Button";
import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "components/AutomationList/TagDB";
import { ButtonIcon } from "components/Icons/ButtonIcons";
interface Props {
className: string;
@@ -25,122 +25,154 @@ export const AutoInfoBox: FC<Props> = ({
tagDB,
}) => {
// state
const [newTag, setNewTag] = useState<[string, string]>(["", ""])
const [[errorIndex, error], _setError] = useState<[number | 'new', string]>([-1, ""]);
const [newTag, setNewTag] = useState<[string, string]>(["", ""]);
const [[errorIndex, error], _setError] = useState<[number | "new", string]>([
-1,
"",
]);
const errorTimeoutId = useRef(-1);
// aliases
const foundNewTagNames = tagDB.getTagNames(tags.map(([n, _]) => n));
const setError = (index: number | 'new', msg: string) => {
_setError([index, msg])
const setError = (index: number | "new", msg: string) => {
_setError([index, msg]);
if (errorTimeoutId.current >= 0) {
window.clearTimeout(errorTimeoutId.current);
}
errorTimeoutId.current = window.setTimeout(() => _setError([-1, ""]), 5000);
}
const onUpdateMetadata = <K extends keyof AutomationMetadata>(k: K) => (update: AutomationMetadata[K]) => onUpdate({
...metadata,
[k]: update
}, tags);
};
const onUpdateMetadata =
<K extends keyof AutomationMetadata>(k: K) =>
(update: AutomationMetadata[K]) =>
onUpdate(
{
...metadata,
[k]: update,
},
tags
);
const validTagName = (newName: string): string | undefined => {
if (newName.length <= 0) {
return "Name must be at least 1 character long"
return "Name must be at least 1 character long";
}
// eslint-disable-next-line
for (const [name, _] of tags) {
if (name.trim() === newName.trim()) {
return `The tag '${name}' already exists`
return `The tag '${name}' already exists`;
}
}
}
};
const updateTagName = (newName: string, tagIndex: number) => {
const error = validTagName(newName);
if (error) {
return setError(tagIndex, error)
return setError(tagIndex, error);
}
onUpdate(metadata, [
...tags.slice(0, tagIndex),
[newName, tags[tagIndex][1]],
...tags.slice(tagIndex + 1),
])
}
const onUpdateTags = (tagValue: string, tagIndex: number) => onUpdate(metadata, [
...tags.slice(0, tagIndex),
[tags[tagIndex][0], tagValue],
...tags.slice(tagIndex + 1),
])
]);
};
const onUpdateTags = (tagValue: string, tagIndex: number) =>
onUpdate(metadata, [
...tags.slice(0, tagIndex),
[tags[tagIndex][0], tagValue],
...tags.slice(tagIndex + 1),
]);
const addNewTag = () => {
const error = validTagName(newTag[0]);
if (error) {
return setError('new', error)
return setError("new", error);
}
onUpdate(metadata, tags.concat([
newTag.map(x => x.trim()) as [string, string]
]));
setNewTag(['', '']);
}
const onRemoveTag = (tagIndex: number) => onUpdate(metadata, [
...tags.slice(0, tagIndex),
...tags.slice(tagIndex + 1),
])
onUpdate(
metadata,
tags.concat([newTag.map((x) => x.trim()) as [string, string]])
);
setNewTag(["", ""]);
};
const onRemoveTag = (tagIndex: number) =>
onUpdate(metadata, [
...tags.slice(0, tagIndex),
...tags.slice(tagIndex + 1),
]);
// render
return <div className={`automation-editor--info-box ${className}`}>
<div className="automation-editor--info-box-inner">
<InputText label="ID" value={metadata.id} onChange={onUpdateMetadata('id')} />
<InputText label="Name" value={metadata.alias ?? ""} onChange={onUpdateMetadata('alias')} />
<InputText multiline label="Description" value={metadata.description ?? ""} onChange={onUpdateMetadata('description')} />
<InputList
label="Mode"
current={metadata.mode}
onChange={onUpdateMetadata('mode')}
options={[
'parallel',
'single',
'queued',
'restart'
]}
/>
<div className="automation-editor--info-box--tags">
<h1>Tags</h1>
<div className="automation-editor--info-box--tag-list">
{tags.map(([tagName, tagValue], tagIndex) => <div key={tagIndex} className="automation-editor--info-box--tag">
return (
<div className={`automation-editor--info-box ${className}`}>
<div className="automation-editor--info-box-inner">
<InputText
label="ID"
value={metadata.id}
onChange={onUpdateMetadata("id")}
/>
<InputText
label="Name"
value={metadata.alias ?? ""}
onChange={onUpdateMetadata("alias")}
/>
<InputText
multiline
label="Description"
value={metadata.description ?? ""}
onChange={onUpdateMetadata("description")}
/>
<InputList
label="Mode"
current={metadata.mode}
onChange={onUpdateMetadata("mode")}
options={["parallel", "single", "queued", "restart"]}
/>
<div className="automation-editor--info-box--tags">
<h1>Tags</h1>
<div className="automation-editor--info-box--tag-list">
{tags.map(([tagName, tagValue], tagIndex) => (
<div key={tagIndex} className="automation-editor--info-box--tag">
<InputAutoText
value={tagName}
label="Name"
onChange={(v) => updateTagName(v, tagIndex)}
options={foundNewTagNames}
error={errorIndex === tagIndex ? error : undefined}
/>
<InputAutoText
value={tagValue}
label="Tag"
onChange={(v) => onUpdateTags(v, tagIndex)}
options={tagDB.getTagValues(tagName)}
error={errorIndex === tagIndex ? error : undefined}
/>
<ButtonIcon
className="automation-editor--info-box--tag--trash"
onClick={() => onRemoveTag(tagIndex)}
icon={<TrashIcon />}
/>
</div>
))}
</div>
<hr />
<div className="automation-editor--info-box--tag">
<InputAutoText
value={tagName}
value={newTag[0]}
label="Name"
onChange={v => updateTagName(v, tagIndex)}
onChange={(v) => setNewTag([v, newTag[1]])}
options={foundNewTagNames}
error={errorIndex === tagIndex ? error : undefined}
error={errorIndex === "new" ? error : undefined}
/>
<InputAutoText
value={tagValue}
value={newTag[1]}
label="Tag"
onChange={v => onUpdateTags(v, tagIndex)}
options={tagDB.getTagValues(tagName)}
error={errorIndex === tagIndex ? error : undefined}
onChange={(v) => setNewTag([newTag[0], v])}
options={tagDB.getTagValues(newTag[0])}
error={errorIndex === "new" ? error : undefined}
/>
<Button className="automation-editor--info-box--tag--trash" onClick={() => onRemoveTag(tagIndex)} ><TrashIcon /></Button>
</div>)}
</div>
<hr />
<div className="automation-editor--info-box--tag">
<InputAutoText
value={newTag[0]}
label="Name"
onChange={v => setNewTag([v, newTag[1]])}
options={foundNewTagNames}
error={errorIndex === 'new' ? error : undefined}
/>
<InputAutoText
value={newTag[1]}
label="Tag"
onChange={v => setNewTag([newTag[0], v])}
options={tagDB.getTagValues(newTag[0])}
error={errorIndex === 'new' ? error : undefined}
/>
<Button className="automation-editor--info-box--tag--add" onClick={addNewTag} ><AddIcon /></Button>
<ButtonIcon
className="automation-editor--info-box--tag--add"
onClick={addNewTag}
icon={<AddIcon />}
/>
</div>
</div>
</div>
{children}
</div>
{children}
</div>
}
);
};
@@ -61,16 +61,19 @@
position: relative;
}
.automation-editor--info-box--icon {
.automation-editor .automation-editor--info-box--icon {
position: absolute;
right: 0em;
bottom: 0.5em;
left: 0.25em;
bottom: 0em;
z-index: 10;
max-width: 1.5em;
max-height: 1.5em;
}
.automation-editor--info-box.hide>.automation-editor--info-box--icon {
transform: rotate(180deg);
z-index: 2;
left: 0.1em;
}
.automation-editor.loading .mock-list {
+162 -123
View File
@@ -1,19 +1,21 @@
import "./index.css";
import Icon from '@mui/material/Icon';
import { ArrowIcon, CheckMarkIcon } from "components/Icons";
import { FC, useEffect, useState } from "react";
import Icon from "@mui/material/Icon";
import { CheckMarkIcon } from "components/Icons";
import { FC, useState } from "react";
import { AutomationData } from "types/automations";
import { AutoInfoBox } from "./AutoInfoBox";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { Button } from "components/Inputs/Button";
import { useAutomatioEditorState, EditorData } from './state';
import { useAutomatioEditorState, EditorData } from "./state";
import { SafeDAGAutomationFlow } from "components/DAGFlow/safe";
import { DAGAutomationFlowDims } from "components/DAGFlow/types";
import { MiniFailure } from 'types/validators/helper';
import { MiniFailure } from "types/validators/helper";
import InputYaml from "components/Inputs/InputYaml";
import { TagDB } from "components/AutomationList/TagDB";
import Skeleton from "@mui/material/Skeleton";
import LinearProgress from "@mui/material/LinearProgress";
import { ArrowBack } from "@mui/icons-material";
import { useCookies } from "react-cookie";
interface Props {
automation?: AutomationData;
@@ -39,133 +41,170 @@ export const AutomationEditor: FC<Props> = ({
saveAndUpdate,
} = useAutomatioEditorState(propsAutos, propsOnUpdate);
const [closeInfo, setCloseInfo] = useState(false);
const [flipped, setFlipped] = useState(dims.flipped);
// effect
useEffect(() => {
if (dims.flipped !== flipped) {
setFlipped(dims.flipped)
}
}, [dims.flipped])
const [
{ ckFlipped },
setCookies,
// eslint-disable-next-line
_,
] = useCookies(["ckFlipped"]);
// alias
const flipped = dims.flipped ? true : ckFlipped === "1";
const setFlipped = (v: boolean) => setCookies("ckFlipped", v ? "1" : "0");
// render
if (state.status === 'loading') {
return <div className="automation-editor loading">
<LinearProgress className="linear-loader" />
<Skeleton className="mock-list" variant="rectangular" />
<Skeleton className="mock-graph" variant="rectangular" />
</div>
}
if (state.status === 'invalid') {
return <ValidationBox
failures={state.failures}
data={state.data}
validate={validate}
onSave={saveAndUpdate}
/>
}
return <div className="automation-editor">
{state.status === 'saving' && <LinearProgress className="linear-loader" />}
<AutoInfoBox
className={closeInfo ? "hide" : "show"}
metadata={state.data.metadata}
tags={state.data.tags}
onUpdate={updateMetadata}
tagDB={tagDB}
>
<ButtonIcon
className="automation-editor--info-box--icon"
onClick={() => setCloseInfo(!closeInfo)}
title={closeInfo ? "Show Metadata" : "Hide Metadata"}
Icon={ArrowIcon}
/>
</AutoInfoBox>
<div className={["automation-editor--flow-wrapper", state.status].join(" ")}>
<div className="automation-editor--flow-wrapper--toolbar">
{!dims.flipped && <Button
className={"automation-editor--flow-wrapper--toolbar--flip-btn"}
onClick={() => setFlipped(!flipped)}
>
<Icon>{flipped ? 'flip_to_front' : 'flip_to_back'}</Icon>
Flip
</Button>}
<Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save}
disabled={state.status !== 'changed'}
>
Save <CheckMarkIcon color="#bf4" />
</Button>
if (state.status === "loading") {
return (
<div className="automation-editor loading">
<LinearProgress className="linear-loader" />
<Skeleton className="mock-list" variant="rectangular" />
<Skeleton className="mock-graph" variant="rectangular" />
</div>
<SafeDAGAutomationFlow
className="automation-editor--flow-wrapper--flow"
sequence={state.data.sequence}
trigger={state.data.trigger}
condition={state.data.condition}
onSequenceUpdate={updateSequence}
onTriggerUpdate={updateTrigger}
onConditionUpdate={updateCondition}
dims={{
...dims,
flipped,
}}
);
}
if (state.status === "invalid") {
return (
<ValidationBox
failures={state.failures}
data={state.data}
validate={validate}
onSave={saveAndUpdate}
/>
</div>
</div>
}
);
}
return (
<div className="automation-editor">
{state.status === "saving" && (
<LinearProgress className="linear-loader" />
)}
<AutoInfoBox
className={closeInfo ? "hide" : "show"}
metadata={state.data.metadata}
tags={state.data.tags}
onUpdate={updateMetadata}
tagDB={tagDB}
>
<ButtonIcon
className="automation-editor--info-box--icon"
onClick={() => setCloseInfo(!closeInfo)}
title={closeInfo ? "Show Metadata" : "Hide Metadata"}
color="success"
icon={<ArrowBack />}
/>
</AutoInfoBox>
<div
className={["automation-editor--flow-wrapper", state.status].join(" ")}
>
<div className="automation-editor--flow-wrapper--toolbar">
{!dims.flipped && (
<Button
className={"automation-editor--flow-wrapper--toolbar--flip-btn"}
onClick={() => setFlipped(!flipped)}
>
<Icon>{flipped ? "flip_to_front" : "flip_to_back"}</Icon>
Flip
</Button>
)}
<Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save}
disabled={state.status !== "changed"}
>
Save <CheckMarkIcon color="#bf4" />
</Button>
</div>
<SafeDAGAutomationFlow
className="automation-editor--flow-wrapper--flow"
sequence={state.data.sequence}
trigger={state.data.trigger}
condition={state.data.condition}
onSequenceUpdate={updateSequence}
onTriggerUpdate={updateTrigger}
onConditionUpdate={updateCondition}
dims={{
...dims,
flipped,
}}
/>
</div>
</div>
);
};
export const ValidationBox: FC<{
failures: MiniFailure[]
validate: (d: any) => MiniFailure[] | null,
data: EditorData,
onSave: (d: EditorData) => void,
}> = props => {
failures: MiniFailure[];
validate: (d: any) => MiniFailure[] | null;
data: EditorData;
onSave: (d: EditorData) => void;
}> = (props) => {
const [{ failures, data }, setState] = useState({
failures: props.failures,
data: props.data,
});
const makeSave = <K extends keyof EditorData>(k: K) => (d: EditorData[K]) => {
const newData = {
...data,
[k]: d,
}
const newFails = props.validate(newData);
if (newFails) {
setState({
failures: newFails,
data: newData,
})
} else {
setState({
failures: [],
data: newData,
})
}
}
const makeSave =
<K extends keyof EditorData>(k: K) =>
(d: EditorData[K]) => {
const newData = {
...data,
[k]: d,
};
const newFails = props.validate(newData);
if (newFails) {
setState({
failures: newFails,
data: newData,
});
} else {
setState({
failures: [],
data: newData,
});
}
};
return <div className="automation-editor-failures">
<ul>
{failures.map((f, i) => <>
<li key={i}>
<b>{f.path}</b>:
<ul>
{f.message.map((m, j) => <li key={j}>
{m}
</li>)}
</ul>
</li>
</>)}
</ul>
<span>Please correct the automation file manually and then continue!</span>
<InputYaml label="Metadata" value={data.metadata} onChange={makeSave('metadata')} />
<InputYaml label="Tags" value={data.tags} onChange={makeSave('tags')} />
<InputYaml label="Trigger" value={data.trigger} onChange={makeSave('trigger')} />
<InputYaml label="Condition" value={data.condition} onChange={makeSave('condition')} />
<InputYaml label="Actions" value={data.sequence} onChange={makeSave('sequence')} />
<Button disabled={failures.length > 0} onClick={() => props.onSave(data)}>Save</Button>
</div>
}
return (
<div className="automation-editor-failures">
<ul>
{failures.map((f, i) => (
<>
<li key={i}>
<b>{f.path}</b>:
<ul>
{f.message.map((m, j) => (
<li key={j}>{m}</li>
))}
</ul>
</li>
</>
))}
</ul>
<span>
Please correct the automation file manually and then continue!
</span>
<InputYaml
label="Metadata"
value={data.metadata}
onChange={makeSave("metadata")}
/>
<InputYaml label="Tags" value={data.tags} onChange={makeSave("tags")} />
<InputYaml
label="Trigger"
value={data.trigger}
onChange={makeSave("trigger")}
/>
<InputYaml
label="Condition"
value={data.condition}
onChange={makeSave("condition")}
/>
<InputYaml
label="Actions"
value={data.sequence}
onChange={makeSave("sequence")}
/>
<Button disabled={failures.length > 0} onClick={() => props.onSave(data)}>
Save
</Button>
</div>
);
};
@@ -1,5 +1,5 @@
import "./AutomationListBox.css";
import { FC, useState } from 'react';
import { FC, useState } from "react";
import { AutomationData } from "types/automations";
import InputMultiSelect from "components/Inputs/InputMultiSelect";
import InputText from "components/Inputs/InputText";
@@ -8,121 +8,135 @@ import { makeGrouping } from "./automationGrouper";
import { AutomationListBoxGroup } from "./AutomationListBoxGroup";
import { useCookies } from "react-cookie";
export type Props = {
automations: AutomationData[];
selected: number;
onSelectAutomation: (i: number) => void;
onRemove: (i: number) => void;
onAdd: () => void;
}
automations: AutomationData[];
selected: number;
onSelectAutomation: (i: number) => void;
onRemove: (i: number) => void;
onAdd: () => void;
};
const useAutomationListBoxState = () => {
const [cookies, setCookies, _] = useCookies(['albSearchText', 'albSelected']);
let initialSelected = [];
try {
initialSelected = JSON.parse(cookies.albSelected)
if (!Array.isArray(initialSelected)) {
initialSelected = [initialSelected]
}
initialSelected = initialSelected.map(Number)
// eslint-disable-next-line
} catch (_) { }
const [searchText, setSearchText] = useState(cookies.albSearchText ?? "");
const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>(initialSelected);
return {
searchText,
setSearchText(v: string) {
setSearchText(v)
setCookies('albSearchText', v)
},
setSelectedTagIdx(n: number[]) {
setSelectedTagIdx(n)
setCookies('albSelected', JSON.stringify(n))
},
selectedTagIdx,
const [
cookies,
setCookies,
// eslint-disable-next-line
_,
] = useCookies(["albSearchText", "albSelected"]);
let initialSelected = [];
try {
initialSelected = JSON.parse(cookies.albSelected);
if (!Array.isArray(initialSelected)) {
initialSelected = [initialSelected];
}
}
initialSelected = initialSelected.map(Number);
// eslint-disable-next-line
} catch (_) {}
const [searchText, setSearchText] = useState(cookies.albSearchText ?? "");
const [selectedTagIdx, setSelectedTagIdx] =
useState<number[]>(initialSelected);
return {
searchText,
setSearchText(v: string) {
setSearchText(v);
setCookies("albSearchText", v);
},
setSelectedTagIdx(n: number[]) {
setSelectedTagIdx(n);
setCookies("albSelected", JSON.stringify(n));
},
selectedTagIdx,
};
};
export const AutomationListBox: FC<Props> = ({
automations,
selected,
onSelectAutomation,
onAdd,
onRemove,
automations,
selected,
onSelectAutomation,
onAdd,
onRemove,
}) => {
const tags = getTagList(automations);
const { searchText, setSearchText, selectedTagIdx, setSelectedTagIdx } =
useAutomationListBoxState();
const filteredAutomations = filterAutomations(
automations,
searchText.toLowerCase()
);
const grouping = makeGrouping(
filteredAutomations.map(([a, _]) => a),
selectedTagIdx.map((i) => tags[i]),
selected
);
const tags = getTagList(automations);
const {
searchText,
setSearchText,
selectedTagIdx,
setSelectedTagIdx,
} = useAutomationListBoxState();
const filteredAutomations = filterAutomations(automations, searchText.toLowerCase(), selectedTagIdx, tags);
const grouping = makeGrouping(
filteredAutomations.map(([a, _]) => a),
selectedTagIdx.map(i => tags[i]),
selected,
)
return <div className="automation-list-box">
<div className="automation-list-box--nav">
<InputText
label="Search"
value={searchText}
onChange={setSearchText}
/>
<InputMultiSelect
label="Tags"
selected={selectedTagIdx}
onChange={setSelectedTagIdx}
options={tags}
max={3}
/>
</div>
<div className="automation-list-box--body">
<AutomationListBoxGroup
events={{
onSelectAutomation,
onRemove
}}
autos={filteredAutomations}
grouping={grouping}
selectedAutomationIdx={selected}
/>
</div>
<div className="automation-list-box--bottom">
<Button onClick={onAdd}>Add</Button>
<span>Showing Automations: {filteredAutomations.length} out of {automations.length}</span>
</div>
return (
<div className="automation-list-box">
<div className="automation-list-box--nav">
<InputText label="Search" value={searchText} onChange={setSearchText} />
<InputMultiSelect
label="Tags"
selected={selectedTagIdx}
onChange={setSelectedTagIdx}
options={tags}
max={3}
/>
</div>
<div className="automation-list-box--body">
<AutomationListBoxGroup
events={{
onSelectAutomation,
onRemove,
}}
autos={filteredAutomations}
grouping={grouping}
selectedAutomationIdx={selected}
/>
</div>
<div className="automation-list-box--bottom">
<Button onClick={onAdd}>Add</Button>
<span>
Showing Automations: {filteredAutomations.length} out of{" "}
{automations.length}
</span>
</div>
</div>
}
);
};
export const getTagList = (autos: AutomationData[]): string[] => Object.keys(autos
.map(a => Object.keys(a.tags))
.reduce((all: any, keys) => {
export const getTagList = (autos: AutomationData[]): string[] =>
Object.keys(
autos
.map((a) => Object.keys(a.tags))
.reduce((all: any, keys) => {
for (const k of keys) {
all[k] = 1
all[k] = 1;
}
return all;
}, {}))
}, {})
);
const filterAutomations = (autos: AutomationData[], searchText: string, selected: number[], tags: string[]): Array<[AutomationData, number]> => autos.map<[AutomationData, number]>((a, i) => [a, i]).filter(([a, i]) => {
if (!a.metadata) {
return true
}
if (searchText.length > 0) {
const filterAutomations = (
autos: AutomationData[],
searchText: string
): Array<[AutomationData, number]> =>
autos
.map<[AutomationData, number]>((a, i) => [a, i])
.filter(([a, i]) => {
if (!a.metadata) {
return true;
}
if (searchText.length > 0) {
if (
!(
(a.metadata.description ?? "").toLocaleLowerCase().includes(searchText) ||
(a.metadata.alias ?? "").toLocaleLowerCase().includes(searchText)
)
!(
(a.metadata.description ?? "")
.toLocaleLowerCase()
.includes(searchText) ||
(a.metadata.alias ?? "").toLocaleLowerCase().includes(searchText)
)
) {
return false
return false;
}
}
return true
})
}
return true;
});
@@ -1,141 +1,166 @@
import { TrashIcon } from "components/Icons";
import { Button } from "components/Inputs/Button";
import { MetadataBox } from "./AutomationMetadataBox";
import { AutomationData } from "types/automations";
import { AutomationGrouping } from "./automationGrouper";
import { FC, useState } from "react";
import { ButtonIcon } from "components/Icons/ButtonIcons";
export type AutomationListBoxEvents = {
onSelectAutomation: (i: number) => void,
onRemove: (i: number) => void,
}
onSelectAutomation: (i: number) => void;
onRemove: (i: number) => void;
};
export type AutomationListBoxGroups = {
grouping: AutomationGrouping,
currentNode: number,
}
grouping: AutomationGrouping;
currentNode: number;
};
export type AutomationListBoxProps = {
events: AutomationListBoxEvents,
groups: AutomationListBoxGroups,
autos: Array<[AutomationData, number]>,
selectedAutomationIdx: number,
events: AutomationListBoxEvents;
groups: AutomationListBoxGroups;
autos: Array<[AutomationData, number]>;
selectedAutomationIdx: number;
};
export type AutomationListBoxGroupProps = {
events: AutomationListBoxEvents,
grouping: AutomationGrouping,
autos: Array<[AutomationData, number]>,
selectedAutomationIdx: number,
}
events: AutomationListBoxEvents;
grouping: AutomationGrouping;
autos: Array<[AutomationData, number]>;
selectedAutomationIdx: number;
};
export const AutomationListBoxGroup: FC<AutomationListBoxGroupProps> = ({
events, grouping, autos, selectedAutomationIdx,
events,
grouping,
autos,
selectedAutomationIdx,
}) => {
if (grouping.top.length === 1) {
return <>
{convertGroupsToItems(autos, {
grouping, currentNode: grouping.top[0],
}, events, selectedAutomationIdx)}
</>
} else {
return <>
{grouping.top.map(groupIdx => <AutomationListBoxGroupItem
key={groupIdx}
autos={autos}
groups={{
grouping,
currentNode: groupIdx
}}
events={events}
selectedAutomationIdx={selectedAutomationIdx}
/>)}
</>
}
}
export const convertGroupsToItems = (
autos: Array<[AutomationData, number]>,
{ grouping, currentNode }: AutomationListBoxGroups,
events: AutomationListBoxEvents,
selectedAutomationIdx: number,
) => {
const automations = grouping.getAutomations(currentNode);
if (automations.length > 0) {
return automations.map(autoIndex =>
<AutomationListBoxItem
key={`${autoIndex}-${autos[autoIndex][1]}`}
events={events}
auto={autos[autoIndex]}
isSelected={selectedAutomationIdx === autos[autoIndex][1]}
/>
)
}
const subgroups = grouping.getSubGroups(currentNode);
if (subgroups.length > 0) {
return subgroups.map(groupIdx => <AutomationListBoxGroupItem
if (grouping.top.length === 1) {
return (
<>
{convertGroupsToItems(
autos,
{
grouping,
currentNode: grouping.top[0],
},
events,
selectedAutomationIdx
)}
</>
);
} else {
return (
<>
{grouping.top.map((groupIdx) => (
<AutomationListBoxGroupItem
key={groupIdx}
autos={autos}
groups={{
grouping,
currentNode: groupIdx
grouping,
currentNode: groupIdx,
}}
events={events}
selectedAutomationIdx={selectedAutomationIdx}
/>)
}
return <></>
}
/>
))}
</>
);
}
};
export const convertGroupsToItems = (
autos: Array<[AutomationData, number]>,
{ grouping, currentNode }: AutomationListBoxGroups,
events: AutomationListBoxEvents,
selectedAutomationIdx: number
) => {
const automations = grouping.getAutomations(currentNode);
if (automations.length > 0) {
return automations.map((autoIndex) => (
<AutomationListBoxItem
key={`${autoIndex}-${autos[autoIndex][1]}`}
events={events}
auto={autos[autoIndex]}
isSelected={selectedAutomationIdx === autos[autoIndex][1]}
/>
));
}
const subgroups = grouping.getSubGroups(currentNode);
if (subgroups.length > 0) {
return subgroups.map((groupIdx) => (
<AutomationListBoxGroupItem
key={groupIdx}
autos={autos}
groups={{
grouping,
currentNode: groupIdx,
}}
events={events}
selectedAutomationIdx={selectedAutomationIdx}
/>
));
}
return <></>;
};
export const AutomationListBoxGroupItem: FC<{
events: AutomationListBoxEvents,
groups: AutomationListBoxGroups,
autos: Array<[AutomationData, number]>,
selectedAutomationIdx: number,
}> = ({
autos, groups, events, selectedAutomationIdx,
}) => {
const groupData = groups.grouping.getData(groups.currentNode);
const automations = groups.grouping.getAutomations(groups.currentNode);
const [open, setOpen] = useState(false);
const isOther = groupData.isOther;
const openIcon = !open ? "⊕" : "⊖";
const total = isOther ? <small>
{automations.length} automation{automations.length !== 1 ? 's' : ''} {groupData.isOther ? "" : "(untagged)"}
</small> : <></>
return <div className={[
"automation-list-box--body--group",
isOther ? 'other' : '',
groupData.selected ? 'selected' : '',
].join(' ')}>
<b onClick={() => setOpen(!open)}>{groupData.name} {openIcon} {total}</b>
{open && convertGroupsToItems(autos, groups, events, selectedAutomationIdx)}
</div>
}
events: AutomationListBoxEvents;
groups: AutomationListBoxGroups;
autos: Array<[AutomationData, number]>;
selectedAutomationIdx: number;
}> = ({ autos, groups, events, selectedAutomationIdx }) => {
const groupData = groups.grouping.getData(groups.currentNode);
const automations = groups.grouping.getAutomations(groups.currentNode);
const [open, setOpen] = useState(false);
const isOther = groupData.isOther;
const openIcon = !open ? "⊕" : "⊖";
const total = isOther ? (
<small>
{automations.length} automation{automations.length !== 1 ? "s" : ""}{" "}
{groupData.isOther ? "" : "(untagged)"}
</small>
) : (
<></>
);
return (
<div
className={[
"automation-list-box--body--group",
isOther ? "other" : "",
groupData.selected ? "selected" : "",
].join(" ")}
>
<b onClick={() => setOpen(!open)}>
{groupData.name} {openIcon} {total}
</b>
{open &&
convertGroupsToItems(autos, groups, events, selectedAutomationIdx)}
</div>
);
};
export const AutomationListBoxItem: FC<{
auto: [AutomationData, number],
isSelected: boolean,
events: AutomationListBoxEvents,
auto: [AutomationData, number];
isSelected: boolean;
events: AutomationListBoxEvents;
}> = ({
events: {
onRemove,
onSelectAutomation,
},
auto: [
auto, autoIndex
],
isSelected,
events: { onRemove, onSelectAutomation },
auto: [auto, autoIndex],
isSelected,
}) => {
let title = "BadAuto<<Missing Metadata>>"
if (auto.metadata) {
title = `Name = ${auto.metadata.alias}\nID = ${auto.metadata.id}\nDescription = ${auto.metadata.description}`
}
return <div
key={autoIndex}
className={["automation-list-box--body--item", isSelected ? 'selected' : ''].join(' ')}
title={title}
onClick={() => onSelectAutomation(autoIndex)}
>
<MetadataBox metadata={auto.metadata} tags={auto.tags} />
<Button onClick={() => onRemove(autoIndex)}><TrashIcon /></Button>
</div>
}
let title = "BadAuto<<Missing Metadata>>";
if (auto.metadata) {
title = `Name = ${auto.metadata.alias}\nID = ${auto.metadata.id}\nDescription = ${auto.metadata.description}`;
}
return (
<div
key={autoIndex}
className={[
"automation-list-box--body--item",
isSelected ? "selected" : "",
].join(" ")}
title={title}
onClick={() => onSelectAutomation(autoIndex)}
>
<MetadataBox metadata={auto.metadata} tags={auto.tags} />
<ButtonIcon onClick={() => onRemove(autoIndex)} icon={<TrashIcon />} />
</div>
);
};
@@ -50,6 +50,7 @@
.automation-list--list.hide>.automation-list--list-hide {
transform: rotate(180deg);
left: 0;
}
/* list children: normal */
@@ -58,8 +59,10 @@
border-width: 1px;
}
.automation-list--list-hide {
.automation-list--list .automation-list--list-hide {
position: absolute;
bottom: 0.5em;
right: 0.5em;
bottom: 0em;
left: 0.5em;
max-width: 1.5em;
max-height: 1.5em;
}
@@ -14,7 +14,7 @@
.automation-list--root.mobile .automation-list--list-hide {
transform: rotate(90deg);
left: 1.25em;
left: 0.25em;
}
.automation-list--root.mobile .automation-editor--info-box {
@@ -33,7 +33,7 @@
}
.automation-list--root.mobile .automation-editor--info-box--icon {
left: 1.25em;
left: 0.5em;
bottom: 0em;
background-color: var(--primary);
transform: rotate(90deg);
@@ -50,8 +50,8 @@
.automation-list--root.mobile .automation-list--list.hide .automation-list--list-hide {
transform: rotate(270deg);
position: fixed;
top: 0.75em;
z-index: 20;
top: 0;
z-index: 5;
}
/* info box hide */
@@ -64,9 +64,9 @@
.automation-list--root.mobile .automation-editor--info-box.hide .automation-editor--info-box--icon {
transform: rotate(270deg);
position: fixed;
top: 0.75em;
background-color: var(--green-opaque);
z-index: 30;
top: 0em;
left: 0.25em;
z-index: 10;
}
+105 -71
View File
@@ -3,18 +3,18 @@ import "./index.mobile.css";
import { AutomationEditor } from "components/AutomationEditor";
import { FC, ReactNode, useState } from "react";
import { AutomationData } from "types/automations";
import { defaultAutomation } from 'utils/defaults';
import { ArrowIcon } from "components/Icons";
import { defaultAutomation } from "utils/defaults";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { ApiService } from "apiService/core";
import { AutomationListBox } from "./AutomationListBox";
import { DAGAutomationFlowDims } from 'components/DAGFlow/types';
import { DAGAutomationFlowDims } from "components/DAGFlow/types";
import useWindowSize from "utils/useWindowSize";
import { makeTagDB } from "./TagDB";
import LinearProgress from "@mui/material/LinearProgress";
import CircularProgress from "@mui/material/CircularProgress";
import { useCookies } from 'react-cookie';
import { useCookies } from "react-cookie";
import { useHA } from "haService";
import { ArrowBack } from "@mui/icons-material";
interface AutomationListParams {
automations: AutomationData[];
@@ -26,12 +26,16 @@ 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 (_) { }
initialCurrent = Number(cookies.alCurrent ?? "0");
} catch (_) {}
const [hideList, setHideList] = useState(false);
const [current, setCurrent] = useState(initialCurrent);
@@ -41,11 +45,11 @@ export const useAutomationListState = () => {
setHideList,
current,
setCurrent(i: number) {
setCurrent(i)
setCookies('alCurrent', String(i))
}
}
}
setCurrent(i);
setCookies("alCurrent", String(i));
},
};
};
export const AutomationList: FC<AutomationListParams> = ({
automations,
@@ -56,49 +60,65 @@ export const AutomationList: FC<AutomationListParams> = ({
children,
}) => {
// state
const { hideList, setHideList, current, setCurrent } = useAutomationListState();
const { hideList, setHideList, current, setCurrent } =
useAutomationListState();
const { isMobile } = useWindowSize();
// alias
const currentAuto = automations.length > 0 ? automations[current] : null;
const tagDB = makeTagDB(automations);
// render
return <div className={["automation-list--root", isMobile ? 'mobile' : ''].join(' ')}>
<div className={["automation-list--list", hideList ? "hide" : "show"].join(' ')}>
<AutomationListBox
automations={automations}
onAdd={() => {
onAdd(defaultAutomation(String(Date.now())));
setCurrent(automations.length)
}}
onSelectAutomation={i => {
setCurrent(i);
if (isMobile) {
setHideList(true)
}
}}
selected={current}
onRemove={onRemove}
/>
<ButtonIcon
onClick={() => setHideList(!hideList)}
className="automation-list--list-hide"
Icon={ArrowIcon}
/>
return (
<div
className={["automation-list--root", isMobile ? "mobile" : ""].join(" ")}
>
<div
className={["automation-list--list", hideList ? "hide" : "show"].join(
" "
)}
>
<AutomationListBox
automations={automations}
onAdd={() => {
onAdd(defaultAutomation(String(Date.now())));
setCurrent(automations.length);
if (isMobile) {
setHideList(true);
}
}}
onSelectAutomation={(i) => {
setCurrent(i);
if (isMobile) {
setHideList(true);
}
}}
selected={current}
onRemove={onRemove}
/>
<ButtonIcon
onClick={() => setHideList(!hideList)}
className="automation-list--list-hide"
icon={<ArrowBack />}
/>
</div>
<div className="automation-list--viewer">
{currentAuto ? (
<AutomationEditor
automation={currentAuto}
onUpdate={(a) => onUpdate(current, a)}
dims={{
...dims,
flipped: isMobile,
}}
tagDB={tagDB}
/>
) : (
<></>
)}
</div>
{children}
</div>
<div className="automation-list--viewer">
{currentAuto ? <AutomationEditor
automation={currentAuto}
onUpdate={a => onUpdate(current, a)}
dims={{
...dims,
flipped: isMobile
}}
tagDB={tagDB}
/> : <></>}
</div>
{children}
</div>
}
);
};
interface ConnectedAutomationListParams {
dims: DAGAutomationFlowDims;
@@ -106,30 +126,44 @@ interface ConnectedAutomationListParams {
}
export const ConnectedAutomationList: FC<ConnectedAutomationListParams> = ({
api: {
state: {
automations,
},
removeAutomation,
updateAutomation,
state: { automations },
...methods
},
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) {
return <div className="automation-list--root loading">
<LinearProgress />
<div className="automation-list--circle-loader">
<CircularProgress />
return (
<div className="automation-list--root loading">
<LinearProgress />
<div className="automation-list--circle-loader">
<CircularProgress />
</div>
</div>
</div>
);
}
if (!automations.ok) {
return <span>Error {automations.error}</span>
return <span>Error {automations.error}</span>;
}
return <AutomationList
dims={dims}
automations={automations.data.data}
onAdd={auto => updateAutomation({ auto, index: automations.data.totalItems + 1 })}
onRemove={index => removeAutomation({ index })}
onUpdate={(index, auto) => updateAutomation({ index, auto })}
/>
}
return (
<AutomationList
dims={dims}
automations={automations.data.data}
onAdd={(auto) =>
updateAutomation({ auto, index: automations.data.totalItems + 1 })
}
onRemove={(index) => removeAutomation({ index })}
onUpdate={(index, auto) => updateAutomation({ index, auto })}
/>
);
};
@@ -1,5 +1,5 @@
import { Classes } from "jss";
import { FC, useState, useEffect } from 'react';
import { FC, useState, useEffect } from "react";
import { getConditionDefaultValues } from "utils/defaults";
import { AutomationCondition } from "types/automations/conditions";
import { CheckMarkIcon, PencilIcon } from "components/Icons";
@@ -10,126 +10,151 @@ import { useStyles } from "./style";
import { getViewer } from "./viewRender";
import useWindowSize from "utils/useWindowSize";
import { useHA } from "haService";
import { getSubTypeList } from "utils/automations";
export const ConditionNode: FC<{
condition: AutomationCondition;
displayMode: boolean;
showDelete?: boolean;
onDelete?: (which: 'root' | number) => void;
onDelete?: (which: "root" | number) => void;
onUpdate?: (data: AutomationCondition) => void;
children?: (props: {
classes: Classes<string>
}) => JSX.Element,
children?: (props: { classes: Classes<string> }) => JSX.Element;
}> = ({
condition,
showDelete = false,
displayMode = true,
onDelete = () => { },
onUpdate = () => { },
children = () => { },
onDelete = () => {},
onUpdate = () => {},
children = () => {},
}) => {
// state
const [internalDisplayMode, setInternalDisplayMode] = useState(displayMode);
const [yamlMode, setYamlMode] = useState(false);
const { isMobile } = useWindowSize();
const { namer } = useHA();
// alias
const effectiveDM = internalDisplayMode || yamlMode;
// effect
useEffect(() => {
setInternalDisplayMode(displayMode);
}, [displayMode])
useEffect(() => {
if (yamlMode) {
setInternalDisplayMode(true);
}
}, [yamlMode])
// alias
const onAddChild = () => {
if (
(condition.condition === 'and') ||
(condition.condition === 'or') ||
(condition.condition === 'not')
) {
onUpdate({
...condition,
conditions: condition.conditions.concat({
condition: 'or',
conditions: []
})
})
}
// state
const [internalDisplayMode, setInternalDisplayMode] = useState(displayMode);
const [yamlMode, setYamlMode] = useState(false);
const { isMobile } = useWindowSize();
const ha = useHA();
// alias
const effectiveDM = internalDisplayMode || yamlMode;
// effect
useEffect(() => {
setInternalDisplayMode(displayMode);
}, [displayMode]);
useEffect(() => {
if (yamlMode) {
setInternalDisplayMode(true);
}
// children
let childrenConditions: JSX.Element;
if (effectiveDM) {
const Viewer = getViewer(condition);
childrenConditions = <Viewer condition={condition} onChange={onUpdate} namer={namer} />
} else {
const Editor = getEditor(condition);
childrenConditions = <Editor condition={condition} onChange={onUpdate} />
}, [yamlMode]);
// alias
const onAddChild = () => {
if (
condition.condition === "and" ||
condition.condition === "or" ||
condition.condition === "not"
) {
onUpdate({
...condition,
conditions: condition.conditions.concat({
condition: "or",
conditions: [],
}),
});
}
// styles
let hasChildren = false;
if (condition.condition === "not") {
hasChildren = true
} else if (condition.condition === 'and') {
hasChildren = true
} else if (condition.condition === 'or') {
hasChildren = true
}
const { classes } = useStyles({ hasChildren, isMobile });
};
// children
let childrenConditions: JSX.Element;
if (effectiveDM) {
const Viewer = getViewer(condition);
childrenConditions = (
<Viewer condition={condition} onChange={onUpdate} namer={ha.namer} />
);
} else {
const Editor = getEditor(condition);
childrenConditions = (
<Editor condition={condition} onChange={onUpdate} ha={ha} />
);
}
// styles
let hasChildren = false;
if (condition.condition === "not") {
hasChildren = true;
} else if (condition.condition === "and") {
hasChildren = true;
} else if (condition.condition === "or") {
hasChildren = true;
}
const { classes } = useStyles({ hasChildren, isMobile });
// components
const DeleteButton = (p: { onClick?: () => void, isRoot?: boolean }) =>
<button className={p.isRoot ? classes.deleteBtnRoot : classes.deleteBtn} onClick={p?.onClick}>X</button>
// components
const DeleteButton = (p: { onClick?: () => void; isRoot?: boolean }) => (
<button
className={p.isRoot ? classes.deleteBtnRoot : classes.deleteBtn}
onClick={p?.onClick}
>
X
</button>
);
return <div className={classes.root}>
return (
<div className={classes.root}>
<>
{(showDelete && !effectiveDM) && <DeleteButton isRoot onClick={() => onDelete('root')} />}
{showDelete && !effectiveDM && (
<DeleteButton isRoot onClick={() => onDelete("root")} />
)}
<div className={classes.title}>
<InputList
label=""
className={classes.titleText}
current={condition.condition}
options={[
'or', 'not', 'and',
'template',
'numeric_state',
'state',
'time',
'trigger',
'zone',
]}
onChange={(n: any) => onUpdate({
...getConditionDefaultValues(n),
...condition,
condition: n,
} as any)}
options={getSubTypeList("condition")}
onChange={(n: any) =>
onUpdate({
...getConditionDefaultValues(n),
...condition,
condition: n,
} as any)
}
/>
{effectiveDM && <button className={classes.yamlBtn} onClick={() => setYamlMode(!yamlMode)}>
{yamlMode ? 'visual' : 'yaml'}
</button>}
{!yamlMode && <button className={classes.modifyBtn} onClick={() => setInternalDisplayMode(!effectiveDM)}>
{effectiveDM ? <PencilIcon className={classes.icon} /> : <CheckMarkIcon className={classes.icon} />}
</button>}
{effectiveDM && (
<button
className={classes.yamlBtn}
onClick={() => setYamlMode(!yamlMode)}
>
{yamlMode ? "visual" : "yaml"}
</button>
)}
{!yamlMode && (
<button
className={classes.modifyBtn}
onClick={() => setInternalDisplayMode(!effectiveDM)}
>
{effectiveDM ? (
<PencilIcon className={classes.icon} />
) : (
<CheckMarkIcon className={classes.icon} />
)}
</button>
)}
</div>
<div className={classes.children}>
{yamlMode && <InputYaml
label=""
value={condition}
onChange={update => onUpdate(update as any)}
/>}
{yamlMode && (
<InputYaml
label=""
value={condition}
onChange={(update) => onUpdate(update as any)}
/>
)}
<div className={classes.conditionWrap}>
{!yamlMode && childrenConditions}
</div>
{!yamlMode && hasChildren && <div className={classes.addBtnContainer}>
<button className={classes.addBtn} onClick={() => onAddChild()}>Add</button>
</div>}
{!yamlMode && hasChildren && (
<div className={classes.addBtnContainer}>
<button className={classes.addBtn} onClick={() => onAddChild()}>
Add
</button>
</div>
)}
</div>
{children({ classes })}
</>
</div>
}
);
};
@@ -1,5 +1,15 @@
import { FC } from "react";
import { AutomationCondition, LogicCondition, NumericCondition, StateCondition, TemplateCondition, TimeCondition, TriggerCondition, ZoneCondition } from 'types/automations/conditions';
import {
AutomationCondition,
DeviceCondition,
LogicCondition,
NumericCondition,
StateCondition,
TemplateCondition,
TimeCondition,
TriggerCondition,
ZoneCondition,
} from "types/automations/conditions";
import InputNumber from "components/Inputs/InputNumber";
import InputText from "components/Inputs/InputText";
import { InputEntity } from "components/Inputs/InputEntities";
@@ -7,210 +17,308 @@ import { ConditionNode } from "./ConditionNode";
import { genUpdateMethods } from "./nestedUpdater";
import { InputTime } from "components/Inputs/InputTime";
import InputYaml from "components/Inputs/InputYaml";
import { HAService } from "haService";
import { DeviceEditor } from "components/DeviceEditor";
interface Editor<C extends AutomationCondition> extends FC<{
condition: C,
onChange: (condition: C) => void;
}> { }
interface Editor<C extends AutomationCondition>
extends FC<{
condition: C;
onChange: (condition: C) => void;
ha: HAService;
}> {}
export const getEditor = (condition: AutomationCondition): Editor<any> => {
switch (condition.condition) {
case 'template':
case "template":
return TemplateEditor;
case 'and':
case "and":
return LogicViewer;
case 'or':
case "or":
return LogicViewer;
case 'not':
case "not":
return LogicViewer;
case 'numeric_state':
case "device":
return DeviceConditionEditor;
case "numeric_state":
return NumericStateEditor;
case 'state':
case "state":
return StateEditor;
case 'time':
case "time":
return TimeEditor;
case 'trigger':
case "trigger":
return TriggerEditor;
case 'zone':
case "zone":
return ZoneEditor;
default:
return () => <div>Not Ready</div>
return () => <div>Not Ready</div>;
}
}
};
export const TemplateEditor: Editor<TemplateCondition> = ({
onChange,
condition,
}) => {
return <>
<InputYaml label="Template" value={condition.value_template} onChange={value_template => onChange({
...condition,
value_template
})} />
</>
}
return (
<>
<InputYaml
label="Template"
value={condition.value_template}
onChange={(value_template) =>
onChange({
...condition,
value_template,
})
}
/>
</>
);
};
export const DeviceConditionEditor: Editor<DeviceCondition> = ({
onChange,
condition,
ha: {
deviceExtras: { useDeviceConditionCapalities, useDeviceConditions },
},
}) => {
return (
<DeviceEditor
type="condition"
state={condition}
setState={(data) =>
onChange({
condition: "device",
...data,
} as any)
}
options={useDeviceConditions(
condition.device_id
? {
deviceId: condition.device_id,
}
: undefined
)}
caps={useDeviceConditionCapalities(condition as any)}
/>
);
};
export const NumericStateEditor: Editor<NumericCondition> = ({
onChange,
condition,
}) => {
return <>
<InputEntity
value={condition.entity_id}
multiple
onChange={entity_id => onChange({
...condition,
entity_id
})}
/>
<InputText label="Attribute" value={condition.attribute ?? ""} onChange={attribute => onChange({
...condition,
attribute
})} />
<InputNumber
label="Above"
value={condition.above ? Number(condition.above) : undefined}
onChange={above => onChange({
...condition,
above: above ? String(above) : undefined,
})}
/>
<InputNumber
label="Below"
value={condition.below ? Number(condition.below) : undefined}
onChange={below => onChange({
...condition,
below: below ? String(below) : undefined,
})}
/>
<InputYaml label="Template" value={condition.value_template ?? ""} onChange={value_template => onChange({
...condition,
value_template
})} />
</>
}
return (
<>
<InputEntity
value={condition.entity_id}
multiple
onChange={(entity_id) =>
onChange({
...condition,
entity_id,
})
}
/>
<InputText
label="Attribute"
value={condition.attribute ?? ""}
onChange={(attribute) =>
onChange({
...condition,
attribute,
})
}
/>
<InputNumber
label="Above"
value={condition.above ? Number(condition.above) : undefined}
onChange={(above) =>
onChange({
...condition,
above: above ? String(above) : undefined,
})
}
/>
<InputNumber
label="Below"
value={condition.below ? Number(condition.below) : undefined}
onChange={(below) =>
onChange({
...condition,
below: below ? String(below) : undefined,
})
}
/>
<InputYaml
label="Template"
value={condition.value_template ?? ""}
onChange={(value_template) =>
onChange({
...condition,
value_template,
})
}
/>
</>
);
};
export const LogicViewer: Editor<LogicCondition> = ({
condition,
onChange,
}) => {
return <>
{condition.conditions.map((c, i) => {
return <ConditionNode
key={i}
condition={c}
displayMode={false}
{...genUpdateMethods(condition, onChange)(i)}
showDelete
/>
})}
</>
}
return (
<>
{condition.conditions.map((c, i) => {
return (
<ConditionNode
key={i}
condition={c}
displayMode={false}
{...genUpdateMethods(condition, onChange)(i)}
showDelete
/>
);
})}
</>
);
};
export const StateEditor: Editor<StateCondition> = ({
onChange,
condition,
}) => {
return <>
<InputEntity
value={condition.entity_id}
multiple
onChange={entity_id => onChange({
...condition,
entity_id
})}
/>
<InputText label="Attribute" value={condition.attribute ?? ""} onChange={attribute => onChange({
...condition,
attribute
})} />
<InputText
label="State"
value={String(condition.state)}
onChange={state => onChange({
...condition,
state,
})}
/>
<InputTime
label="For"
value={condition.for}
onChange={_for => onChange({
...condition,
for: _for,
})}
/>
</>
}
return (
<>
<InputEntity
value={condition.entity_id}
multiple
onChange={(entity_id) =>
onChange({
...condition,
entity_id,
})
}
/>
<InputText
label="Attribute"
value={condition.attribute ?? ""}
onChange={(attribute) =>
onChange({
...condition,
attribute,
})
}
/>
<InputText
label="State"
value={String(condition.state)}
onChange={(state) =>
onChange({
...condition,
state,
})
}
/>
<InputTime
label="For"
value={condition.for}
onChange={(_for) =>
onChange({
...condition,
for: _for,
})
}
/>
</>
);
};
export const TimeEditor: Editor<TimeCondition> = ({
onChange,
condition,
}) => {
return <>
<InputTime
label="After"
value={condition.after}
onChange={after => onChange({
...condition,
after,
})}
/>
<InputTime
label="Before"
value={condition.before}
onChange={before => onChange({
...condition,
before,
})}
/>
<b>Weekday not support for no, use yaml for now</b> {condition.weekday}
</>
}
export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
return (
<>
<InputTime
label="After"
value={condition.after}
onChange={(after) =>
onChange({
...condition,
after,
})
}
/>
<InputTime
label="Before"
value={condition.before}
onChange={(before) =>
onChange({
...condition,
before,
})
}
/>
<b>Weekday not support for no, use yaml for now</b> {condition.weekday}
</>
);
};
export const TriggerEditor: Editor<TriggerCondition> = ({
onChange,
condition,
}) => {
return <>
<InputText label="Trigger ID" value={condition.id} onChange={id => onChange({
...condition,
id
})} />
</>
}
return (
<>
<InputText
label="Trigger ID"
value={condition.id}
onChange={(id) =>
onChange({
...condition,
id,
})
}
/>
</>
);
};
export const ZoneEditor: Editor<ZoneCondition> = ({
onChange,
condition,
}) => {
return <>
<InputText label="Zone" value={condition.zone} onChange={zone => onChange({
...condition,
zone
})} />
<InputEntity
value={condition.entity_id}
multiple
onChange={entity_id => onChange({
...condition,
entity_id
})}
/>
<InputText
label="State"
value={String(condition.state)}
onChange={state => onChange({
...condition,
state,
})}
/>
</>
}
export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => {
return (
<>
<InputEntity
label="Zone"
value={condition.zone}
multiple={false}
onChange={(zone) =>
onChange({
...condition,
zone: zone ?? "",
})
}
restrictToDomain={["zone"]}
/>
<InputEntity
label="Entity with Location"
value={condition.entity_id}
multiple
onChange={(entity_id) =>
onChange({
...condition,
entity_id,
})
}
restrictToDomain={["person", "device_tracker"]}
/>
<InputText
label="State"
value={String(condition.state)}
onChange={(state) =>
onChange({
...condition,
state,
})
}
/>
</>
);
};
@@ -1,45 +1,53 @@
import { FC } from "react";
import { AutomationCondition, LogicCondition } from "types/automations/conditions";
import {
AutomationCondition,
LogicCondition,
} from "types/automations/conditions";
import { getDescriptionFromAutomationNode, Namer } from "utils/formatting";
import { ConditionNode } from "./ConditionNode";
import { genUpdateMethods } from "./nestedUpdater";
interface Viewer<C extends AutomationCondition> extends FC<{
condition: C;
namer: Namer;
onChange: (condition: C) => void;
}> { }
interface Viewer<C extends AutomationCondition>
extends FC<{
condition: C;
namer: Namer;
onChange: (condition: C) => void;
}> {}
export const getViewer = (condition: AutomationCondition): Viewer<any> => {
if (
(condition.condition === 'and') ||
(condition.condition === 'or') ||
(condition.condition === 'not')
condition.condition === "and" ||
condition.condition === "or" ||
condition.condition === "not"
) {
return LogicViewer
return LogicViewer;
}
return GenericViewer
}
return GenericViewer;
};
export const GenericViewer: Viewer<AutomationCondition> = ({
condition,
namer,
}) => {
return <>
{getDescriptionFromAutomationNode(condition, namer)}
</>
}
return <>{getDescriptionFromAutomationNode(condition, namer, true)}</>;
};
export const LogicViewer: Viewer<LogicCondition> = ({
condition,
onChange,
}) => {
return <>
{condition.conditions.map((c, i) => {
return <ConditionNode key={i} condition={c} displayMode
{...genUpdateMethods(condition, onChange)(i)}
/>
})}
</>
}
return (
<>
{condition.conditions.map((c, i) => {
return (
<ConditionNode
key={i}
condition={c}
displayMode
{...genUpdateMethods(condition, onChange)(i)}
/>
);
})}
</>
);
};
+161 -141
View File
@@ -1,12 +1,17 @@
import { FC, useState } from "react";
import ReactFlow, { Controls } from 'react-flow-renderer';
import ReactFlow, { Controls } from "react-flow-renderer";
import { AutomationSequenceNode } from "types/automations";
import { AutomationTrigger } from 'types/automations/triggers';
import { AutomationTrigger } from "types/automations/triggers";
import { triggerToFlow } from "./triggerConvertor";
import { DAGNode } from "./DAGNode";
import { DAGAutomationFlowDims, FlowData, ModalState, UpdateModalState } from './types';
import { DAGCircle } from './DAGCircle';
import {
DAGAutomationFlowDims,
FlowData,
ModalState,
UpdateModalState,
} from "./types";
import { DAGCircle } from "./DAGCircle";
import { sequenceToFlow } from "./sequenceConvertor";
import { makeSequenceUpdater } from "./updater";
import { NodeEditor } from "components/NodeEditor";
@@ -19,152 +24,167 @@ import { DAGErrorNode } from "./DAGErrorNode";
import { useHA } from "haService";
const nodeTypes = {
'dagnode': convertToFlowNode(DAGNode),
'errornode': convertToFlowNode(DAGErrorNode),
'dagcircle': DAGCircle,
}
dagnode: convertToFlowNode(DAGNode),
errornode: convertToFlowNode(DAGErrorNode),
dagcircle: DAGCircle,
};
const makeOnEditAutomationConditions = (
const makeOnEditAutomationConditions =
(
conditions: AutomationCondition[],
updateConditions: (c: AutomationCondition[]) => void,
openModal: UpdateModalState,
) => () => openModal({
single: false,
node: conditions,
allowedTypes: ['condition'],
update: c => updateConditions(c as any),
})
openModal: UpdateModalState
) =>
() =>
openModal({
single: false,
node: conditions,
allowedTypes: ["condition"],
update: (c) => updateConditions(c as any),
});
export interface DAGAutomationFlowProps {
className?: string;
trigger: AutomationTrigger[];
condition: AutomationCondition[];
sequence: AutomationSequenceNode[];
dims: DAGAutomationFlowDims;
onTriggerUpdate: (t: AutomationTrigger[]) => void;
onSequenceUpdate: (s: AutomationSequenceNode[]) => void;
onConditionUpdate: (s: AutomationCondition[]) => void;
className?: string;
trigger: AutomationTrigger[];
condition: AutomationCondition[];
sequence: AutomationSequenceNode[];
dims: DAGAutomationFlowDims;
onTriggerUpdate: (t: AutomationTrigger[]) => void;
onSequenceUpdate: (s: AutomationSequenceNode[]) => void;
onConditionUpdate: (s: AutomationCondition[]) => void;
}
export const DAGAutomationFlow: FC<DAGAutomationFlowProps> = ({
className,
trigger,
condition,
sequence,
onTriggerUpdate,
onSequenceUpdate,
onConditionUpdate,
dims,
className,
trigger,
condition,
sequence,
onTriggerUpdate,
onSequenceUpdate,
onConditionUpdate,
dims,
}) => {
// state
const [modalState, setModalState] = useState<ModalState | null>(null);
const { namer, } = useHA();
// modal
let modalBody = <></>
if (modalState) {
if (modalState.single) {
modalBody = <NodeEditor
node={modalState.node}
isErrored={modalState.isError}
onClose={() => setModalState(null)}
onSave={n => {
modalState.update(n as any);
setModalState(null);
}}
allowedTypes={modalState.allowedTypes}
saveBtnCreateText={modalState.saveBtnCreateText}
/>
} else {
modalBody = <MultiNodeEditor
sequence={modalState.node}
onClose={() => setModalState(null)}
onSave={(n) => modalState.update(n as any)}
allowedTypes={['condition']}
/>
}
// state
const [modalState, setModalState] = useState<ModalState | null>(null);
const { namer } = useHA();
// modal
let modalBody = <></>;
if (modalState) {
if (modalState.single) {
modalBody = (
<NodeEditor
node={modalState.node}
isErrored={modalState.isError}
onClose={() => setModalState(null)}
onSave={(n) => {
modalState.update(n as any);
setModalState(null);
}}
allowedTypes={modalState.allowedTypes}
saveBtnCreateText={modalState.saveBtnCreateText}
/>
);
} else {
modalBody = (
<MultiNodeEditor
sequence={modalState.node}
onClose={() => setModalState(null)}
onSave={(n) => modalState.update(n as any)}
allowedTypes={["condition"]}
/>
);
}
}
// convert automation to flow data
const condPoint = makeConditionPoint(
'c', dims.flipped ? {
y: dims.padding.y + dims.nodeHeight * dims.distanceFactor,
x: dims.padding.x + dims.nodeWidth * 0.25
} : {
x: dims.padding.x + dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y + dims.nodeHeight * 0.25
}, dims, condition.length, makeOnEditAutomationConditions(
condition,
onConditionUpdate,
setModalState,
));
const flowData: FlowData = {
nodes: [condPoint],
edges: [],
}
triggerToFlow(flowData, trigger, condPoint.id, dims, {
namer,
onAdd: () => onTriggerUpdate([
...trigger, {
platform: 'event',
event_type: '',
}
]),
onDelete: i => onTriggerUpdate([
...trigger.slice(0, i),
...trigger.slice(i + 1)
]),
onEdit: i => setModalState({
single: true,
node: trigger[i],
update: t => onTriggerUpdate([
...trigger.slice(0, i),
t,
...trigger.slice(i + 1)
]),
allowedTypes: ['trigger'],
})
});
sequenceToFlow(
flowData,
sequence,
condPoint.id,
{
...dims, padding: dims.flipped ? {
y: condPoint.position.y - dims.nodeHeight - dims.conditionHeight,
x: dims.padding.x,
} : {
x: condPoint.position.x - dims.nodeWidth - dims.conditionWidth,
y: dims.padding.y,
}
// convert automation to flow data
const condPoint = makeConditionPoint(
"c",
dims.flipped
? {
y: dims.padding.y + dims.nodeHeight * dims.distanceFactor,
x: dims.padding.x + dims.nodeWidth * 0.25,
}
: {
x: dims.padding.x + dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y + dims.nodeHeight * 0.25,
},
namer,
makeSequenceUpdater(sequence, onSequenceUpdate, setModalState),
);
// this fixes some strange edge drawing issue
flowData.edges = flowData.edges.map(e => ({
...e,
"source": `${e.source}-${dims.flipped}`,
"target": `${e.target}-${dims.flipped}`,
}))
flowData.nodes = flowData.nodes.map(n => ({
...n,
id: `${n.id}-${dims.flipped}`
}))
// render
return <>
<Modal open={!!modalState}>
{modalBody}
</Modal>
<ReactFlow
className={className}
nodeTypes={nodeTypes}
snapToGrid
onlyRenderVisibleElements
nodesConnectable={false}
nodesDraggable={false}
{...flowData}
>
<Controls />
</ReactFlow>
</>;
}
dims,
condition.length,
makeOnEditAutomationConditions(condition, onConditionUpdate, setModalState)
);
const flowData: FlowData = {
nodes: [condPoint],
edges: [],
};
triggerToFlow(flowData, trigger, condPoint.id, dims, {
namer,
onAdd: () =>
setModalState({
single: true,
saveBtnCreateText: true,
node: {
platform: "device",
},
update: (n) => {
onTriggerUpdate([...trigger, n]);
},
allowedTypes: ["trigger"],
}),
onDelete: (i) =>
onTriggerUpdate([...trigger.slice(0, i), ...trigger.slice(i + 1)]),
onEdit: (i) =>
setModalState({
single: true,
node: trigger[i],
update: (t) =>
onTriggerUpdate([...trigger.slice(0, i), t, ...trigger.slice(i + 1)]),
allowedTypes: ["trigger"],
}),
});
sequenceToFlow(
flowData,
sequence,
condPoint.id,
{
...dims,
padding: dims.flipped
? {
y: condPoint.position.y - dims.nodeHeight - dims.conditionHeight,
x: dims.padding.x,
}
: {
x: condPoint.position.x - dims.nodeWidth - dims.conditionWidth,
y: dims.padding.y,
},
},
namer,
makeSequenceUpdater(sequence, onSequenceUpdate, setModalState)
);
// this fixes some strange edge drawing issue
flowData.edges = flowData.edges.map((e) => ({
...e,
source: `${e.source}-${dims.flipped}`,
target: `${e.target}-${dims.flipped}`,
}));
flowData.nodes = flowData.nodes.map((n) => ({
...n,
id: `${n.id}-${dims.flipped}`,
}));
// render
return (
<>
<Modal open={!!modalState}>{modalBody}</Modal>
<ReactFlow
className={className}
nodeTypes={nodeTypes}
snapToGrid
onlyRenderVisibleElements
nodesConnectable={false}
nodesDraggable={false}
{...flowData}
>
<Controls />
</ReactFlow>
</>
);
};
+341 -273
View File
@@ -1,312 +1,380 @@
import { AutomationSequenceNode } from 'types/automations';
import { DAGAutomationFlowDims, FlowData } from './types';
import { getDescriptionFromAutomationNode, Namer } from 'utils/formatting';
import { XYPosition } from 'react-flow-renderer';
import { ChooseAction } from 'types/automations/actions';
import { makeFlowCircle } from './DAGCircle';
import { createOnRemoveForChooseNode, SequenceUpdater } from './updater';
import { getNodeType } from 'utils/automations';
import { makeAddButton, makeConditionPoint } from './flowDataMods';
import { AutomationSequenceNode } from "types/automations";
import { DAGAutomationFlowDims, FlowData } from "./types";
import { getDescriptionFromAutomationNode, Namer } from "utils/formatting";
import { XYPosition } from "react-flow-renderer";
import { ChooseAction } from "types/automations/actions";
import { makeFlowCircle } from "./DAGCircle";
import { createOnRemoveForChooseNode, SequenceUpdater } from "./updater";
import { getNodeType } from "utils/automations";
import { makeAddButton, makeConditionPoint } from "./flowDataMods";
export const sequenceToFlow = (
flowData: FlowData,
sequence: AutomationSequenceNode[],
fromPoint: string,
dims: DAGAutomationFlowDims,
namer: Namer,
updater: SequenceUpdater,
prefix: string = "",
flowData: FlowData,
sequence: AutomationSequenceNode[],
fromPoint: string,
dims: DAGAutomationFlowDims,
namer: Namer,
updater: SequenceUpdater,
prefix: string = ""
) => {
let lastPointId = fromPoint;
let lasPos: XYPosition | null = null;
// sequence
for (let i = 0; i < sequence.length; i++) {
const node = sequence[i];
const nodeId = `${prefix}n-${i}`;
let position: XYPosition;
if (lasPos) {
position = dims.flipped ? {
y: lasPos.y + dims.nodeHeight * dims.distanceFactor,
x: dims.padding.x
} : {
x: lasPos.x + dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y
}
} else {
position = dims.flipped ? {
y: dims.padding.y + dims.nodeHeight * dims.distanceFactor * (i + 2),
x: dims.padding.x
} : {
x: dims.padding.x + dims.nodeWidth * dims.distanceFactor * (i + 2),
y: dims.padding.y
};
}
// draw node
if (getNodeType(node) === 'action') {
if ('choose' in node) {
try {
const out = addChooseNode(node, position, nodeId, dims, namer, updater, i);
position = out.lastPos
flowData = mergeFlowDatas(flowData, out.flowData);
} catch (err) {
console.error(err)
addErrorNode(flowData, nodeId, position, dims, err, updater.makeOnEditForBadNode(i));
}
} else {
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
namer,
});
}
} else {
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
namer,
});
}
addEdge(flowData, lastPointId, nodeId, false)
lastPointId = nodeId;
lasPos = position;
let lastPointId = fromPoint;
let lasPos: XYPosition | null = null;
// sequence
for (let i = 0; i < sequence.length; i++) {
const node = sequence[i];
const nodeId = `${prefix}n-${i}`;
let position: XYPosition;
if (lasPos) {
position = dims.flipped
? {
y: lasPos.y + dims.nodeHeight * dims.distanceFactor,
x: dims.padding.x,
}
: {
x: lasPos.x + dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y,
};
} else {
position = dims.flipped
? {
y: dims.padding.y + dims.nodeHeight * dims.distanceFactor * (i + 2),
x: dims.padding.x,
}
: {
x: dims.padding.x + dims.nodeWidth * dims.distanceFactor * (i + 2),
y: dims.padding.y,
};
}
// draw node
if (getNodeType(node) === "action") {
if ("choose" in node) {
try {
const out = addChooseNode(
node,
position,
nodeId,
dims,
namer,
updater,
i
);
position = out.lastPos;
flowData = mergeFlowDatas(flowData, out.flowData);
} catch (err) {
console.error(err);
addErrorNode(
flowData,
nodeId,
position,
dims,
err,
updater.makeOnEditForBadNode(i)
);
}
} else {
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
namer,
});
}
} else {
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
namer,
});
}
addEdge(flowData, lastPointId, nodeId, false);
lastPointId = nodeId;
lasPos = position;
}
// add button
const addCircle = makeAddButton(
`${prefix}-+`,
dims.flipped ? {
y: (
lasPos === null ?
dims.padding.y + dims.nodeHeight * dims.distanceFactor * (sequence.length + 1) :
lasPos.y
) + dims.nodeHeight * dims.distanceFactor,
x: dims.padding.x + dims.circleSize * 1.5
} : {
x: (
lasPos === null ?
dims.padding.x + dims.nodeWidth * dims.distanceFactor * (sequence.length + 1) :
lasPos.x
) + dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y + dims.circleSize / 4
// add button
const addCircle = makeAddButton(
`${prefix}-+`,
dims.flipped
? {
y:
(lasPos === null
? dims.padding.y +
dims.nodeHeight * dims.distanceFactor * (sequence.length + 1)
: lasPos.y) +
dims.nodeHeight * dims.distanceFactor,
x: dims.padding.x + dims.circleSize * 1.5,
}
: {
x:
(lasPos === null
? dims.padding.x +
dims.nodeWidth * dims.distanceFactor * (sequence.length + 1)
: lasPos.x) +
dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y + dims.circleSize / 4,
},
dims,
updater.addNode,
false,
)
flowData.nodes.push(addCircle)
addEdge(flowData, lastPointId, addCircle.id, false)
return {
position: lasPos,
pointId: lastPointId,
};
}
dims,
updater.addNode,
false
);
flowData.nodes.push(addCircle);
addEdge(flowData, lastPointId, addCircle.id, false);
return {
position: lasPos,
pointId: lastPointId,
};
};
const xyApply = (p1: XYPosition, p2: XYPosition, fcn: (a: number, b: number) => number): XYPosition => ({
x: fcn(p1.x, p2.x), y: fcn(p1.y, p2.y)
})
const xyApply = (
p1: XYPosition,
p2: XYPosition,
fcn: (a: number, b: number) => number
): XYPosition => ({
x: fcn(p1.x, p2.x),
y: fcn(p1.y, p2.y),
});
const addEdge = (flowData: FlowData, source: string, target: string, animated: boolean = false) => flowData.edges.push({
const addEdge = (
flowData: FlowData,
source: string,
target: string,
animated: boolean = false
) =>
flowData.edges.push({
id: `${source}-${target}`,
source,
target,
animated,
})
});
const addSingleNode = (
flowData: FlowData,
node: AutomationSequenceNode,
position: XYPosition,
nodeId: string,
{
flipped,
nodeHeight,
nodeWidth,
}: DAGAutomationFlowDims,
opts: {
onEditClick: () => void;
onXClick: () => void;
namer: Namer;
}
) => flowData.nodes.push({
flowData: FlowData,
node: AutomationSequenceNode,
position: XYPosition,
nodeId: string,
{ flipped, nodeHeight, nodeWidth }: DAGAutomationFlowDims,
opts: {
onEditClick: () => void;
onXClick: () => void;
namer: Namer;
}
) =>
flowData.nodes.push({
id: nodeId,
type: 'dagnode',
type: "dagnode",
data: {
label: getDescriptionFromAutomationNode(node, opts.namer),
height: nodeHeight,
width: nodeWidth,
color: getNodeType(node) === 'action' ? 'green' : 'blue',
hasInput: true,
flipped,
...opts,
label: getDescriptionFromAutomationNode(node, opts.namer, true),
height: nodeHeight,
width: nodeWidth,
color: getNodeType(node) === "action" ? "green" : "blue",
hasInput: true,
flipped,
...opts,
},
position,
});
});
const addErrorNode = (
flowData: FlowData,
nodeId: string,
position: XYPosition,
{
nodeHeight,
nodeWidth,
}: DAGAutomationFlowDims,
error: any,
onEdit: () => void,
hasInput: boolean = true,
) => flowData.nodes.push({
flowData: FlowData,
nodeId: string,
position: XYPosition,
{ nodeHeight, nodeWidth }: DAGAutomationFlowDims,
error: any,
onEdit: () => void,
hasInput: boolean = true
) =>
flowData.nodes.push({
id: nodeId,
type: 'errornode',
type: "errornode",
position,
data: {
height: nodeHeight,
width: nodeWidth,
hasInput,
onEdit,
error,
}
})
height: nodeHeight,
width: nodeWidth,
hasInput,
onEdit,
error,
},
});
const addChooseNode = (
node: ChooseAction,
position: XYPosition,
nodeId: string,
dims: DAGAutomationFlowDims,
namer: Namer,
updater: SequenceUpdater,
i: number,
node: ChooseAction,
position: XYPosition,
nodeId: string,
dims: DAGAutomationFlowDims,
namer: Namer,
updater: SequenceUpdater,
i: number
) => {
const flowData: FlowData = {
nodes: [],
edges: [],
};
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
namer,
});
let lastPos: XYPosition = position;
// conditions
node.choose.forEach(({ sequence, conditions }, j) => {
const sequenceId = `${nodeId}.${j}`;
// edit/delete circle
const circle = makeFlowCircle(`${sequenceId}>delete`, dims.flipped ? {
const flowData: FlowData = {
nodes: [],
edges: [],
};
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i),
namer,
});
let lastPos: XYPosition = position;
// conditions
node.choose.forEach(({ sequence, conditions }, j) => {
const sequenceId = `${nodeId}.${j}`;
// edit/delete circle
const circle = makeFlowCircle(
`${sequenceId}>delete`,
dims.flipped
? {
y: position.y + dims.nodeHeight * dims.distanceFactor,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor,
} : {
}
: {
x: position.x + dims.nodeWidth * dims.distanceFactor,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor,
}, {
flipped: dims.flipped,
size: dims.circleSize,
onRemove: createOnRemoveForChooseNode(
node,
d => updater.updateNode(i, d),
j,
),
})
flowData.nodes.push(circle)
addEdge(flowData, nodeId, circle.id, true)
const condNode = makeConditionPoint(
`${sequenceId}>cond`,
dims.flipped ? {
y: circle.position.y + dims.circleSize * dims.distanceFactor,
x: circle.position.x - dims.circleSize,
} : {
x: circle.position.x + dims.circleSize * dims.distanceFactor,
y: circle.position.y + dims.circleSize / 8,
},
dims,
conditions.length,
updater.makeOnEditConditionsForChooseNode(i, j)
);
flowData.nodes.push(condNode)
addEdge(flowData, circle.id, condNode.id, true)
// actual sub sequence
const lastPoint = sequenceToFlow(flowData, sequence, condNode.id, {
...dims,
padding: dims.flipped ? {
y: condNode.position.y - dims.nodeHeight * dims.distanceFactor,
x: condNode.position.x - dims.conditionHeight / 2,
} : {
x: condNode.position.x - (dims.nodeWidth + dims.conditionWidth),
y: condNode.position.y - dims.conditionHeight / 2,
},
}, namer, updater.makeChildUpdaterForChooseAction(i, j), `${sequenceId}.`);
if (lastPoint.position) {
lastPos = xyApply(lastPos, lastPoint.position, Math.max)
} else {
lastPos = xyApply(lastPos, dims.flipped ? {
y: lastPos.y,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor
} : {
x: lastPos.x,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor
}, Math.max)
}
})
const totalChildren = node.choose.length;
// add button
const addCirlce = makeAddButton(
`${nodeId}>add`,
dims.flipped ? {
y: position.y + dims.nodeHeight * dims.distanceFactor,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor,
} : {
x: position.x + dims.nodeWidth * dims.distanceFactor,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor,
},
dims,
() => updater.updateNode(i, {
...node,
choose: [
...node.choose,
{
sequence: [],
conditions: [],
}
]
}),
false,
},
{
flipped: dims.flipped,
size: dims.circleSize,
onRemove: createOnRemoveForChooseNode(
node,
(d) => updater.updateNode(i, d),
j
),
}
);
flowData.nodes.push(addCirlce)
addEdge(flowData, nodeId, addCirlce.id, true)
flowData.nodes.push(circle);
addEdge(flowData, nodeId, circle.id, true);
const condNode = makeConditionPoint(
`${sequenceId}>cond`,
dims.flipped
? {
y: circle.position.y + dims.circleSize * dims.distanceFactor,
x: circle.position.x - dims.circleSize,
}
: {
x: circle.position.x + dims.circleSize * dims.distanceFactor,
y: circle.position.y + dims.circleSize / 8,
},
dims,
conditions.length,
updater.makeOnEditConditionsForChooseNode(i, j)
);
flowData.nodes.push(condNode);
addEdge(flowData, circle.id, condNode.id, true);
// else
const elseCircle = makeFlowCircle(`${nodeId}>else`, dims.flipped ? {
y: position.y + dims.nodeHeight * dims.distanceFactor,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor * 2,
} : {
x: position.x + dims.nodeWidth * dims.distanceFactor,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor * 2,
}, { size: dims.circleSize, flipped: dims.flipped })
flowData.nodes.push(elseCircle)
addEdge(flowData, nodeId, elseCircle.id, true)
const lastPoint = sequenceToFlow(flowData, node.default ?? [], elseCircle.id, {
// actual sub sequence
const lastPoint = sequenceToFlow(
flowData,
sequence,
condNode.id,
{
...dims,
padding: dims.flipped ? {
padding: dims.flipped
? {
y: condNode.position.y - dims.nodeHeight * dims.distanceFactor,
x: condNode.position.x - dims.conditionHeight / 2,
}
: {
x: condNode.position.x - (dims.nodeWidth + dims.conditionWidth),
y: condNode.position.y - dims.conditionHeight / 2,
},
},
namer,
updater.makeChildUpdaterForChooseAction(i, j),
`${sequenceId}.`
);
if (lastPoint.position) {
lastPos = xyApply(lastPos, lastPoint.position, Math.max);
} else {
lastPos = xyApply(
lastPos,
dims.flipped
? {
y: lastPos.y,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor,
}
: {
x: lastPos.x,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor,
},
Math.max
);
}
});
const totalChildren = node.choose.length;
// add button
const addCirlce = makeAddButton(
`${nodeId}>add`,
dims.flipped
? {
y: position.y + dims.nodeHeight * dims.distanceFactor,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor,
}
: {
x: position.x + dims.nodeWidth * dims.distanceFactor,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor,
},
dims,
() =>
updater.updateNode(i, {
...node,
choose: [
...node.choose,
{
sequence: [],
conditions: [],
},
],
}),
false
);
flowData.nodes.push(addCirlce);
addEdge(flowData, nodeId, addCirlce.id, true);
// else
const elseCircle = makeFlowCircle(
`${nodeId}>else`,
dims.flipped
? {
y: position.y + dims.nodeHeight * dims.distanceFactor,
x: lastPos.x + dims.nodeWidth * dims.distanceFactor * 2,
}
: {
x: position.x + dims.nodeWidth * dims.distanceFactor,
y: lastPos.y + dims.nodeHeight * dims.distanceFactor * 2,
},
{ size: dims.circleSize, flipped: dims.flipped }
);
flowData.nodes.push(elseCircle);
addEdge(flowData, nodeId, elseCircle.id, true);
const lastPoint = sequenceToFlow(
flowData,
node.default ?? [],
elseCircle.id,
{
...dims,
padding: dims.flipped
? {
y: position.y,
x: elseCircle.position.x - 1.4 * dims.circleSize,
} : {
}
: {
x: position.x - dims.nodeWidth,
y: elseCircle.position.y - dims.circleSize / 4,
},
}, namer, updater.makeChildUpdaterForChooseAction(i, null), `${nodeId}.${totalChildren}.`)
if (lastPoint.position) {
lastPos = xyApply(lastPos, lastPoint.position, Math.max)
} else {
lastPos = xyApply(lastPos, elseCircle.position, Math.max)
}
return { lastPos, flowData }
}
},
},
namer,
updater.makeChildUpdaterForChooseAction(i, null),
`${nodeId}.${totalChildren}.`
);
if (lastPoint.position) {
lastPos = xyApply(lastPos, lastPoint.position, Math.max);
} else {
lastPos = xyApply(lastPos, elseCircle.position, Math.max);
}
return { lastPos, flowData };
};
export const mergeFlowDatas = (fd1: FlowData, fd2: FlowData): FlowData => {
fd1.edges = fd1.edges.concat(fd2.edges);
fd1.nodes = fd1.nodes.concat(fd2.nodes);
return fd1
}
fd1.edges = fd1.edges.concat(fd2.edges);
fd1.nodes = fd1.nodes.concat(fd2.nodes);
return fd1;
};
@@ -1,65 +1,74 @@
import { AutomationTrigger } from 'types/automations/triggers';
import { DAGAutomationFlowDims, FlowData, TriggerMakerOptions } from './types';
import { makeAddButton } from './flowDataMods';
import { getDescriptionFromAutomationNode } from 'utils/formatting';
import { AutomationTrigger } from "types/automations/triggers";
import { DAGAutomationFlowDims, FlowData, TriggerMakerOptions } from "./types";
import { makeAddButton } from "./flowDataMods";
import { getDescriptionFromAutomationNode } from "utils/formatting";
export const triggerToFlow = (
flowData: FlowData,
trigger: AutomationTrigger[],
toPoint: string,
dims: DAGAutomationFlowDims,
opts: TriggerMakerOptions,
flowData: FlowData,
trigger: AutomationTrigger[],
toPoint: string,
dims: DAGAutomationFlowDims,
opts: TriggerMakerOptions
) => {
const {
distanceFactor,
nodeHeight,
nodeWidth,
padding,
conditionHeight,
circleSize,
const {
distanceFactor,
nodeHeight,
nodeWidth,
padding,
conditionHeight,
circleSize,
flipped,
} = dims;
// convert all triggers to dag nodes
trigger.forEach((t, i) => {
const flowId = `t-${i}`;
flowData.nodes.push({
id: flowId,
type: "dagnode",
data: {
label: getDescriptionFromAutomationNode(t, opts.namer, true),
height: nodeHeight,
width: nodeWidth,
flipped,
} = dims;
// convert all triggers to dag nodes
trigger.forEach((t, i) => {
const flowId = `t-${i}`;
flowData.nodes.push({
id: flowId,
type: 'dagnode',
data: {
label: getDescriptionFromAutomationNode(t, opts.namer),
height: nodeHeight,
width: nodeWidth,
flipped,
color: 'red',
onEditClick: () => opts.onEdit(i),
onXClick: () => opts.onDelete(i),
},
position: flipped ? {
y: padding.y,
x: padding.x + nodeWidth * distanceFactor * i
} : {
x: padding.x,
y: padding.y + nodeHeight * distanceFactor * i
}
})
flowData.edges.push({
id: `e(${flowId})-(${toPoint})`,
source: flowId,
target: toPoint,
})
color: "red",
onEditClick: () => opts.onEdit(i),
onXClick: () => opts.onDelete(i),
},
position: flipped
? {
y: padding.y,
x: padding.x + nodeWidth * distanceFactor * i,
}
: {
x: padding.x,
y: padding.y + nodeHeight * distanceFactor * i,
},
});
flowData.edges.push({
id: `e(${flowId})-(${toPoint})`,
source: flowId,
target: toPoint,
});
});
// create a 'add button'
flowData.nodes.push(makeAddButton(
'trigger-add',
flipped ? {
// create a 'add button'
flowData.nodes.push(
makeAddButton(
"trigger-add",
flipped
? {
y: padding.y + circleSize / 4,
x: padding.x + nodeWidth * distanceFactor * trigger.length,
} : {
}
: {
x: padding.x + nodeWidth * 0.4,
y: padding.y + conditionHeight / 2 + nodeHeight * distanceFactor * trigger.length,
},
dims,
opts.onAdd
))
}
y:
padding.y +
conditionHeight / 2 +
nodeHeight * distanceFactor * trigger.length,
},
dims,
opts.onAdd
)
);
};
+73 -86
View File
@@ -2,39 +2,32 @@ import { AutomationSequenceNode } from "types/automations";
import { ChooseAction } from "types/automations/actions";
import { AutomationCondition } from "types/automations/conditions";
import { UpdateModalState } from "./types";
import { getNodeType } from '../../utils/automations';
import { getNodeType } from "../../utils/automations";
export type SequenceUpdater = ReturnType<typeof makeSequenceUpdater>;
export const makeSequenceUpdater = (
sequence: AutomationSequenceNode[],
onChange: (s: AutomationSequenceNode[]) => void,
openModal: UpdateModalState,
openModal: UpdateModalState
) => ({
sequence,
onChange,
removeNode(i: number) {
return onChange([
...sequence.slice(0, i),
...sequence.slice(i + 1),
])
return onChange([...sequence.slice(0, i), ...sequence.slice(i + 1)]);
},
addNode() {
return openModal({
single: true,
saveBtnCreateText: true,
node: {
choose: [],
default: [],
device_id: "",
},
update: n => {
onChange([
...sequence,
n,
])
update: (n) => {
onChange([...sequence, n]);
},
allowedTypes: ['action', 'condition']
})
allowedTypes: ["action", "condition"],
});
},
updateNode(i: number, node: AutomationSequenceNode) {
if (JSON.stringify(node) !== JSON.stringify(sequence[i])) {
@@ -42,7 +35,7 @@ export const makeSequenceUpdater = (
...sequence.slice(0, i),
node,
...sequence.slice(i + 1),
])
]);
}
},
updateChooseActionData(i: number, data: ChooseAction) {
@@ -50,96 +43,90 @@ export const makeSequenceUpdater = (
return this.updateNode(i, {
...node,
...data,
})
});
},
makeChildUpdaterForChooseAction(i: number, j: number | null) {
const node = sequence[i];
if ('choose' in node) {
if ("choose" in node) {
if (j !== null) {
return makeSequenceUpdater(
node.choose[j].sequence,
seq => this.updateNode(i, {
...node,
choose: [
...node.choose.slice(0, j),
{
...node.choose[j],
sequence: seq,
},
...node.choose.slice(j + 1),
]
}),
openModal,
)
(seq) =>
this.updateNode(i, {
...node,
choose: [
...node.choose.slice(0, j),
{
...node.choose[j],
sequence: seq,
},
...node.choose.slice(j + 1),
],
}),
openModal
);
} else {
return makeSequenceUpdater(
node.default ?? [],
seq => this.updateNode(i, {
...node,
default: seq
}),
openModal,
)
(seq) =>
this.updateNode(i, {
...node,
default: seq,
}),
openModal
);
}
}
throw new Error(`Cannot create sub-updater for ${node}`)
throw new Error(`Cannot create sub-updater for ${node}`);
},
makeOnModalOpenForNode(
i: number,
node: AutomationSequenceNode,
) {
return () => openModal({
single: true,
node,
allowedTypes: ['action', 'condition'],
update: n => this.updateNode(i, n),
})
makeOnModalOpenForNode(i: number, node: AutomationSequenceNode) {
return () =>
openModal({
single: true,
node,
allowedTypes: ["action", "condition"],
update: (n) => this.updateNode(i, n),
});
},
makeOnEditConditionsForChooseNode(
i: number,
j: number,
) {
makeOnEditConditionsForChooseNode(i: number, j: number) {
return () => {
const node = sequence[i] as ChooseAction;
return openModal({
single: false,
node: node.choose[j].conditions,
allowedTypes: ['condition'],
update: conditions => this.updateNode(i, {
...node,
choose: [
...node.choose.slice(0, j),
{
sequence: node.choose[j].sequence,
conditions: conditions as AutomationCondition[],
},
...node.choose.slice(j + 1),
]
}),
})
}
allowedTypes: ["condition"],
update: (conditions) =>
this.updateNode(i, {
...node,
choose: [
...node.choose.slice(0, j),
{
sequence: node.choose[j].sequence,
conditions: conditions as AutomationCondition[],
},
...node.choose.slice(j + 1),
],
}),
});
};
},
makeOnEditForBadNode(i: number) {
const node = sequence[i];
return () => openModal({
single: true,
isError: true,
node,
allowedTypes: [getNodeType(node)],
update: n => this.updateNode(i, n),
})
}
return () =>
openModal({
single: true,
isError: true,
node,
allowedTypes: [getNodeType(node)],
update: (n) => this.updateNode(i, n),
});
},
});
export const createOnRemoveForChooseNode = (
action: ChooseAction,
update: (data: ChooseAction) => void,
j: number
) => () => update({
...action,
choose: [
...action.choose.slice(0, j),
...action.choose.slice(j + 1),
]
})
export const createOnRemoveForChooseNode =
(action: ChooseAction, update: (data: ChooseAction) => void, j: number) =>
() =>
update({
...action,
choose: [...action.choose.slice(0, j), ...action.choose.slice(j + 1)],
});
@@ -0,0 +1,92 @@
import {
BaseOption,
InputAutoComplete,
} from "components/Inputs/InputAutoComplete";
import { InputDevice } from "components/Inputs/InputDevice";
import { InputDeviceCapabilties } from "components/Inputs/InputDeviceCapabilties";
import { InputEntity } from "components/Inputs/InputEntities";
import { cleanUpUndefined } from "components/NodeEditor/OptionManager/OptionManager";
import { DeviceBaseType, DeviceTypeCapability } from "haService/types";
import { AutomationDeviceState } from "types/automations/common";
export type DeviceEditorProps<DBT extends DeviceBaseType> = {
type: "action" | "condition" | "trigger";
state: Partial<AutomationDeviceState>;
setState: (n: Partial<AutomationDeviceState & Record<string, any>>) => void;
options: Record<string, BaseOption<{ data: DBT[] }>>;
caps: Partial<DeviceTypeCapability>;
};
export function DeviceEditor<DBT extends DeviceBaseType>({
type,
state,
setState,
caps,
options,
}: DeviceEditorProps<DBT>) {
// aliases
const update = (upd: Partial<AutomationDeviceState & Record<string, any>>) =>
setState(
cleanUpUndefined({
...state,
...upd,
})
);
const actionId = (state.type ?? "") + (state.subtype ?? "");
const entities = ((options[actionId] ?? {}).data ?? [])
.map(({ entity_id }) => entity_id)
.filter((x) => !!x) as string[];
// render
return (
<>
<InputDevice
key="devices"
label="Device"
value={state.device_id ?? ""}
onChange={(device_id) => setState({ device_id: device_id ?? "" })}
/>
<InputAutoComplete
key="action"
label="Action"
multiple={false}
value={actionId}
options={Object.keys(options).map((k) => options[k])}
disabled={Object.keys(options).length === 0}
onChange={(key) => {
if (key) {
const opt = options[key].data[0];
const updateObj: any = { ...opt };
delete updateObj["metadata"];
setState(updateObj);
} else {
setState({
device_id: state.device_id,
});
}
}}
/>
{entities.length > 0 && (
<InputEntity
key={"entities" + state.device_id}
label="Entity"
value={state.entity_id ?? ""}
multiple={false}
onChange={(entity_id) =>
update({ entity_id: entity_id ?? undefined })
}
preSelectedEntityIds={entities}
/>
)}
{caps?.extra_fields && (
<InputDeviceCapabilties
key="caps"
state={state}
setState={setState}
defn={caps.extra_fields}
/>
)}
{Object.keys(options).length + entities.length === 0 && (
<>This device has no {type}s.</>
)}
</>
);
}
@@ -0,0 +1,6 @@
.MuiButtonBase-root.icon-button[type="button"] {
border-width: 1px;
border-style: solid;
max-width: 1.5em;
max-height: 1.5em;
}
+23 -29
View File
@@ -1,30 +1,24 @@
import { FC } from 'react';
import { IconBaseProps } from './base';
import { createAppUseStyles } from 'styles/theme';
import "./ButtonIcons.css";
import { FC, ReactNode } from "react";
import MuiIconButton, { IconButtonTypeMap } from "@mui/material/IconButton";
export interface ButtonIconStyleProps {
}
export interface ButtonIconProps extends IconBaseProps, ButtonIconStyleProps {
Icon: FC<IconBaseProps>;
}
const useButtonIconStyles = createAppUseStyles(theme => ({
buttonIcon: {
borderRadius: "100%",
borderWidth: 1,
borderStyle: "groove",
padding: "0.25em",
"&:hover": {
backgroundColor: theme.secondaryAccent,
cursor: 'pointer',
}
}
}))
export const ButtonIcon: FC<ButtonIconProps> = ({
Icon,
className,
...props
}) => <Icon
className={`${useButtonIconStyles({}).classes.buttonIcon} ${className}`} {...props}
/>
export const ButtonIcon: FC<{
icon: ReactNode;
onClick?: () => void;
className?: string;
title?: string;
disabled?: boolean;
color?: IconButtonTypeMap["props"]["color"];
}> = (props) => {
return (
<MuiIconButton
className={["icon-button", props.className ?? ""].join(" ")}
onClick={props.onClick}
title={props.title}
color={props.color}
disabled={props.disabled}
>
{props.icon}
</MuiIconButton>
);
};
+33 -24
View File
@@ -1,41 +1,50 @@
import { ComponentStory } from "@storybook/react";
import { IconBase } from "./base";
import { PencilIcon, CheckMarkIcon, TrashIcon, InfoIcon, ArrowIcon, AddIcon, ZoomIcon, GearIcon } from ".";
import {
PencilIcon,
CheckMarkIcon,
TrashIcon,
InfoIcon,
ArrowIcon,
AddIcon,
ZoomIcon,
GearIcon,
} from ".";
import { ButtonIcon } from "./ButtonIcons";
import { Page } from "components/Page";
export default {
title: 'Icons',
title: "Icons",
component: IconBase,
};
export const IconList: ComponentStory<typeof IconBase> = (args) => {
return <Page>
<PencilIcon {...args} />
<CheckMarkIcon {...args} />
<AddIcon {...args} />
<TrashIcon {...args} />
<InfoIcon {...args} />
<ZoomIcon {...args} />
<GearIcon {...args} />
</Page>
}
return (
<Page>
<PencilIcon {...args} />
<CheckMarkIcon {...args} />
<AddIcon {...args} />
<TrashIcon {...args} />
<InfoIcon {...args} />
<ZoomIcon {...args} />
<GearIcon {...args} />
</Page>
);
};
IconList.args = {
size: 2,
color: 'red'
}
color: "red",
};
export const ButtonIconExample: ComponentStory<typeof IconBase> = (args) => {
return <Page>
<ButtonIcon {...args} Icon={ArrowIcon} />
</Page>
}
return (
<Page>
<ButtonIcon icon={<ArrowIcon {...args} />} />
</Page>
);
};
ButtonIconExample.args = {
size: 2,
color: 'red'
}
color: "red",
};
+20 -6
View File
@@ -1,7 +1,21 @@
import { ButtonHTMLAttributes, FC } from "react";
import { useButtonStyles } from "./styles";
import { FC, ReactNode } from "react";
import MuiButton from "@mui/material/Button";
export const Button: FC<ButtonHTMLAttributes<HTMLButtonElement>> = props => {
const { classes } = useButtonStyles({});
return <button {...props} className={`${classes.input} ${props.className ?? ''}`} />
}
export const Button: FC<{
className?: string;
title?: string;
disabled?: boolean;
children?: ReactNode;
onClick?: () => void;
}> = (props) => {
return (
<MuiButton
className={props.className}
title={props.title}
disabled={props.disabled}
onClick={props.onClick}
variant="outlined"
children={props.children}
/>
);
};
@@ -0,0 +1,27 @@
import { FC } from "react";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { useHAAreas } from "haService/AreaRegistry";
export type InputAreaProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[];
restrictedIntegrations?: string[];
};
export const InputArea: FC<InputAreaProps> = (props) => {
// state
const areas = useHAAreas();
console.log(areas);
return (
<InputAutoComplete
{...props}
validateOption={(v) => areas.validateOptions(v)}
options={areas.getOptions()}
getID={areas.getID}
getLabel={areas.getLabel}
onlyShowLabel
/>
);
};
@@ -30,6 +30,18 @@
.input-autocomplete--tags {
max-height: 5em;
width: fit-content;
max-width: 100%;
overflow: auto;
text-overflow: ellipsis;
}
.input-autocomplete--chip small {
max-width: 7em;
text-overflow: ellipsis;
overflow: hidden;
}
.input-autocomplete--popper {
min-width: fit-content;
}
@@ -0,0 +1,23 @@
import { computeSimilarity } from "./InputAutoComplete";
test("similarity score", () => {
const searchTerms = [
"lught",
"light",
"light balcn",
"light bal",
"light balcony",
"Balcony lig",
].map((x) => computeSimilarity(x, "light.balcony", "Balcony Light"));
expect(searchTerms).toStrictEqual(searchTerms.sort());
});
test("similarity score", () => {
expect(
computeSimilarity(
"li",
"6592b3d6d05d3de6fa26c3dbd2edecc2",
"Balcony Lights"
)
).toBeGreaterThan(0);
});
+245 -141
View File
@@ -1,152 +1,256 @@
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 { Badge } from "@mui/material";
import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
import Chip from "@mui/material/Chip";
import Badge from "@mui/material/Badge";
import Popper from "@mui/material/Popper";
import { SearchItem } from "./extras";
import { ReactNode } from "react";
import { prettyName } from "utils/formatting";
export type BaseOption<T = {}> = {
id: string;
label: string;
} & T;
export type Option<T = {}> = string | BaseOption<T>;
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;
validateOption?: (v: string[]) => string[] | null;
groupBy?: (opt: T) => string;
options: T[];
getLabel?: (opt: T) => string;
getID?: (opt: T) => string;
} & InputAutoCompletePropsBase;
export type InputAutoCompletePropsBase = {
label?: string;
} & ({
value: string | null;
multiple?: false;
onChange: (v: string | null) => void;
} | {
value: string | string[];
multiple: true;
onChange: (v: string[]) => void;
})
export const InputAutoComplete: FC<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;
className?: string;
disabled?: boolean;
required?: boolean;
onlyShowLabel?: boolean;
helperText?: ReactNode;
endAdornment?: ReactNode;
} & (
| {
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];
if (props.multiple) {
props.onChange(cleanValue);
} else {
props.onChange(cleanValue[cleanValue.length - 1])
}
| {
value: string | string[];
multiple: true;
onChange: (v: string[]) => void;
}
);
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
}
}
}
/>
export function computeSimilarity(
text: string,
optId: string,
optLabel: string
) {
let similarityScore = 0;
const lowCaseId = optId.toLocaleLowerCase();
const lowCaseLabel = optLabel.toLocaleLowerCase();
for (const segment of text.toLocaleLowerCase().split(" ")) {
if (lowCaseId.includes(segment)) {
similarityScore += lowCaseId.length / lowCaseId.length;
}
if (lowCaseLabel.includes(segment)) {
similarityScore += lowCaseLabel.length / lowCaseLabel.length;
}
}
return similarityScore;
}
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
.filter((opt) => !value.includes(getID(opt)))
.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}
disabled={props.disabled}
PopperComponent={(props) => {
return (
<Popper
key={Math.random().toString()}
{...props}
className={[props.className, "input-autocomplete--popper"].join(
" "
)}
/>
);
}}
filterOptions={(opts, s) => {
const searchTerm = s.inputValue;
if (!searchTerm) {
return opts;
}
return opts
.map((opt) => {
return {
opt,
similarityScore: computeSimilarity(
searchTerm,
getID(opt),
getLabel(opt)
),
};
})
.filter((opt) => opt.similarityScore > 0)
.sort((a, b) => {
return a.similarityScore < b.similarityScore ? 1 : -1;
})
.map(({ opt }) => opt);
}}
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}
onlyShowLabel={props.onlyShowLabel}
/>
</>
);
}}
renderInput={(params) => (
<TextField
{...params}
InputProps={{
...params.InputProps,
endAdornment: props.endAdornment ?? params.InputProps.endAdornment,
}}
variant="filled"
required={props.required}
label={props.label ?? "Entity ID"}
helperText={helperText}
disabled={props.disabled}
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"
title={`${label} / ${id}`}
label={
<>
{id === label ? (
<span>{prettyName(label)}</span>
) : (
<b>{label}</b>
)}
{id !== label && !props.onlyShowLabel && (
<small>{id}</small>
)}
</>
}
{...tagProps}
/>
);
})}
</div>
);
if (props.multiple) {
return (
<Badge badgeContent={tagValue.length} color="info">
{inner}
</Badge>
);
} else {
return inner;
}
}}
/>
);
}
+34 -22
View File
@@ -1,11 +1,15 @@
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import { ReactNode } from "react";
export interface InputAutoTextProps {
label: string;
value: string;
className?: string;
options?: string[];
error?: string;
required?: boolean;
endAdornment?: ReactNode;
onChange: (v: string) => void;
}
export default function InputAutoText({
@@ -13,28 +17,36 @@ export default function InputAutoText({
label,
options = [],
onChange,
className,
required,
endAdornment,
error,
}: InputAutoTextProps) {
return <Autocomplete
freeSolo
value={value}
options={options}
onChange={(_e, v) => onChange(
v === null ? "" : v
)}
renderInput={params => <TextField
{...params}
variant="filled"
label={label}
error={error !== undefined}
helperText={error}
onChange={e => {
e.preventDefault();
onChange(
e.target.value
)
}}
/>}
/>
return (
<Autocomplete
freeSolo
className={className}
value={value}
options={options}
onChange={(_e, v) => onChange(v === null ? "" : v)}
renderInput={(params) => (
<TextField
{...params}
required={required}
variant="filled"
label={label}
error={error !== undefined}
helperText={error}
fullWidth
InputProps={{
endAdornment,
}}
onChange={(e) => {
e.preventDefault();
onChange(e.target.value);
}}
/>
)}
/>
);
}
+60 -5
View File
@@ -1,22 +1,77 @@
import Checkbox from "@mui/material/Checkbox";
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormGroup from "@mui/material/FormGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import { ReactNode } from "react";
import FormHelperText from "@mui/material/FormHelperText";
import InputAdornment from "@mui/material/InputAdornment";
export interface Props {
label: string;
value: boolean;
title?: string;
helperText?: ReactNode;
onChange: (v: boolean) => void;
disabled?: boolean;
className?: string;
required?: boolean;
placeholder?: string;
endAdornment?: ReactNode;
}
export default function InputBoolean({
label,
value = false,
title,
helperText,
onChange,
disabled = false,
className,
required,
placeholder,
endAdornment,
}: Props) {
return <FormGroup className={className}>
<FormControlLabel disabled={disabled} control={<Checkbox checked={value} onChange={() => onChange(!value)} />} label={label} />
</FormGroup>
return (
<FormGroup
className={className}
title={title}
style={{
alignItems: "flex-start",
}}
>
<FormControlLabel
disabled={disabled}
control={
<Checkbox
checked={value}
onChange={() => onChange(!value)}
required={required}
placeholder={placeholder}
/>
}
label={
endAdornment ? (
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
}}
>
<span
style={{
flex: 1,
}}
>
{label}
</span>
<InputAdornment position="end">{endAdornment}</InputAdornment>
</div>
) : (
label
)
}
/>
<FormHelperText>{helperText}</FormHelperText>
</FormGroup>
);
}
+77 -75
View File
@@ -1,98 +1,98 @@
import "./InputTime.css";
import { useState, useEffect, FC } from "react";
import TextField from '@mui/material/TextField';
import EditIcon from '@mui/icons-material/Edit';
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 {
convertAutomationTimeToTimeObject,
convertObjectToAutomationTimeString,
} from "utils/time";
import { 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';
import InputLabel from "@mui/material/InputLabel";
import { ButtonIcon } from "components/Icons/ButtonIcons";
// constants
const fields: Array<keyof AutomationTimeObject> = [
'hours',
'minutes',
'seconds',
'milliseconds'
]
"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))
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
})
[k]: 0,
});
} else if (k === "hours") {
setDisplayValue({
...displayValue,
[k]: Number(v)
})
[k]: Number(v),
});
} else if (k === "minutes") {
let minutes = Number(v);
let { hours = 0 } = displayValue
let { hours = 0 } = displayValue;
if (minutes > 59) {
const additonalHours = Math.floor(minutes / 60)
hours += additonalHours
minutes = minutes - additonalHours * 60
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
let { hours = 0, minutes = 0 } = displayValue;
if (seconds > 59) {
const additonalHours = Math.floor(seconds / (60 * 60))
hours += additonalHours
seconds = seconds - additonalHours * 60
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
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
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
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
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
const additionalSeconds = Math.floor(milliseconds / 1000);
seconds += additionalSeconds;
milliseconds = milliseconds - additionalSeconds * 1000;
}
setDisplayValue({
...displayValue,
@@ -100,49 +100,51 @@ export const InputTime: FC<Props> = (props) => {
hours,
seconds,
milliseconds,
})
});
}
}
};
// effect
useEffect(() => {
if (disabled && !props.value) {
return
return;
}
if (disabled) {
props.onChange(undefined)
props.onChange(undefined);
} else {
const pVal = convertAutomationTimeToTimeString(props.value);
const cVal = convertObjectToAutomationTimeString(displayValue);
if (pVal !== cVal) {
props.onChange(displayValue)
props.onChange(displayValue);
}
}
}, [disabled, displayValue])
// eslint-disable-next-line
}, [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)}
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)}
/>
))}
<ButtonIcon
onClick={() => setDisabled(!disabled)}
icon={disabled ? <EditIcon /> : <CloseIcon />}
/>
)}
<IconButton onClick={() => setDisabled(!disabled)}>
{disabled ? <EditIcon /> : <CloseIcon />}
</IconButton>
</div>
</div>
</div>
}
);
};
+18 -14
View File
@@ -1,18 +1,22 @@
import { FC } from "react";
import { useHADeviceRegistry } from 'haService';
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete';
import { useHADeviceRegistry } from "haService";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
export type InputDeviceProps = InputAutoCompletePropsBase & { multiple?: false };
export type InputDeviceProps = InputAutoCompletePropsBase;
export const InputDevice: FC<InputDeviceProps> = props => {
// state
const dr = useHADeviceRegistry();
return <InputAutoComplete
{...props}
label={props.label ?? "Device ID"}
getID={dr.getID}
getLabel={dr.getLabel}
options={dr.getOptions()}
export const InputDevice: FC<InputDeviceProps> = (props) => {
// state
const dr = useHADeviceRegistry();
return (
<InputAutoComplete
{...props}
label={props.label ?? "Device ID"}
getID={dr.getID}
getLabel={dr.getLabel}
options={dr.getOptions()}
/>
}
);
};
@@ -0,0 +1,6 @@
.input-device-caps {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
@@ -0,0 +1,120 @@
import "./InputDeviceCapabilties.css";
import { HaFormSchema } from "haService/types";
import { useSnackbar } from "notistack";
import { useRef } from "react";
import { prettyName } from "utils/formatting";
import { InputAutoComplete, Option } from "./InputAutoComplete";
import InputBoolean from "./InputBoolean";
import { InputTime } from "./InputDayTime";
import InputNumber from "./InputNumber";
import InputText from "./InputText";
export type InputDeviceCapabiltiesProps<T extends Record<string, any>> = {
defn: HaFormSchema[];
state: T;
setState: (s: T) => void;
};
export function InputDeviceCapabilties<T extends Record<string, any>>(
props: InputDeviceCapabiltiesProps<T>
) {
const snackr = useSnackbar();
const msgRef = useRef<Record<string, boolean>>({});
return (
<div className="input-device-caps">
{props.defn.map((def, i) => {
const prop = {
key: String(i),
className: "input-device-cap",
label:
prettyName(def.name) +
" " +
(JSON.stringify(def.description) ?? ""),
required: def.required,
placeholder: def.default,
value: props.state[def.name],
onChange: (v: any) =>
props.setState({
...props.state,
[def.name]: v,
}),
};
if (def.type === "boolean") {
return <InputBoolean {...prop} />;
} else if (def.type === "string") {
return <InputText {...prop} />;
} else if (def.type === "integer") {
return (
<InputNumber
{...prop}
step={1}
max={def.valueMax}
min={def.valueMin}
/>
);
} else if (def.type === "float") {
return <InputNumber {...prop} step={0.01} />;
} else if (def.type === "constant") {
return (
<InputText {...prop} value={def.value ?? props.state[def.name]} />
);
} else if (def.type === "positive_time_period_dict") {
return <InputTime {...prop} />;
} else if (def.type === "select") {
return (
<InputAutoComplete
{...prop}
multiple={false}
options={def.options.map(([value, label]) => ({
id: value,
label: prettyName(label),
}))}
/>
);
} else if (def.type === "multi_select") {
let options: Option[] = [];
if (Array.isArray(def.options)) {
options = def.options.map((opt) =>
Array.isArray(opt)
? {
id: opt[0],
label: prettyName(opt[1]),
}
: {
id: opt,
label: prettyName(opt),
}
);
} else {
options = Object.entries(def.options).map(([id, label]) => ({
id,
label: prettyName(label),
}));
}
return (
<InputAutoComplete {...prop} multiple={true} options={options} />
);
}
if (!msgRef.current[def.name + def.type]) {
msgRef.current[def.name + def.type] = true;
snackr.enqueueSnackbar(
<span>
"{def.name}" is of a unimplemented type "{def.type}"! <br />
Please report this to the maintainers.{" "}
<b>For now, we leave you with a generic textbox!</b> <br />
DEBUG="{JSON.stringify(def)}"
</span>,
{
variant: "warning",
persist: true,
}
);
}
return (
<>
<InputText {...prop} />
</>
);
})}
</div>
);
}
+52 -16
View File
@@ -1,22 +1,58 @@
import { FC } from "react";
import { useHAEntities } from 'haService';
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete';
import { useHAEntities } from "haService/HAEntities";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { prettyName } from "utils/formatting";
export type InputEntityProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[],
}
restrictToDomain?: string[];
restrictedIntegrations?: string[];
preSelectedEntityIds?: string[];
};
export const InputEntity: FC<InputEntityProps> = props => {
// state
const entities = useHAEntities();
return <InputAutoComplete
{...props}
validateOption={v => entities.validateOptions(v, props.restrictToDomain)}
options={entities.getOptions(props.restrictToDomain)}
getID={entities.getID}
getLabel={entities.getLabel}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''}
export const InputEntity: FC<InputEntityProps> = (props) => {
// state
const entities = useHAEntities();
let options = entities.getOptions(
props.restrictToDomain,
props.restrictedIntegrations
);
if (props.preSelectedEntityIds) {
options = options.filter((opt) =>
props.preSelectedEntityIds?.includes(entities.getID(opt))
);
}
const validateOptions = (v: string[]): null | string[] => {
const errors: string[] = [];
if (props.preSelectedEntityIds) {
v.forEach((eid) => {
if (!props.preSelectedEntityIds?.includes(eid)) {
errors.push(`"${eid}" is not a valid selection`);
}
});
}
errors.concat(
entities.validateOptions(
v,
props.restrictToDomain,
props.restrictedIntegrations
) ?? []
);
if (errors.length > 0) {
return errors;
}
return null;
};
return (
<InputAutoComplete
{...props}
validateOption={validateOptions}
options={options}
getID={entities.getID}
getLabel={entities.getLabel}
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
/>
}
);
};
+61 -36
View File
@@ -1,54 +1,79 @@
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;
disabled?: boolean;
};
export function InputList<T extends string | Object>({
current,
options,
onChange,
label,
id,
className,
prettyOptionLabels,
prettyOptionLabels = true,
getKey = String,
placeholder,
title,
helperText,
endAdornment,
disabled,
}: 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` }}
fullWidth
disabled={disabled}
>
{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
disabled={disabled}
>
{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>
);
}
@@ -0,0 +1,3 @@
.input-number .MuiButtonBase-root.icon-button[type="button"].icon-button {
border-style: none;
}
+68 -25
View File
@@ -1,43 +1,86 @@
import "./InputNumber.css";
import Close from "@mui/icons-material/Close";
import TextField from "@mui/material/TextField";
import IconButton from "@mui/material/IconButton";
import InputAdornment from "@mui/material/InputAdornment";
import Edit from "@mui/icons-material/Edit";
import { ReactNode } from "react";
import { ButtonIcon } from "components/Icons/ButtonIcons";
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;
title?: string;
helperText?: ReactNode;
endAdornment?: ReactNode;
}
export default function InputNumber({
label,
value = undefined,
onChange,
className = "",
min, max, step,
min,
max,
step,
unit,
placeholder,
required,
endAdornment,
helperText,
title,
}: 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;
let labelElm = <></>;
let unitElm = <></>;
if (label) {
labelElm = <span>{label}</span>;
}
if (unit) {
unitElm = <small>({unit})</small>;
}
return (
<TextField
variant="filled"
label={
<div className="input-number--label">
{labelElm} {unitElm}
</div>
}
}}
/>
title={title}
value={value}
onChange={(e) => onChange(Number(e.target.value ?? 0))}
disabled={disabled}
className={["input-number", className ?? ""].join(" ")}
placeholder={placeholder}
required={required}
fullWidth
helperText={helperText}
InputProps={{
endAdornment: endAdornment ? (
endAdornment
) : (
<InputAdornment position="end">
<ButtonIcon
onClick={() => onChange(disabled ? 0 : undefined)}
icon={disabled ? <Edit /> : <Close />}
/>
</InputAdornment>
),
inputProps: {
min,
max,
type: "number",
step,
},
}}
/>
);
}
+43 -20
View File
@@ -1,11 +1,10 @@
import { PropsWithChildren, useState } from "react";
import React, { ReactNode, useState } from "react";
import { useToolTip } from "tooltip/context";
import TextField from '@mui/material/TextField';
import InputWrapper from "./InputWrapper";
import TextField from "@mui/material/TextField";
export interface Props {
textBoxFor?: string;
label: string;
label: string | JSX.Element;
value: string;
onChange: (v: string) => void;
onEnter?: () => void;
@@ -13,37 +12,62 @@ export interface Props {
multiline?: boolean;
maxRows?: number;
className?: string;
placeholder?: any;
title?: string;
helperText?: ReactNode;
endAdornment?: ReactNode;
required?: boolean;
}
export default function InputText({
label,
title,
helperText,
textBoxFor,
value = "",
onChange,
onEnter = () => { },
endAdornment,
onEnter = () => {},
additionalTooltipFilters = {},
multiline = false,
maxRows = 4,
children,
className,
}: PropsWithChildren<Props>) {
placeholder,
required,
}: 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') {
const [isFocused, setIsFocused] = useState(false);
return (
<TextField
className={className}
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 => {
onChange={(e) => {
e.preventDefault();
onChange(e.target.value)
onChange(e.target.value);
}}
onBlur={() => {
setIsFocused(false)
setIsFocused(false);
}}
onFocus={e => {
setIsFocused(true)
onFocus={(e) => {
setIsFocused(true);
if (textBoxFor) {
tooltip.setFocus(
e.target.getBoundingClientRect(),
@@ -53,10 +77,9 @@ export default function InputText({
filterObjects: additionalTooltipFilters,
},
onChange
)
);
}
}}
/>
{children}
</InputWrapper>
);
}
@@ -2,6 +2,12 @@
display: flex;
gap: 0;
flex-direction: row;
justify-content: center;
align-items: center;
}
.input-time>.input-time--inner>.icon-button {
border: none;
}
.input-time>.input-time--inner>.MuiFormControl-root {
+76 -75
View File
@@ -1,25 +1,24 @@
import "./InputTime.css";
import { useState, useEffect, FC } from "react";
import TextField from '@mui/material/TextField';
import EditIcon from '@mui/icons-material/Edit';
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 {
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';
import { ButtonIcon } from "components/Icons/ButtonIcons";
// constants
const fields: Array<keyof AutomationTimeObject> = [
'hours',
'minutes',
'seconds',
'milliseconds'
]
"hours",
"minutes",
"seconds",
"milliseconds",
];
export interface Props {
label: string;
value?: AutomationTime;
@@ -27,73 +26,73 @@ export interface Props {
className?: string;
}
export const InputTime: FC<Props> = (props) => {
// state
const [disabled, setDisabled] = useState(!props.value)
const [displayValue, setDisplayValue] = useState(convertAutomationTimeToTimeObject(props.value))
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
})
[k]: 0,
});
} else if (k === "hours") {
setDisplayValue({
...displayValue,
[k]: Number(v)
})
[k]: Number(v),
});
} else if (k === "minutes") {
let minutes = Number(v);
let { hours = 0 } = displayValue
let { hours = 0 } = displayValue;
if (minutes > 59) {
const additonalHours = Math.floor(minutes / 60)
hours += additonalHours
minutes = minutes - additonalHours * 60
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
let { hours = 0, minutes = 0 } = displayValue;
if (seconds > 59) {
const additonalHours = Math.floor(seconds / (60 * 60))
hours += additonalHours
seconds = seconds - additonalHours * 60
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
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
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
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
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
const additionalSeconds = Math.floor(milliseconds / 1000);
seconds += additionalSeconds;
milliseconds = milliseconds - additionalSeconds * 1000;
}
setDisplayValue({
...displayValue,
@@ -101,49 +100,51 @@ export const InputTime: FC<Props> = (props) => {
hours,
seconds,
milliseconds,
})
});
}
}
};
// effect
useEffect(() => {
if (disabled && !props.value) {
return
return;
}
if (disabled) {
props.onChange(undefined)
props.onChange(undefined);
} else {
const pVal = convertAutomationTimeToTimeString(props.value);
const cVal = convertObjectToAutomationTimeString(displayValue);
if (pVal !== cVal) {
props.onChange(displayValue)
props.onChange(displayValue);
}
}
}, [disabled, displayValue])
// eslint-disable-next-line
}, [disabled, displayValue]);
return <div className={["input-time", props.className ?? ""].join(" ")}>
{/* <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)}
return (
<div className={["input-time", props.className ?? ""].join(" ")}>
{/* <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)}
/>
))}
<ButtonIcon
onClick={() => setDisabled(!disabled)}
icon={disabled ? <EditIcon /> : <CloseIcon />}
/>
)}
<IconButton onClick={() => setDisabled(!disabled)}>
{disabled ? <EditIcon /> : <CloseIcon />}
</IconButton>
</div>
</div>
</div>
}
);
};
@@ -0,0 +1,41 @@
.input-yaml {
align-items: flex-start;
position: relative;
}
.input-yaml label {
position: initial;
margin-bottom: 1em;
}
.input-yaml [lang=yaml] {
flex: 1;
width: 100%;
min-width: 100%;
}
.input-yaml .MuiFormHelperText-root {
width: 100%;
max-width: 100%;
display: block;
overflow: hidden;
margin: 0;
padding: 0.25em 0.1em;
}
.input-yaml .MuiInputAdornment-positionEnd {
position: absolute;
right: 0.5em;
top: 3.5em;
}
.input-yaml .input-yaml--placeholder {
position: absolute;
left: 2em;
top: 2.5em;
color: var(--primary-accent);
}
.input-yaml .MuiButtonBase-root.icon-button[type="button"].icon-button {
border-style: none;
}
+87 -34
View File
@@ -1,17 +1,26 @@
import "./InputYaml.css";
import * as yaml from "js-yaml";
import { useEffect, useState } from "react";
import { useDelayEffect } from 'utils/useDelay';
import CodeMirror from '@uiw/react-codemirror';
import InputWrapper from "./InputWrapper";
import { useEffect, useState, ReactNode } from "react";
import CodeMirror from "@uiw/react-codemirror";
import FormControl from "@mui/material/FormControl";
import InputLabel from "@mui/material/InputLabel";
import FormHelperText from "@mui/material/FormHelperText";
import InputAdornment from "@mui/material/InputAdornment";
import { Save } from "@mui/icons-material";
import { ButtonIcon } from "components/Icons/ButtonIcons";
export interface Props<T extends {}> {
label: string;
value: T;
onChange: (v: T) => void;
error?: JSX.Element | string,
error?: JSX.Element | string;
className?: string;
placeholder?: any;
required?: boolean;
title?: string;
helperText?: ReactNode;
endAdornment?: ReactNode;
}
export default function InputYaml<T extends {}>({
label,
@@ -19,45 +28,89 @@ export default function InputYaml<T extends {}>({
value = {} as any,
onChange,
className,
placeholder,
required,
title,
helperText,
endAdornment,
}: Props<T>) {
const [{ text, error }, setState] = useState<{
text: string,
error: undefined | JSX.Element | string,
const [{ text, error, hasChanged }, setState] = useState<{
text: string;
error: undefined | JSX.Element | string;
hasChanged: boolean;
}>({
text: yaml.dump(value),
error: incmError,
hasChanged: false,
});
const setText = (t: string) => {
try {
yaml.load(t)
setState({ text: t, error: undefined })
yaml.load(t);
setState({ text: t, error: undefined, hasChanged: true });
} catch (_) {
setState({ text: t, error: "! Invalid Yaml !" })
setState({ text: t, error: "! Invalid Yaml !", hasChanged: true });
}
}
};
const onSave = () => {
if (!error && yaml.dump(value) !== text) {
if (text) {
onChange(yaml.load(text) as any);
} else if (Array.isArray(value)) {
onChange([] as any);
} else {
onChange({} as any);
}
setState({
text,
error,
hasChanged: false,
});
}
};
useEffect(() => {
setState({
text: yaml.dump(value),
error: incmError,
})
}, [value, incmError])
useDelayEffect(() => {
if (!error && (yaml.dump(value) !== text)) {
if (text) {
onChange(yaml.load(text) as any)
} else if (Array.isArray(value)) {
onChange([] as any)
} else {
onChange({} as any)
}
}
}, [text], 1000)
return <InputWrapper className={className} label={label} error={error}>
<CodeMirror
theme={"dark"}
value={text}
lang="yaml"
onChange={setText}
/>
</InputWrapper>
hasChanged: false,
});
}, [value, incmError]);
return (
<FormControl
className={["input-yaml", className ?? ""].join(" ")}
fullWidth
title={title}
>
<InputLabel>
{label} {required ? "*" : ""}
</InputLabel>
<CodeMirror
theme={"dark"}
value={text}
lang="yaml"
onChange={setText}
maxWidth="100%"
width="100%"
minWidth="100%"
/>
<span className="input-yaml--placeholder">
{!!text ? "" : placeholder}
</span>
<InputAdornment position="end">
<ButtonIcon
disabled={!hasChanged}
onClick={() => onSave()}
title={!!error ? "Invalid YAML" : hasChanged ? "Save" : ""}
icon={
<Save
color={hasChanged ? (!!error ? "error" : "success") : "disabled"}
/>
}
/>
{endAdornment}
</InputAdornment>
<FormHelperText variant="filled" error={!!error}>
{error ? error : helperText}
</FormHelperText>
</FormControl>
);
}
@@ -4,25 +4,33 @@ import { Page } from "components/Page";
import { SearchItem } from "./extras";
export default {
title: 'Inputs/Extras/SearchItem',
title: "Inputs/Extras/SearchItem",
component: SearchItem,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
parameters: { actions: { argTypesRegex: "^on.*" } },
argTypes: {},
} as ComponentMeta<typeof SearchItem>;
const Template: ComponentStory<typeof SearchItem> = (args) => {
return (
<Page>
<div
style={{
width: "15em",
height: "3em",
border: "1px solid var(--primary-accent)",
}}
>
<SearchItem {...args} />
</div>
</Page>
);
};
const Template: ComponentStory<typeof SearchItem> = args => {
return <Page>
<SearchItem {...args} />
</Page>
}
export const Simple = Template.bind({})
export const Simple = Template.bind({});
Simple.args = {
id: "sensor.humidity_main_bedroom",
label: 'Main Bedroom Humidity',
label: "Main Bedroom Humidity",
searchTerm: "bedroom",
listProps: {},
} as any
onlyShowLabel: false,
};
+38 -4
View File
@@ -1,9 +1,43 @@
.input-extras--search-item--list {
display: flex;
flex-direction: row;
gap: 0.15em;
flex-direction: column;
gap: 0;
justify-content: center;
align-items: flex-start !important;
margin: 0;
padding: 0;
min-height: 2em;
max-height: 100%;
height: 100%;
width: 100%;
min-width: 100%;
max-width: 20em;
text-overflow: ellipsis;
overflow: hidden;
}
.input-extras--search-item--list>small::before {
.input-extras--search-item--list small {
/* max-height: 2em; */
max-width: 100%;
width: fit-content;
overflow: hidden;
text-overflow: ellipsis;
}
.input-extras--search-item--list b {
max-height: 1.5em;
width: fit-content;
max-width: 100%;
padding-right: 0.25em;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
}
/* .input-extras--search-item--list>small::before {
content: "/ ";
}
} */
+69 -41
View File
@@ -1,47 +1,75 @@
import "./extras.css";
import { FC } from "react";
import parse from 'autosuggest-highlight/parse';
import match from 'autosuggest-highlight/match';
import parse from "autosuggest-highlight/parse";
import match from "autosuggest-highlight/match";
export const HighlightElm: FC<{
text: string,
searchTerm: string
}> = ({
text,
searchTerm
}) => {
const matches = match(text, searchTerm, {
"findAllOccurrences": true,
"insideWords": true
});
const parts = parse(text, matches);
return <>
{parts.map((part, index) => (
<span
key={index}
style={{
textDecoration: part.highlight ? 'underline' : 'unset'
}}
>
{part.text}
</span>
))}
</>
}
text: string;
searchTerm: string;
}> = ({ text, searchTerm }) => {
const matches = match(text, searchTerm, {
findAllOccurrences: true,
insideWords: true,
});
const parts = parse(text, matches);
return (
<>
{parts.map((part, index) => (
<span
key={index}
style={{
textDecoration: part.highlight ? "underline" : "unset",
}}
>
{part.text}
</span>
))}
</>
);
};
export const SearchItem: FC<{
listProps: React.HTMLAttributes<HTMLLIElement>,
label: string,
id: string,
searchTerm: string,
}> = ({
listProps,
label,
id,
searchTerm
}) => <li {...listProps} className={[listProps.className ?? "", 'input-extras--search-item--list'].join(' ')}>
<b><HighlightElm text={label} searchTerm={searchTerm} /></b> <small>
<HighlightElm text={id} searchTerm={searchTerm} />
</small>
</li>
listProps: React.HTMLAttributes<HTMLLIElement>;
label: string;
id: string;
searchTerm: string;
onlyShowLabel?: boolean;
}> = ({ listProps, label, id, searchTerm, onlyShowLabel = false }) => {
const labelElm = (
<b className="input-extras--search-item--list--label">
<HighlightElm text={label} searchTerm={searchTerm} />
</b>
);
const idElm = (
<small className="input-extras--search-item--list--id">
<HighlightElm text={id} searchTerm={searchTerm} />
</small>
);
let inner = (
<>
{labelElm}
{idElm}
</>
);
if (onlyShowLabel) {
if (label) {
inner = labelElm;
} else {
inner = idElm;
}
}
return (
<li
{...listProps}
className={[
listProps.className ?? "",
"input-extras--search-item--list",
].join(" ")}
>
{inner}
</li>
);
};
+17
View File
@@ -0,0 +1,17 @@
.modal--root {
display: flex;
justify-content: center;
align-items: center;
z-index: 10;
position: fixed;
height: 100vh;
width: 100vw;
top: 0;
left: 0;
}
.modal--root>div {
max-width: fit-content;
min-width: 100px;
padding: 0.25em;
}
+16 -53
View File
@@ -1,61 +1,24 @@
import "./index.css";
import Paper from "@mui/material/Paper";
import MuiModal from "@mui/material/Modal";
import { FC, ReactNode } from "react";
import { createAppUseStyles } from "styles/theme";
import { Card, CardActions, CardContent } from "@mui/material";
export interface ModalStyleProps {
open: boolean;
}
export interface Props extends ModalStyleProps {
children: ReactNode;
actions?: ReactNode;
}
const useModalStyle = createAppUseStyles<ModalStyleProps>(theme => ({
root: ({ open }) => ({
display: open ? 'flex' : 'none',
justifyContent: 'center',
alignItems: 'center',
zIndex: open ? 10 : -1,
position: 'fixed',
height: '100vh',
width: '100vw',
top: 0,
left: 0,
}),
background: {
zIndex: 5,
position: 'absolute',
height: '100vh',
width: '100vw',
top: 0,
left: 0,
backgroundColor: theme.secondaryOpaque,
},
inner: {
zIndex: 10,
maxWidth: '80vw',
maxHeight: '90vh',
minHeight: 'min-content',
minWidth: '100px',
padding: '15px',
display: 'flex',
flexDirection: 'column',
backgroundColor: theme.primary,
borderSize: '1px',
borderStyle: 'solid',
borderColor: theme.primaryAccent,
borderRadius: '10px',
color: theme.primaryAccent,
overflow: "auto",
resize: "auto",
}
}));
export const Modal: FC<Props> = ({
children,
...props
}) => {
const { classes } = useModalStyle(props);
return <div className={classes.root}>
<div className={classes.background} />
<div className={classes.inner}>
{children}
</div>
</div>
}
export const Modal: FC<Props> = ({ children, actions, open }) => {
return (
<MuiModal open={open}>
<div className="modal--root">
<Card variant="outlined">
<CardContent>{children}</CardContent>
</Card>
</div>
</MuiModal>
);
};
@@ -1,36 +1,31 @@
import { InputDevice } from "components/Inputs/InputDevice";
import { InputEntity } from "components/Inputs/InputEntities";
import InputText from "components/Inputs/InputText";
import { DeviceEditor } from "components/DeviceEditor";
import { DeviceAction } from "types/automations/actions";
import { OptionManager, updateActionData } from './OptionManager';
import { OptionManager } from "./OptionManager";
export const ActionDeviceState: OptionManager<DeviceAction> = {
defaultState: () => ({
alias: "",
device_id: ""
device_id: "",
}),
isReady: () => true,
renderOptionList: (state, setState, entities) => {
const update = updateActionData(state, setState);
return <>
<InputDevice
value={state.device_id ?? ""}
onChange={device_id => update({ device_id: device_id ?? "" })}
Component: ({ state, setState, ha }) => {
const options = ha.deviceExtras.useDeviceActions(
state.device_id
? {
deviceId: state.device_id,
}
: undefined
);
const caps = ha.deviceExtras.useDeviceCapalities(
state.device_id && state.type && state.domain ? (state as any) : undefined
);
return (
<DeviceEditor
state={state}
setState={setState}
options={options}
caps={caps}
type="action"
/>
<InputText
textBoxFor="type"
label="Action"
value={state.type ?? ""}
onChange={type => update({ type })}
/>
<InputEntity
value={state.entity_id ?? ""}
onChange={entity_id => update({
entity_id: entity_id ? entity_id : undefined,
domain: entity_id ? entity_id.split('.')[0] : ""
})}
/>
</>
}
}
);
},
};
@@ -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, ha: { 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,46 +1,54 @@
import { HAEntitiesState } from 'haService';
import { FC } from 'react';
import { AutomationAction } from 'types/automations/actions';
import { AutomationCondition } from 'types/automations/conditions';
import { HAService } from "haService";
import { HAEntitiesState } from "haService/HAEntities";
import { FC } from "react";
import { AutomationAction } from "types/automations/actions";
import { AutomationCondition } from "types/automations/conditions";
export type OptionManager<T> = {
defaultState(): T;
isReady(s: T): boolean;
} & ({
renderOptionList(s: T, set: (s: T) => void, entities: HAEntitiesState): JSX.Element;
} | {
Component: FC<{
state: T,
setState: (s: T) => void,
entities: HAEntitiesState,
}>
})
} & (
| {
renderOptionList(
s: T,
set: (s: T) => void,
entities: HAEntitiesState
): JSX.Element;
}
| {
Component: FC<{
state: T;
setState: (s: T) => void;
ha: HAService;
}>;
}
);
export const cleanUpUndefined = (data: Record<string, any>): any => {
const clean: any = {};
Object.keys(data).forEach(k => {
if ((data[k] !== undefined) && (data[k] !== null)) {
clean[k] = data[k]
Object.keys(data).forEach((k) => {
if (data[k] !== undefined && data[k] !== null) {
clean[k] = data[k];
}
})
});
return clean;
}
};
export const updateConditionData = <T extends AutomationCondition>(
setState: (s: T) => void
) => (
state: T,
data: Partial<T>,
) => setState(cleanUpUndefined({
...state,
...data,
}))
export const updateConditionData =
<T extends AutomationCondition>(setState: (s: T) => void) =>
(state: T, data: Partial<T>) =>
setState(
cleanUpUndefined({
...state,
...data,
})
);
export const updateActionData = <T extends AutomationAction>(
state: T,
setState: (s: T) => void
) => (
data: Partial<T>,
) => setState(cleanUpUndefined({
...state,
...data,
}))
export const updateActionData =
<T extends AutomationAction>(state: T, setState: (s: T) => void) =>
(data: Partial<T>) =>
setState(
cleanUpUndefined({
...state,
...data,
})
);
@@ -1,38 +1,38 @@
import { OptionManager } from './OptionManager';
import { AutomationTriggerDevice } from 'types/automations/triggers';
import InputText from 'components/Inputs/InputText';
import { InputEntity } from 'components/Inputs/InputEntities';
import InputTextBubble from 'components/Inputs/InputTextBubble';
import { InputDevice } from 'components/Inputs/InputDevice';
import { OptionManager } from "./OptionManager";
import { AutomationTriggerDevice } from "types/automations/triggers";
import { DeviceEditor } from "components/DeviceEditor";
export const TriggerDevice: OptionManager<AutomationTriggerDevice> = {
defaultState: () => ({
"platform": 'device',
platform: "device",
}),
isReady: () => true,
renderOptionList: (state, setState, { getDomainList }) => {
return <>
<InputTextBubble label="Domain" options={getDomainList()} value={state.domain} onChange={domain => setState({
...state,
domain: domain ? domain[0] : "",
})} />
<InputText label="Type" value={state.type ?? ""} onChange={type => setState({
...state,
type
})} />
<InputText label="Subtype" value={state.subtype ?? ""} onChange={subtype => setState({
...state,
subtype
})} />
<InputDevice value={state.device_id ?? ""} onChange={device_id => setState({
...state,
device_id: device_id ?? "",
})} />
<InputEntity restrictToDomain={state.domain ? [state.domain] : undefined} value={state.entity_id ?? ""} multiple onChange={entity_id => setState({
...state,
entity_id
})} />
</>
}
}
Component: ({ state, setState, ha }) => {
// state
const triggers = ha.deviceExtras.useDeviceTriggers(
state.device_id
? {
deviceId: state.device_id,
}
: undefined
);
const caps = ha.deviceExtras.useDeviceTriggerCapalities(
state.device_id && state.type && state.domain ? (state as any) : undefined
);
return (
<DeviceEditor
type="trigger"
state={state}
setState={(s) =>
setState({
platform: "device",
...s,
})
}
options={triggers}
caps={caps}
/>
);
},
};
@@ -1,36 +1,37 @@
import InputText from "components/Inputs/InputText";
import { OptionManager } from './OptionManager';
import { AutomationTriggerEvent } from '../../../types/automations/triggers';
import { OptionManager } from "./OptionManager";
import { AutomationTriggerEvent } from "../../../types/automations/triggers";
import InputYaml from "components/Inputs/InputYaml";
export const TriggerEventState: OptionManager<AutomationTriggerEvent> = {
defaultState: () => ({
"platform": "event",
"event_type": "",
"event_data": {},
"context": {},
platform: "event",
event_type: "",
event_data: {},
context: {},
}),
isReady: ({ event_type }) => {
return (event_type !== "")
return event_type !== "";
},
renderOptionList: (state, setState) => {
return <>
<InputText
label="Event Type"
value={String(state.event_type)}
onChange={event_type => setState({ ...state, event_type })}
/>
<InputYaml
label="Data"
value={state.event_data ?? {}}
onChange={event_data => setState({ ...state, event_data })}
/>
<InputYaml
label="Context"
value={state.event_data ?? {}}
onChange={context => setState({ ...state, context })}
/>
</>
}
}
return (
<>
<InputText
label="Event Type"
value={String(state.event_type)}
onChange={(event_type) => setState({ ...state, event_type })}
/>
<InputYaml
label="Data"
value={state.event_data ?? {}}
onChange={(event_data) => setState({ ...state, event_data })}
/>
<InputYaml
label="Context"
value={state.context ?? {}}
onChange={(context) => setState({ ...state, context })}
/>
</>
);
},
};
@@ -1,54 +1,128 @@
import { OptionManager } from './OptionManager';
import { AutomationTriggerState } from 'types/automations/triggers';
import InputText from 'components/Inputs/InputText';
import { InputEntity } from 'components/Inputs/InputEntities';
import { InputTime } from 'components/Inputs/InputTime';
import { OptionManager } from "./OptionManager";
import { AutomationTriggerState } from "types/automations/triggers";
import InputText from "components/Inputs/InputText";
import { InputEntity } from "components/Inputs/InputEntities";
import { InputTime } from "components/Inputs/InputTime";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { FC } from "react";
import { getEntityDomains } from "utils/automations";
import { InputList } from "components/Inputs/InputList";
import { entityDomainsAreBinary } from "../../../utils/automations";
export const TriggerState: OptionManager<AutomationTriggerState> = {
defaultState: () => ({
"platform": 'state',
"entity_id": "",
platform: "state",
entity_id: "",
}),
isReady: () => true,
renderOptionList: (state, setState) => {
return <>
<InputEntity
value={state.entity_id}
multiple
onChange={entity_id => setState({
...state,
entity_id
})}
/>
<InputText label="Attribute" value={state.attribute ?? ""} onChange={attribute => setState({
...state,
attribute
})} />
Component: ({ state, setState, ha: { entities } }) => {
const attributes = entities.getAttributes(state.entity_id);
const states = entities.getStates(state.entity_id, state.attribute);
return (
<>
<InputEntity
value={state.entity_id}
multiple
onChange={(entity_id) =>
setState({
...state,
entity_id,
})
}
/>
<InputAutoComplete
label="Attribute"
value={state.attribute ?? ""}
options={attributes}
multiple={false}
onChange={(attribute) =>
setState({
...state,
attribute: attribute ?? undefined,
})
}
/>
<FromTo
entityId={state.entity_id}
hasAttribute={!!state.attribute}
values={{ to: state.to ?? "", from: state.from ?? "" }}
onChange={(x) => setState({ ...state, ...x })}
states={states}
/>
<InputTime
label="For"
value={state.for}
onChange={(_for) =>
setState({
...state,
for: _for,
})
}
/>
</>
);
},
};
export const FromTo: FC<{
entityId: string | string[];
hasAttribute: boolean;
values: { to: string; from: string };
onChange: (s: Partial<{ to: string; from: string }>) => void;
states: string[];
}> = (props) => {
if (!props.hasAttribute) {
const domains = getEntityDomains(props.entityId);
if (entityDomainsAreBinary(domains)) {
return (
<div style={{ display: "flex", flexDirection: "row", gap: "0.25em" }}>
<InputList
label="From"
options={["on", "off"]}
current={props.values.from}
onChange={(from) =>
props.onChange({
from,
})
}
/>
<InputList
label="To"
options={["on", "off"]}
current={props.values.to}
onChange={(to) =>
props.onChange({
to,
})
}
/>
</div>
);
}
}
const example = `eg. ${props.states.join(" or ")}`;
return (
<div style={{ display: "flex", flexDirection: "row", gap: "0.25em" }}>
<InputText
label="From"
value={state.from ?? ""}
onChange={from => setState({
...state,
from,
})}
value={props.values.from}
onChange={(from) =>
props.onChange({
from,
})
}
placeholder={example}
/>
<InputText
label="To"
value={state.to ?? ""}
onChange={to => setState({
...state,
to,
})}
value={props.values.to}
onChange={(to) =>
props.onChange({
to,
})
}
placeholder={example}
/>
<InputTime
label="For"
value={state.for}
onChange={_for => setState({
...state,
for: _for,
})}
/>
</>
}
}
</div>
);
};
@@ -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 ha = 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,122 @@ 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,
ha.namer,
false
)}
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, ha.entities)
) : (
<optionManager.Component
state={currentNode}
setState={setState}
ha={ha}
/>
)}
</>
);
},
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 +203,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 +220,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.warn({ 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: <></>,
};
}
}
};
@@ -1,106 +1,135 @@
import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { NodeEditor } from ".";
import { AutomationCondition } from "types/automations/conditions";
import { Button } from "components/Inputs/Button";
import { useState } from 'react';
import { useState } from "react";
import { Modal } from "components/Modal";
import { Page } from "components/Page";
export default {
title: 'NodeEditor',
title: "NodeEditor",
component: NodeEditor,
parameters: { actions: { argTypesRegex: '^on.*' } },
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
node: {
'data': {},
'service': '',
'target': '',
}
}
} as ComponentMeta<typeof NodeEditor>
data: {},
service: "",
target: "",
},
},
} as ComponentMeta<typeof NodeEditor>;
const Base: ComponentStory<typeof NodeEditor> = props => {
return <Page>
<NodeEditor {...props} />
</Page>
const Base: ComponentStory<typeof NodeEditor> = (props) => {
return (
<Page>
<NodeEditor {...props} />
</Page>
);
};
export const Action = Base.bind({})
export const SingleOption = Action.bind({})
export const Action = Base.bind({});
export const SingleOption = Action.bind({});
SingleOption.args = {
...SingleOption.args,
allowedTypes: ['action'],
}
export const Condition = Action.bind({})
allowedTypes: ["action"],
};
export const Condition = Action.bind({});
Condition.args = {
...Condition.args,
node: {
"condition": "and",
"conditions": [
condition: "and",
conditions: [
{
"condition": "numeric_state",
"entity_id": [
"sensor.kitchen_humidity"
],
"conditions": [],
"above": "40"
condition: "numeric_state",
entity_id: ["sensor.kitchen_humidity"],
conditions: [],
above: "40",
},
{
"condition": "template",
"value_template": "states('switch.kitchen') == 'on'"
}
]
condition: "template",
value_template: "states('switch.kitchen') == 'on'",
},
],
} as AutomationCondition,
}
};
export const UnSupported = Action.bind({})
export const UnSupported = Action.bind({});
UnSupported.args = {
...UnSupported.args,
node: {
"condition": "bargs",
"platform": "rouge"
condition: "bargs",
platform: "rouge",
} as any,
}
};
export const DeviceTriggerExample = Action.bind({})
export const DeviceTriggerExample = Action.bind({});
DeviceTriggerExample.args = {
...DeviceTriggerExample.args,
node: {
"platform": 'device',
platform: "device",
device_id: "bd83b10cb1c7aa028c12dade5b4e87d5",
},
}
export const InAModal: ComponentStory<typeof NodeEditor> = props => {
const [open, setOpen] = useState(false);
return <Page>
<Button onClick={() => setOpen(!open)}>Open Editor</Button>
<Modal open={open}>
<NodeEditor {...props} onClose={() => setOpen(!open)} />
</Modal>
</Page>
};
export const InAModal: ComponentStory<typeof NodeEditor> = (props) => {
const [open, setOpen] = useState(false);
return (
<Page>
<Button onClick={() => setOpen(!open)}>Open Editor</Button>
<Modal open={open}>
<NodeEditor {...props} onClose={() => setOpen(!open)} />
</Modal>
</Page>
);
};
export const ServiceExample = Action.bind({})
export const ServiceExample = Action.bind({});
ServiceExample.args = {
...ServiceExample.args,
node: {
"target": {},
"data": {},
"service": "",
target: {},
data: {},
service: "",
},
}
};
export const ServiceWithDataExample = Action.bind({});
ServiceWithDataExample.args = {
...ServiceWithDataExample.args,
node: {
target: {
entity: "light.switch_baby",
},
data: {
color_name: "red",
},
service: "light.turn_on",
},
};
export const DelayExample = Action.bind({})
export const DelayExample = Action.bind({});
DelayExample.args = {
...DelayExample.args,
node: {
"wait_template": "",
wait_template: "",
},
}
};
export const StateTriggerExample = Action.bind({});
StateTriggerExample.args = {
...StateTriggerExample.args,
node: {
platform: "state",
entity_id: "binary_sensor.door_main",
},
};
export const DeviceActionFilledExample = Action.bind({});
DeviceActionFilledExample.args = {
...DeviceActionFilledExample.args,
node: {
type: "toggle",
device_id: "c9711be86b0301955f72380509285485",
},
};
+86 -54
View File
@@ -1,14 +1,14 @@
import "./index.css";
import { FC, ReactNode } from 'react';
import { AutomationNode, AutomationNodeMapping } from 'types/automations/index';
import { FC, ReactNode } from "react";
import { AutomationNode, AutomationNodeMapping } from "types/automations/index";
import { useEditorNodeState } from "./OptionManager";
import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button";
import InputBoolean from "components/Inputs/InputBoolean";
export interface NodeEditorProps {
node: AutomationNode
node: AutomationNode;
allowedTypes?: Array<keyof AutomationNodeMapping>;
onClose?: () => void;
onSave?: (n: AutomationNode) => void;
@@ -21,9 +21,9 @@ export interface NodeEditorProps {
export const NodeEditor: FC<NodeEditorProps> = ({
node,
allowedTypes = ["action", "condition", "trigger"],
onClose = () => { },
onSave = () => { },
onFlags = () => { },
onClose = () => {},
onSave = () => {},
onFlags = () => {},
saveBtnCreateText = false,
children,
isErrored = false,
@@ -34,58 +34,90 @@ export const NodeEditor: FC<NodeEditorProps> = ({
// alias
const isModified = state.isModified;
const isReady = state.isReady();
const areYouSureNotReady = (what: string) => !isReady ?
window.confirm(`This node is missing some values, are you sure you want to ${what}?`) :
state.isErrored ?
window.confirm(`This node contains errors, are you sure you want to ${what}?`) :
true;
const areYouSureNotReady = (what: string) =>
!isReady
? window.confirm(
`This node is missing some values, are you sure you want to ${what}?`
)
: state.isErrored
? window.confirm(
`This node contains errors, are you sure you want to ${what}?`
)
: true;
// events
onFlags(isReady, isModified);
// render
return <div className={[
"node-editor--root",
isModified ? "modded" : "",
(!isReady && isModified) ? 'not-ready' : '',
state.data.enabled === false ? 'disabled' : 'enabled'
].join(" ")}>
<div className="node-editor--body">
<div className="node-editor--body-title">
{allowedTypes.length > 1 ? <InputList
label="Type"
current={state.nodeType}
options={allowedTypes}
onChange={state.setNodeType}
/> : <></>}
{state.nodeType !== 'condition' ? <InputList
label={state.prettyNodeType}
current={state.subType as any}
options={state.subTypes}
onChange={state.setSubType}
/> : <></>}
<div className="node-editor--body-flags">
<InputBoolean label="Yaml" onChange={state.setYamlMode} value={state.yamlMode} disabled={state.isErrored} />
<InputBoolean className="enabled-flag" label='Enabled' value={state.data.enabled ?? true} onChange={state.setEnabled} />
return (
<div
className={[
"node-editor--root",
isModified ? "modded" : "",
!isReady && isModified ? "not-ready" : "",
state.data.enabled === false ? "disabled" : "enabled",
].join(" ")}
>
<div className="node-editor--body">
<div className="node-editor--body-title">
{allowedTypes.length > 1 ? (
<InputList
label="Type"
current={state.nodeType}
options={allowedTypes}
onChange={state.setNodeType}
prettyOptionLabels
/>
) : (
<></>
)}
{state.nodeType !== "condition" ? (
<InputList
label={state.prettyNodeType}
current={state.subType as any}
options={state.subTypes}
onChange={state.setSubType}
prettyOptionLabels
/>
) : (
<></>
)}
<div className="node-editor--body-flags">
<InputBoolean
label="Yaml"
onChange={state.setYamlMode}
value={state.yamlMode}
disabled={state.isErrored}
/>
<InputBoolean
className="enabled-flag"
label="Enabled"
value={state.data.enabled ?? true}
onChange={state.setEnabled}
/>
</div>
</div>
{state.renderOptionList()}
</div>
<div className="node-editor--footer">
<Button
className="node-editor--footer--close"
onClick={() => areYouSureNotReady("close") && onClose()}
>
Close
</Button>
<Button
className="node-editor--footer--save"
onClick={() => {
if (areYouSureNotReady("save")) {
onSave(state.data);
}
}}
title={!isReady ? "Some fields have not been properly filled up" : ""}
>
{saveBtnCreateText ? "Create" : "Save"}
</Button>
{children}
</div>
{state.renderOptionList()}
</div>
<div className="node-editor--footer">
<Button className="node-editor--footer--close" onClick={() => areYouSureNotReady('close') && onClose()}>Close</Button>
<Button
className="node-editor--footer--save"
onClick={() => {
if (areYouSureNotReady('save')) {
onSave(state.data)
}
}}
title={
!isReady ? "Some fields have not been properly filled up" : ""
}
>
{saveBtnCreateText ? "Create" : "Save"}
</Button>
{children}
</div>
</div>
}
);
};
+79 -62
View File
@@ -1,80 +1,97 @@
import "./index.css";
import { createRef, FC, ReactNode, useEffect, useRef } from 'react';
import { createTheme, ThemeProvider, useTheme } from '@mui/material/styles';
import { createRef, FC, ReactNode, useEffect, useRef } from "react";
import { createTheme, ThemeProvider, useTheme } from "@mui/material/styles";
import { VersionBox } from "components/VersionBox";
import { SnackbarKey, SnackbarProvider, useSnackbar } from 'notistack';
import { Button } from "@mui/material";
import { useHAConnection } from 'haService/connection';
import { SnackbarKey, SnackbarProvider, useSnackbar } from "notistack";
import Button from "@mui/material/Button";
import { useHAConnection } from "haService/connection";
const theme = createTheme({
palette: {
mode: 'dark'
},
palette: {
mode: "dark",
},
});
export const InternalPage: FC<{
children: ReactNode
children: ReactNode;
}> = ({ children }) => {
const conn = useHAConnection();
const theme = useTheme();
const snackbar = useSnackbar();
const snackbarKeyHAConKey = useRef<SnackbarKey | null>(null);
const conn = useHAConnection();
const theme = useTheme();
const snackbar = useSnackbar();
const snackbarKeyHAConKey = useRef<SnackbarKey | null>(null);
useEffect(() => {
if (conn.status === 'error') {
if (snackbarKeyHAConKey.current) {
snackbar.closeSnackbar(snackbarKeyHAConKey.current)
}
snackbarKeyHAConKey.current = snackbar.enqueueSnackbar(`Failed to connect to homeassistant due to "${JSON.stringify(conn.error)}"`, {
"variant": "error",
"persist": true,
})
} else if (conn.status === 'loading') {
if (snackbarKeyHAConKey.current) {
snackbar.closeSnackbar(snackbarKeyHAConKey.current)
}
snackbarKeyHAConKey.current = snackbar.enqueueSnackbar(`Connecting to websocket...`, {
"variant": "info",
})
} else if (conn.status === "loaded") {
if (snackbarKeyHAConKey.current) {
snackbar.closeSnackbar(snackbarKeyHAConKey.current)
}
snackbarKeyHAConKey.current = snackbar.enqueueSnackbar(`Connected to HA!`, {
"variant": "success",
})
useEffect(() => {
if (conn.status === "error") {
if (snackbarKeyHAConKey.current) {
snackbar.closeSnackbar(snackbarKeyHAConKey.current);
}
snackbarKeyHAConKey.current = snackbar.enqueueSnackbar(
`Failed to connect to homeassistant due to "${JSON.stringify(
conn.error
)}"`,
{
variant: "error",
persist: true,
}
}, [conn, snackbar])
);
} else if (conn.status === "loading") {
if (snackbarKeyHAConKey.current) {
snackbar.closeSnackbar(snackbarKeyHAConKey.current);
}
snackbarKeyHAConKey.current = snackbar.enqueueSnackbar(
`Connecting to websocket...`,
{
variant: "info",
}
);
} else if (conn.status === "loaded") {
if (snackbarKeyHAConKey.current) {
snackbar.closeSnackbar(snackbarKeyHAConKey.current);
}
snackbarKeyHAConKey.current = snackbar.enqueueSnackbar(
`Connected to HA!`,
{
variant: "success",
}
);
}
}, [conn, snackbar]);
return <main className="page" style={{
return (
<main
className="page"
style={{
color: theme.palette.text.primary,
background: theme.palette.background.default,
}}>
<VersionBox />
{children}
}}
>
<VersionBox />
{children}
</main>
}
);
};
export const Page: FC<{
children: ReactNode
children: ReactNode;
}> = ({ children }) => {
const notistackRef = createRef<any>();
const onClickDismiss = (key: SnackbarKey) => () => {
notistackRef.current.closeSnackbar(key);
}
return <ThemeProvider theme={theme}>
<SnackbarProvider
anchorOrigin={{
"vertical": "bottom",
"horizontal": "center"
}}
ref={notistackRef}
action={key => <Button onClick={onClickDismiss(key)}>Dismiss</Button>}
dense preventDuplicate
>
<InternalPage>
{children}
</InternalPage>
</SnackbarProvider>
const notistackRef = createRef<any>();
const onClickDismiss = (key: SnackbarKey) => () => {
notistackRef.current.closeSnackbar(key);
};
return (
<ThemeProvider theme={theme}>
<SnackbarProvider
anchorOrigin={{
vertical: "bottom",
horizontal: "center",
}}
ref={notistackRef}
action={(key) => <Button onClick={onClickDismiss(key)}>Dismiss</Button>}
dense
preventDuplicate
>
<InternalPage>{children}</InternalPage>
</SnackbarProvider>
</ThemeProvider>
}
);
};
@@ -0,0 +1,23 @@
.service-editor--field {
display: flex;
flex-direction: row;
align-items: center;
}
.service-editor--field .MuiFormHelperText-contained {
max-width: 100%;
overflow: hidden;
}
.service-editor--field--description {
text-overflow: ellipsis;
overflow: hidden;
word-wrap: break-word;
white-space: nowrap;
width: 100%;
max-width: 100%;
}
.service-editor--field .service-editor--field--remove.icon-button.MuiButtonBase-root.icon-button[type="button"] {
border-style: none;
}
@@ -0,0 +1,137 @@
import "./ServiceEditorField.css";
import { FC, useRef } from "react";
import { ServiceEditorOption } from "./options";
import InputText from "components/Inputs/InputText";
import InputNumber from "components/Inputs/InputNumber";
import { RemoveCircle } from "@mui/icons-material";
import { InputAutoComplete, Option } from "components/Inputs/InputAutoComplete";
import { prettyName } from "utils/formatting";
import InputBoolean from "components/Inputs/InputBoolean";
import { SelectorNumber, SelectorText } from "haService/fieldTypes";
import InputYaml from "components/Inputs/InputYaml";
import { useSnackbar } from "notistack";
import { InputEntity } from "components/Inputs/InputEntities";
import { ButtonIcon } from "components/Icons/ButtonIcons";
export type ServiceEditorFieldProps = {
option: ServiceEditorOption;
value: any;
onChange: (v: any) => void;
onRemove?: () => void;
};
export const ServiceEditorField: FC<ServiceEditorFieldProps> = ({
option,
value,
onChange,
onRemove,
}) => {
const snackr = useSnackbar();
const msgRef = useRef<Record<string, boolean>>({});
const description = option.data.description ?? "";
const isRequired = !onRemove;
const label = option.label;
let example = "";
const removeIcon = !onRemove ? (
<></>
) : (
<ButtonIcon
className="service-editor--field--remove"
onClick={onRemove}
title={`Remove ${label}`}
icon={<RemoveCircle color="secondary" />}
/>
);
example = option.data.example ? `Example: ${option.data.example}` : "";
const prop = {
className: "service-editor--field",
label,
title: description,
helperText: (
<div className="service-editor--field--description">{description}</div>
),
value: value ?? option.data.default,
onChange: onChange,
required: isRequired,
placeholder: example,
endAdornment: removeIcon,
};
if (option.data.selector) {
if ("number" in option.data.selector) {
const options: Partial<SelectorNumber> =
option.data.selector.number ?? {};
return (
<InputNumber
{...prop}
min={options.min}
max={options.max}
step={options.step}
/>
);
}
if (option.data.selector?.select) {
return (
<InputAutoComplete
{...prop}
options={option.data.selector.select.options.map<Option>((opt) => {
if (typeof opt === "string") {
return {
id: opt,
label: prettyName(opt),
};
}
return {
id: opt.value,
label: opt.label,
};
})}
getLabel={(opt) => {
if (typeof opt === "string") {
return prettyName(opt);
}
return opt.label;
}}
onlyShowLabel
/>
);
} else if ("text" in option.data.selector) {
const options: Partial<SelectorText> = option.data.selector.text ?? {};
return <InputText {...prop} multiline={options.multiline} />;
} else if ("boolean" in option.data.selector) {
return <InputBoolean {...prop} />;
} else if ("object" in option.data.selector) {
return <InputYaml {...prop} />;
} else if ("entity" in option.data.selector) {
const options = option.data.selector.entity ?? {};
console.log(options);
return (
<InputEntity
{...prop}
multiple={false}
restrictToDomain={options.domain ? [options.domain] : undefined}
restrictedIntegrations={
options.integration ? [options.integration] : undefined
}
/>
);
}
}
if (option.data.selector) {
if (!msgRef.current[JSON.stringify(option.data.selector)]) {
msgRef.current[JSON.stringify(option.data.selector)] = true;
snackr.enqueueSnackbar(
<span>
"{JSON.stringify(Object.keys(option.data.selector))}" is of a
unimplemented! <br />
Please report this to the maintainers.{" "}
<b>For now, we leave you with a generic textbox!</b> <br />
DEBUG="{JSON.stringify(option.data.selector)}"
</span>,
{
variant: "warning",
persist: true,
}
);
}
}
return <InputText {...prop} />;
};
@@ -0,0 +1,21 @@
.service-editor--targets {
display: flex;
flex-direction: row;
gap: 1em;
padding-bottom: 0.5em;
overflow: hidden;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
.service-editor--targets>div {
flex: 1;
min-width: 8em;
}
@media (max-width: 450px) {
.service-editor--targets>div {
max-width: 38vw;
}
}
@@ -0,0 +1,108 @@
import "./ServiceEditorTarget.css";
import { InputDevice } from "components/Inputs/InputDevice";
import { InputEntity } from "components/Inputs/InputEntities";
import { Targets } from "haService/fieldTypes";
import { FC } from "react";
import { InputArea } from "components/Inputs/InputArea";
type RawTargetData = {
entity_id?: string[] | string;
area_id?: string[] | string;
device_id?: string[] | string;
};
type CleanTargetData = {
entity_id: string[];
area_id: string[];
device_id: string[];
};
export type ServiceEditorTargetProps = {
defn: Targets;
value: RawTargetData | null | undefined;
onChange: (v: any) => void;
};
export const ServiceEditorTarget: FC<ServiceEditorTargetProps> = (props) => {
const value = cleanUpValue(props.value ?? {});
const domainRestrictions: string[] = [];
const integrationRestrictions: string[] = [];
if (props.defn.entity) {
if (typeof props.defn.entity.domain === "string") {
domainRestrictions.push(props.defn.entity.domain);
}
if (typeof props.defn.entity.integration === "string") {
integrationRestrictions.push(props.defn.entity.integration);
}
}
return (
<div className="service-editor--targets">
<InputEntity
label="Entity"
value={value.entity_id}
onChange={(entity_id) =>
props.onChange({
...(props.value || {}),
entity_id,
})
}
restrictToDomain={
domainRestrictions.length === 0 ? undefined : domainRestrictions
}
restrictedIntegrations={
integrationRestrictions.length === 0
? undefined
: integrationRestrictions
}
multiple
/>
<InputDevice
label="Device"
value={value.device_id}
onChange={(device_id) =>
props.onChange({
...(props.value || {}),
device_id,
})
}
multiple
/>
<InputArea
label="Area"
value={value.area_id}
onChange={(area_id) =>
props.onChange({
...(props.value || {}),
area_id,
})
}
restrictToDomain={
domainRestrictions.length === 0 ? undefined : domainRestrictions
}
restrictedIntegrations={
integrationRestrictions.length === 0
? undefined
: integrationRestrictions
}
multiple
/>
</div>
);
};
const cleanUpValue = (value: RawTargetData): CleanTargetData => {
const cleanOne = (v?: string[] | string): string[] => {
if (typeof v === "string") {
return [v];
}
if (!v || !Array.isArray(v)) {
return [];
}
return v;
};
return {
entity_id: cleanOne(value.entity_id),
device_id: cleanOne(value.device_id),
area_id: cleanOne(value.area_id),
};
};
@@ -0,0 +1,44 @@
.service-editor {
display: flex;
flex-direction: column;
padding: 0.5em 0.25em;
margin: 0.5em 0.25em;
border-color: var(--primary-accent);
border-width: 1px;
border-style: solid;
border-radius: 5px;
background-color: var(--secondary);
}
.service-editor hr {
width: 90%;
margin-top: 0.5em;
margin-bottom: 1em;
}
.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,575 @@
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";
import InputYaml from "components/Inputs/InputYaml";
export default {
title: "Services/ServiceEditor",
component: ServiceEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof ServiceEditor>;
const Template: ComponentStory<typeof ServiceEditor> = (props) => {
const [state, setState] = useState(props.data);
return (
<Page>
<div
style={{
maxHeight: "99vh",
overflow: "auto",
}}
>
<ServiceEditor
{...props}
data={state}
onUpdate={(d) => {
setState(d);
props.onUpdate(d);
}}
/>
<div
style={{
maxHeight: "25vh",
overflow: "auto",
}}
>
<InputYaml label="" value={state} onChange={() => {}} />
</div>
<div
style={{
maxHeight: "25vh",
overflow: "auto",
}}
>
<InputYaml
label=""
value={props.service.fields}
onChange={() => {}}
/>
</div>
<div
style={{
maxHeight: "25vh",
overflow: "auto",
}}
>
<InputYaml
label=""
value={props.service.target ?? {}}
onChange={() => {}}
/>
</div>
</div>
</Page>
);
};
const makeExample = (service: TypedHassService) => {
const Eg = Template.bind({});
Eg.args = {
...Eg,
service,
data: {
target: {},
field: {},
},
};
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" } },
});
export const LightTurnOn = makeExample({
name: "Turn on",
description:
"Turn on one or more lights and adjust properties of the light, even when they are turned on already.\n",
target: {
entity: {
domain: "light",
},
},
fields: {
transition: {
name: "Transition",
description: "Duration it takes to get to next state.",
selector: {
number: {
min: 0,
max: 300,
unit_of_measurement: "seconds",
},
},
},
rgb_color: {
name: "Color",
description: "The color for the light (based on RGB - red, green, blue).",
selector: {
color_rgb: null,
},
},
rgbw_color: {
name: "RGBW-color",
description:
"A list containing four integers between 0 and 255 representing the RGBW (red, green, blue, white) color for the light.",
advanced: true,
example: "[255, 100, 100, 50]",
selector: {
object: null,
},
},
rgbww_color: {
name: "RGBWW-color",
description:
"A list containing five integers between 0 and 255 representing the RGBWW (red, green, blue, cold white, warm white) color for the light.",
advanced: true,
example: "[255, 100, 100, 50, 70]",
selector: {
object: null,
},
},
color_name: {
name: "Color name",
description: "A human readable color name.",
advanced: true,
selector: {
select: {
options: [
"homeassistant",
"aliceblue",
"antiquewhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"blanchedalmond",
"blue",
"blueviolet",
"brown",
"burlywood",
"cadetblue",
"chartreuse",
"chocolate",
"coral",
"cornflowerblue",
"cornsilk",
"crimson",
"cyan",
"darkblue",
"darkcyan",
"darkgoldenrod",
"darkgray",
"darkgreen",
"darkgrey",
"darkkhaki",
"darkmagenta",
"darkolivegreen",
"darkorange",
"darkorchid",
"darkred",
"darksalmon",
"darkseagreen",
"darkslateblue",
"darkslategray",
"darkslategrey",
"darkturquoise",
"darkviolet",
"deeppink",
"deepskyblue",
"dimgray",
"dimgrey",
"dodgerblue",
"firebrick",
"floralwhite",
"forestgreen",
"fuchsia",
"gainsboro",
"ghostwhite",
"gold",
"goldenrod",
"gray",
"green",
"greenyellow",
"grey",
"honeydew",
"hotpink",
"indianred",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderblush",
"lawngreen",
"lemonchiffon",
"lightblue",
"lightcoral",
"lightcyan",
"lightgoldenrodyellow",
"lightgray",
"lightgreen",
"lightgrey",
"lightpink",
"lightsalmon",
"lightseagreen",
"lightskyblue",
"lightslategray",
"lightslategrey",
"lightsteelblue",
"lightyellow",
"lime",
"limegreen",
"linen",
"magenta",
"maroon",
"mediumaquamarine",
"mediumblue",
"mediumorchid",
"mediumpurple",
"mediumseagreen",
"mediumslateblue",
"mediumspringgreen",
"mediumturquoise",
"mediumvioletred",
"midnightblue",
"mintcream",
"mistyrose",
"moccasin",
"navajowhite",
"navy",
"navyblue",
"oldlace",
"olive",
"olivedrab",
"orange",
"orangered",
"orchid",
"palegoldenrod",
"palegreen",
"paleturquoise",
"palevioletred",
"papayawhip",
"peachpuff",
"peru",
"pink",
"plum",
"powderblue",
"purple",
"red",
"rosybrown",
"royalblue",
"saddlebrown",
"salmon",
"sandybrown",
"seagreen",
"seashell",
"sienna",
"silver",
"skyblue",
"slateblue",
"slategray",
"slategrey",
"snow",
"springgreen",
"steelblue",
"tan",
"teal",
"thistle",
"tomato",
"turquoise",
"violet",
"wheat",
"white",
"whitesmoke",
"yellow",
"yellowgreen",
],
},
},
},
hs_color: {
name: "Hue/Sat color",
description:
"Color for the light in hue/sat format. Hue is 0-360 and Sat is 0-100.",
advanced: true,
example: "[300, 70]",
selector: {
object: null,
},
},
xy_color: {
name: "XY-color",
description: "Color for the light in XY-format.",
advanced: true,
example: "[0.52, 0.43]",
selector: {
object: null,
},
},
color_temp: {
name: "Color temperature",
description: "Color temperature for the light in mireds.",
selector: {
color_temp: {
min_mireds: 153,
max_mireds: 500,
},
},
},
kelvin: {
name: "Color temperature (Kelvin)",
description: "Color temperature for the light in Kelvin.",
advanced: true,
selector: {
number: {
min: 2000,
max: 6500,
step: 100,
unit_of_measurement: "K",
},
},
},
brightness: {
name: "Brightness value",
description:
"Number indicating brightness, where 0 turns the light off, 1 is the minimum brightness and 255 is the maximum brightness supported by the light.",
advanced: true,
selector: {
number: {
min: 0,
max: 255,
},
},
},
brightness_pct: {
name: "Brightness",
description:
"Number indicating percentage of full brightness, where 0 turns the light off, 1 is the minimum brightness and 100 is the maximum brightness supported by the light.",
selector: {
number: {
min: 0,
max: 100,
unit_of_measurement: "%",
},
},
},
brightness_step: {
name: "Brightness step value",
description: "Change brightness by an amount.",
advanced: true,
selector: {
number: {
min: -225,
max: 255,
},
},
},
brightness_step_pct: {
name: "Brightness step",
description: "Change brightness by a percentage.",
selector: {
number: {
min: -100,
max: 100,
unit_of_measurement: "%",
},
},
},
white: {
name: "White",
description:
"Set the light to white mode and change its brightness, where 0 turns the light off, 1 is the minimum brightness and 255 is the maximum brightness supported by the light.",
advanced: true,
selector: {
number: {
min: 0,
max: 255,
},
},
},
profile: {
name: "Profile",
description: "Name of a light profile to use.",
advanced: true,
example: "relax",
selector: {
text: null,
},
},
flash: {
name: "Flash",
description: "If the light should flash.",
advanced: true,
selector: {
select: {
options: [
{
label: "Long",
value: "long",
},
{
label: "Short",
value: "short",
},
],
},
},
},
effect: {
name: "Effect",
description: "Light effect.",
selector: {
text: null,
},
},
},
});
export const ZhaLight = makeExample({
name: "Turn Light",
description: "",
fields: {
entity: {
description: "Light Entity",
selector: {
entity: {
domain: "light",
integration: "zha",
},
},
},
},
});
export const UltimateService = makeExample({
name: "Ultimate Service",
description: "Show a notification in the frontend.",
fields: {
message: {
name: "Text",
description: "Message body of the notification. [Templates accepted]",
example: "Please check your configuration.yaml.",
selector: {
text: null,
},
},
entity_id: {
name: "Entity with domain filter",
description: "Name(s) of media player entities.",
selector: {
entity: {
domain: "media_player",
},
},
},
level: {
name: "Options",
description: "Log level.",
default: "error",
selector: {
select: {
options: [
{
label: "Debug",
value: "debug",
},
{
label: "Info",
value: "info",
},
{
label: "Warning",
value: "warning",
},
{
label: "Error",
value: "error",
},
{
label: "Critical",
value: "critical",
},
],
},
},
},
format: {
name: "String Options",
description: "Stream format supported by media player.",
default: "hls",
selector: {
select: {
options: ["hls"],
},
},
},
keep_days: {
name: "Number",
description: "Number of history days to keep in database after purge.",
selector: {
number: {
min: 0,
max: 365,
unit_of_measurement: "days",
},
},
},
repack: {
name: "Boolean",
description:
"Attempt to save disk space by rewriting the entire database file.",
default: false,
selector: {
boolean: null,
},
},
domains: {
name: "Objects",
description:
"List the domains that need to be removed from the recorder database.",
example: "sun",
default: [],
selector: {
object: null,
},
},
addon: {
name: "Add-on",
description: "The add-on slug.",
example: "core_ssh",
selector: {
addon: null,
},
},
name: {
name: "Theme",
description: "Name of a predefined theme",
example: "default",
selector: {
theme: null,
},
},
icon: {
name: "Icon",
description: "Name of icon for the group.",
example: "mdi:camera",
selector: {
icon: null,
},
},
},
});
@@ -0,0 +1,156 @@
import "./index.css";
import { cleanUpUndefined } from "components/NodeEditor/OptionManager/OptionManager";
import { TypedHassService } from "haService/fieldTypes";
import { FC, useState } from "react";
import {
ServiceEditorOption,
splitUpOptions,
convertFieldToOption,
ServiceEditorData,
} from "./options";
import { ServiceEditorField } from "./ServiceEditorField";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { ServiceEditorTarget } from "./ServiceEditorTarget";
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, data);
const [additionalFields, setAdditionalFields] = useState<{
field: string[];
optionalList: ServiceEditorOption[];
}>({
field: options.incmFields,
optionalList: options.additional,
});
// aliases
const hasRequired = options.required.length > 0;
const hasTargets = !!service.target && Object.keys(service.target).length > 0;
const hasOptional = additionalFields.field.length > 0;
const hasNothing =
!hasRequired &&
!hasOptional &&
!hasTargets &&
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={"field-" + opt.id}
option={opt}
value={data.field[opt.id]}
onChange={(v) =>
onUpdate({
...data,
field: {
...data.field,
[opt.id]: v,
},
})
}
/>
))}
{hasTargets && (
<ServiceEditorTarget
key={"target-" + serviceId}
defn={service.target ?? {}}
value={data.target}
onChange={(target) =>
onUpdate({
...data,
target,
})
}
/>
)}
<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,
},
})
}
/>
);
})}
</div>
</>
)}
<hr />
{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,
field: additionalFields.field.concat([newField.id]),
optionalList: additionalFields.optionalList.filter(
(opt) => !(opt.id === newField.id)
),
});
}
}}
options={additionalFields.optionalList}
/>
</div>
)}
</div>
);
};
@@ -0,0 +1,38 @@
import { BaseOption } from "components/Inputs/InputAutoComplete";
import { FieldData, TypedHassService } from "haService/fieldTypes";
import { prettyName } from "utils/formatting";
export type ServiceEditorData = {
field: Record<string, any>;
target: Record<string, any>;
};
export type ServiceEditorOption = BaseOption<{
data: FieldData
}>;
export const convertFieldToOption = (id: string, data: FieldData): ServiceEditorOption => ({
id,
label: data.name ?? prettyName(id),
data,
})
export const splitUpOptions = (service: TypedHassService, data: ServiceEditorData) => {
const required: ServiceEditorOption[] = [];
const additional: ServiceEditorOption[] = [];
const incmFields: string[] = [];
Object.keys(service.fields ?? {}).forEach((key) => {
const serviceData = service.fields[key];
const opt = convertFieldToOption(key, serviceData);
if (serviceData.required) {
required.push(opt);
} else {
if (data.field[opt.id]) {
incmFields.push(opt.id)
} else {
additional.push(opt);
}
}
});
return { required, additional, incmFields };
};
+179
View File
@@ -0,0 +1,179 @@
import { Connection, getCollection } from "home-assistant-js-websocket";
import { useHassCollection } from "./useHassCollection";
import { Option, BaseOption } from "components/Inputs/InputAutoComplete";
import { EntityRegisteryItem, HassEntitiesRegistry } from "./types";
import { prettyName } from "utils/formatting";
export interface AreaRegistryItem {
area_id: string;
name: string;
picture: null | string;
}
export type AreaDB = Record<
string,
AreaRegistryItem & {
domains: Set<string>;
integrations: Set<string>;
}
>;
export const fetchAreaRegistry = (conn: Connection) =>
Promise.all([
conn.sendMessagePromise<AreaRegistryItem[]>({
type: "config/area_registry/list",
}),
conn.sendMessagePromise<HassEntitiesRegistry>({
type: "config/entity_registry/list",
}),
]).then(([areas, er]) => {
const areaDB: AreaDB = areas.reduce<AreaDB>((all, item) => {
return {
...all,
[item.area_id]: {
...item,
domains: new Set(),
integrations: new Set(),
},
};
}, {});
er.forEach((eri) => {
if (eri.area_id) {
if (eri.entity_id) {
areaDB[eri.area_id].domains.add(
eri.entity_id.split(".")[0].toLowerCase()
);
}
if (eri.platform) {
areaDB[eri.area_id].domains.add(eri.platform);
}
}
});
return areaDB;
});
export const areaRegistryColl = (conn: Connection) =>
getCollection<AreaDB>(conn, "_$earg", fetchAreaRegistry);
export type AreaOptionData = {
data: Partial<EntityRegisteryItem>;
};
export type AreaBaseOption = BaseOption<AreaOptionData>;
export type AreaOption = Option<AreaOptionData>;
export const useHAAreas = () => {
const areas = useHassCollection(areaRegistryColl);
const methods = {
areaHasEntityDomain(areaId: string, domains: string[]): boolean {
if (!areas.ready) {
return true;
}
for (const d of domains) {
if (!areas.collection.state[areaId].domains.has(d)) {
return false;
}
}
return true;
},
areaHasEntityIntegration(areaId: string, integrations: string[]): boolean {
if (!areas.ready) {
return true;
}
for (const d of integrations) {
if (!areas.collection.state[areaId].integrations.has(d)) {
return false;
}
}
return true;
},
validateOptions(
options: string[],
restrictedDomains?: string[],
restrictedIntegrations?: string[]
): null | string[] {
let out = options;
if (restrictedDomains) {
const domains = restrictedDomains.map((x) => x.toLowerCase());
const domainsStr =
domains.length > 1
? `one of "${domains.join(", ")}"`
: `"${domains[0]}"`;
out = out.reduce<string[]>((all = [], areaId) => {
if (!methods.areaHasEntityDomain(areaId, domains)) {
return [...all, `${methods.getLabel(areaId)} is not ${domainsStr}`];
}
return all;
}, []);
} else if (restrictedIntegrations) {
const integrations = restrictedIntegrations.map((x) => x.toLowerCase());
const domainsStr =
integrations.length > 1
? `one of "${integrations.join(", ")}"`
: `"${integrations[0]}"`;
out = out.reduce<string[]>((all = [], areaId) => {
if (!methods.areaHasEntityIntegration(areaId, integrations)) {
return [...all, `${methods.getLabel(areaId)} is not ${domainsStr}`];
}
return all;
}, []);
}
if (out.length > 0) {
return out;
}
return null;
},
getBaseOption(opt: AreaOption): AreaBaseOption {
if (!areas.ready) {
throw new Error("Not Ready!");
}
if (typeof opt === "string") {
return {
id: opt,
label: areas.collection.state[opt].name ?? prettyName(opt),
data: areas.collection.state[opt],
};
}
return opt;
},
getOptions(
restrictToDomain?: string[],
restrictedIntegrations?: string[]
): AreaOption[] {
if (!areas.ready) {
return [];
}
let keys = Object.keys(areas.collection.state);
if (restrictToDomain) {
const domains = restrictToDomain.map((x) => x.toLowerCase());
keys = keys.filter((key) => methods.areaHasEntityDomain(key, domains));
}
if (restrictedIntegrations) {
const integrations = restrictedIntegrations.map((x) => x.toLowerCase());
keys = keys.filter((key) =>
methods.areaHasEntityIntegration(key, integrations)
);
}
return keys.map((key) => ({
id: key,
label: areas.collection.state[key].name ?? prettyName(key),
data: areas.collection.state[key],
}));
},
getLabel: (opt: AreaOption): string => {
if (typeof opt === "string") {
if (areas.ready) {
return areas.collection.state[opt].name ?? prettyName(opt);
}
return opt;
}
return opt.label ?? opt.id;
},
getID: (opt: AreaOption): string => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
},
};
return methods;
};
-21
View File
@@ -1,21 +0,0 @@
import { Connection, getCollection } from "home-assistant-js-websocket";
import { DeviceRegistryItem, HassDevices } from './types';
export const fetchDeviceRegistry = (conn: Connection): Promise<Record<string, DeviceRegistryItem>> =>
conn.sendMessagePromise<HassDevices>({
"type": "config/device_registry/list"
}).then(
data =>
data.filter(
({ disabled_by }) => !disabled_by
).reduce<Record<string, DeviceRegistryItem>>((all, n) => {
all[n.id] = n
return all
}, {}
))
export const deviceRegistryColl = (conn: Connection) => getCollection<Record<string, DeviceRegistryItem>>(
conn,
"_$drc",
fetchDeviceRegistry
)
-8
View File
@@ -1,8 +0,0 @@
import { Connection, getCollection } from "home-assistant-js-websocket";
import { HassEntitiesRegistry } from './types';
export const fetchEntityRegistry = (conn: Connection) => conn.sendMessagePromise<HassEntitiesRegistry>({
"type": "config/entity_registry/list"
}).then(data => data.filter(({ disabled_by }) => !disabled_by))
export const entityRegistryColl = (conn: Connection) => getCollection<HassEntitiesRegistry>(conn, "_$erc", fetchEntityRegistry)
+161
View File
@@ -0,0 +1,161 @@
import { Option } from "components/Inputs/InputAutoComplete";
import { useHassCollection } from "./useHassCollection";
import { entitiesColl } from "home-assistant-js-websocket";
import { entitySourceColl } from "./additionalCollections";
export type EntityOption = Option<{ domain: string; integration: string }>;
export type HAEntitiesState = ReturnType<typeof useHAEntities>;
export const useHAEntities = () => {
const entities = useHassCollection(entitiesColl, (state) => ({
domains: Array.from(
new Set(Object.keys(state).map((x) => x.split(".")[0])).keys()
).sort(),
}));
const entitySource = useHassCollection(entitySourceColl);
const methods = {
getStates(inp: string[] | string, attribute?: string): string[] {
if (!entities.ready) {
return [];
}
let entityIds: string[] = [];
if (typeof inp === "string") {
entityIds = [inp];
} else if (Array.isArray(inp)) {
entityIds = inp;
}
let state: Set<string> = new Set();
entityIds.forEach((entityId) => {
if (entities.collection.state[entityId]) {
if (!attribute) {
state.add(entities.collection.state[entityId].state);
} else {
const val = (entities.collection.state[entityId]?.attributes ?? {})[
attribute
];
if (val) {
state.add(val);
}
}
}
});
return Array.from(state.keys());
},
getAttributes(inp: string[] | string): string[] {
if (!entities.ready) {
return [];
}
let entityIds: string[] = [];
if (typeof inp === "string") {
entityIds = [inp];
} else if (Array.isArray(inp)) {
entityIds = inp;
}
let attributes: Set<string> = new Set();
entityIds.forEach((entityId) => {
const thisAttrs = new Set(
Object.keys(entities.collection.state[entityId]?.attributes ?? {})
);
if (attributes.size === 0) {
attributes = thisAttrs;
} else {
attributes = new Set([...attributes].filter((a) => thisAttrs.has(a)));
}
});
return Array.from(attributes.keys());
},
getDomainList(): string[] {
return entities.additional?.domains ?? [];
},
validateOptions(
options: string[],
restrictedDomains?: string[],
restrictedIntegrations?: string[]
): null | string[] {
let out = options;
if (restrictedDomains) {
const domains = restrictedDomains.map((x) => x.toLowerCase());
const domainsStr =
domains.length > 1
? `one of "${domains.join(", ")}"`
: `"${domains[0]}"`;
out = out.reduce<string[]>((all = [], key) => {
if (!domains.includes(key.toLowerCase().split(".")[0])) {
return [...all, `${methods.getLabel(key)} is not ${domainsStr}`];
}
return all;
}, []);
}
if (restrictedIntegrations && entitySource.ready) {
const domains = restrictedIntegrations.map((x) => x.toLowerCase());
const domainsStr =
domains.length > 1
? `one of "${domains.join(", ")}"`
: `"${domains[0]}"`;
out = out.reduce<string[]>((all = [], key) => {
const integration = entitySource.collection.state[key].domain;
if (!domains.includes(integration.toLowerCase())) {
return [...all, `${methods.getLabel(key)} is not ${domainsStr}`];
}
return all;
}, []);
}
if (out.length > 0) {
return out;
}
return null;
},
getOptions(
restrictToDomain?: string[],
restrictedIntegrations?: string[]
): EntityOption[] {
if (!entities.ready) {
return [];
}
let keys = Object.keys(entities.collection.state);
if (restrictToDomain) {
const domains = restrictToDomain.map((x) => x.toLowerCase());
keys = keys.filter((key) =>
domains.includes(key.toLowerCase().split(".")[0])
);
}
if (restrictedIntegrations && entitySource.ready) {
const integrations = restrictedIntegrations.map((x) => x.toLowerCase());
keys = keys.filter((key) => {
const integration = (
entitySource.collection.state[key]?.domain ?? ""
).toLowerCase();
return integrations.includes(integration);
});
}
return keys.map((key) => ({
id: key,
label: entities.collection.state[key].attributes.friendly_name ?? key,
domain: key.split(".")[0] ?? "n/a",
integration: entitySource.ready
? (entitySource.collection.state[key] ?? {}).domain ?? "n/a"
: "...",
}));
},
getLabel: (opt: EntityOption): string => {
if (typeof opt === "string") {
if (entities.ready) {
return (
entities.collection.state[opt]?.attributes.friendly_name ?? opt
);
}
return opt;
}
return opt.label ?? opt.id;
},
getID: (opt: EntityOption): string => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
},
};
return {
...entities,
...methods,
};
};
@@ -0,0 +1,45 @@
import { Connection, getCollection } from "home-assistant-js-websocket";
import {
DeviceRegistryItem,
EntitySource,
HassDevices,
HassEntitiesRegistry,
} from "./types";
export const fetchDeviceRegistry = (
conn: Connection
): Promise<Record<string, DeviceRegistryItem>> =>
conn
.sendMessagePromise<HassDevices>({
type: "config/device_registry/list",
})
.then((data) =>
data
.filter(({ disabled_by }) => !disabled_by)
.reduce<Record<string, DeviceRegistryItem>>((all, n) => {
all[n.id] = n;
return all;
}, {})
);
export const deviceRegistryColl = (conn: Connection) =>
getCollection<Record<string, DeviceRegistryItem>>(
conn,
"_$drc",
fetchDeviceRegistry
);
export const fetchEntityRegistry = (conn: Connection) =>
conn
.sendMessagePromise<HassEntitiesRegistry>({
type: "config/entity_registry/list",
})
.then((data) => data.filter(({ disabled_by }) => !disabled_by));
export const entityRegistryColl = (conn: Connection) =>
getCollection<HassEntitiesRegistry>(conn, "_$erc", fetchEntityRegistry);
export const fetchEntitySource = (conn: Connection) =>
conn.sendMessagePromise<Record<string, EntitySource>>({
type: "entity/source",
});
export const entitySourceColl = (conn: Connection) =>
getCollection<Record<string, EntitySource>>(conn, "_$esc", fetchEntitySource);
+92 -86
View File
@@ -1,101 +1,107 @@
import { useState, useEffect, useRef } from 'react';
import { useState, useEffect, useRef } from "react";
import {
ERR_HASS_HOST_REQUIRED,
createLongLivedTokenAuth,
Connection,
ERR_CANNOT_CONNECT,
ERR_CONNECTION_LOST,
ERR_INVALID_AUTH,
ERR_INVALID_HTTPS_TO_HTTP,
createConnection as _createConnection,
ERR_HASS_HOST_REQUIRED,
createLongLivedTokenAuth,
Connection,
ERR_CANNOT_CONNECT,
ERR_CONNECTION_LOST,
ERR_INVALID_AUTH,
ERR_INVALID_HTTPS_TO_HTTP,
createConnection as _createConnection,
} from "home-assistant-js-websocket";
import { wsURL } from 'apiService';
import { wsURL } from "apiService";
export type HAConnection = {
status: 'loading'
} | {
status: 'loaded',
connection: Connection,
} | {
status: 'error',
error: any,
};
export type HAConnection =
| {
status: "loading";
}
| {
status: "loaded";
connection: Connection;
}
| {
status: "error";
error: any;
};
let haConnection: HAConnection = {
status: 'loading',
status: "loading",
};
const translateErrorCodes = (errorCode: number) => {
if (errorCode === ERR_HASS_HOST_REQUIRED) {
return "Missing HASS host"
}
if (errorCode === ERR_CANNOT_CONNECT) {
return "Failed to connect"
}
if (errorCode === ERR_CONNECTION_LOST) {
return "Connection Lost"
}
if (errorCode === ERR_INVALID_AUTH) {
return "Invalid Host"
}
if (errorCode === ERR_INVALID_HTTPS_TO_HTTP) {
return "Invalid https to http"
}
return errorCode;
}
if (errorCode === ERR_HASS_HOST_REQUIRED) {
return "Missing HASS host";
}
if (errorCode === ERR_CANNOT_CONNECT) {
return "Failed to connect";
}
if (errorCode === ERR_CONNECTION_LOST) {
return "Connection Lost";
}
if (errorCode === ERR_INVALID_AUTH) {
return "Invalid Host";
}
if (errorCode === ERR_INVALID_HTTPS_TO_HTTP) {
return "Invalid https to http";
}
return errorCode;
};
const createConnection = async () => {
try {
return _createConnection({
auth: createLongLivedTokenAuth(wsURL, 'xxx'),
});
} catch (error) {
// eslint-disable-next-line
throw {
originalError: JSON.stringify(error),
message: translateErrorCodes(error as any),
}
}
}
try {
return _createConnection({
auth: createLongLivedTokenAuth(wsURL, "xxx"),
});
} catch (error) {
// eslint-disable-next-line
throw {
originalError: JSON.stringify(error),
message: translateErrorCodes(error as any),
};
}
};
async function startHAConnection() {
let connection: Connection;
try {
connection = await createConnection();
} catch (error) {
haConnection = {
status: 'error',
error: {
originalError: JSON.stringify(error),
message: translateErrorCodes(error as any),
}
}
throw error
}
let connection: Connection;
try {
connection = await createConnection();
} catch (error) {
haConnection = {
status: 'loaded',
connection,
}
return haConnection;
status: "error",
error: {
originalError: JSON.stringify(error),
message: translateErrorCodes(error as any),
},
};
throw error;
}
haConnection = {
status: "loaded",
connection,
};
return haConnection;
}
startHAConnection().then(console.log).catch(console.error);
startHAConnection().then(console.info).catch(console.error);
export const useHAConnection = (): HAConnection => {
const [conn, setConn] = useState<HAConnection>(haConnection);
const timeID = useRef<number | undefined>(undefined);
useEffect(() => {
if (conn.status !== haConnection.status) {
setConn(haConnection);
}
const waiter = () => {
if (conn.status !== haConnection.status) {
setConn(haConnection);
}
timeID.current = window.setTimeout(() => {
waiter()
}, conn.status === 'loading' ? 500 : 5000)
}
waiter()
return () => window.clearTimeout(timeID.current)
}, [conn, setConn])
return conn;
};
const [conn, setConn] = useState<HAConnection>(haConnection);
const timeID = useRef<number | undefined>(undefined);
useEffect(() => {
if (conn.status !== haConnection.status) {
setConn(haConnection);
}
const waiter = () => {
if (conn.status !== haConnection.status) {
setConn(haConnection);
}
timeID.current = window.setTimeout(
() => {
waiter();
},
conn.status === "loading" ? 500 : 5000
);
};
waiter();
return () => window.clearTimeout(timeID.current);
}, [conn, setConn]);
return conn;
};
+17 -18
View File
@@ -1,26 +1,25 @@
import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useHAEntities } from "haService";
import { useHAEntities } from "haService/HAEntities";
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
const conn = useHAEntities();
onRender && onRender()
return <code>
{JSON.stringify(conn, null, 4)}
</code>
}
const conn = useHAEntities();
onRender && onRender();
return <code>{JSON.stringify(conn, null, 4)}</code>;
};
export default {
title: 'Services/HA Entities',
component: Test,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {}
} as ComponentMeta<typeof Test>
title: "Services/HA Entities",
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>
};
);
};
+146
View File
@@ -0,0 +1,146 @@
import { BaseOption } from "components/Inputs/InputAutoComplete";
import { MessageBase } from "home-assistant-js-websocket";
import { useEffect, useRef, useState } from "react";
import { prettyName } from "utils/formatting";
import {
DeviceConditionType,
DeviceTriggerType,
DeviceTypeAction,
DeviceTypeCapability,
HASendMessage,
} from "./types";
export const makeCreateUseThing = (callHA: HASendMessage) =>
function <Args, HAData, STData>(
convertArgsToMessage: (a: Args) => MessageBase,
transformHAData: (ha: HAData) => STData,
defaultSTData: STData
) {
return function useThis(args?: Args) {
const lastThing = useRef<string | null>(null);
const [stData, setStData] = useState<STData>(defaultSTData);
useEffect(() => {
const currentThing = JSON.stringify(args);
if (args && currentThing && lastThing.current !== currentThing) {
lastThing.current = currentThing;
const msg = convertArgsToMessage(args);
callHA(msg)
.then((raw: HAData) => {
if (lastThing.current === currentThing) {
setStData(transformHAData(raw));
}
})
.catch((error) => {
console.warn({ msg, args, currentThing, error });
});
} else if (lastThing.current !== currentThing) {
lastThing.current = currentThing;
setStData(defaultSTData);
}
}, [args]);
return stData;
};
};
export const getDeviceExtraWsCalls = (callHA: HASendMessage) => {
const createUseThing = makeCreateUseThing(callHA);
const reduceDeviceThings = function <
Raw extends { type: string; subtype?: string; entity_id?: string }
>(raw: Raw[]) {
return raw.reduce<Record<string, BaseOption<{ data: Raw[] }>>>(
(all, opt: Raw) => {
const id = opt.type + (opt.subtype ?? "");
if (!all[id]) {
return {
...all,
[id]: {
id,
label:
prettyName(opt.type) + (opt.subtype ? ` ${opt.subtype}` : ""),
data: [opt],
},
};
} else {
all[id].data.push(opt);
return all;
}
},
{}
);
};
return {
useDeviceActions: createUseThing<
{ deviceId: string },
DeviceTypeAction[],
Record<string, BaseOption<{ data: DeviceTypeAction[] }>>
>(
({ deviceId }) => ({
type: "device_automation/action/list",
device_id: deviceId,
}),
reduceDeviceThings,
{}
),
useDeviceCapalities: createUseThing<
DeviceTypeAction,
DeviceTypeCapability,
Partial<DeviceTypeCapability>
>(
(action) => ({
type: "device_automation/action/capabilities",
action,
}),
(data) => data,
{}
),
useDeviceTriggerCapalities: createUseThing<
DeviceTypeAction,
DeviceTypeCapability,
Partial<DeviceTypeCapability>
>(
(trigger) => ({
type: "device_automation/trigger/capabilities",
trigger,
}),
(data) => data,
{}
),
useDeviceTriggers: createUseThing<
{ deviceId: string },
DeviceTriggerType[],
Record<string, BaseOption<{ data: DeviceTriggerType[] }>>
>(
({ deviceId }) => ({
type: "device_automation/trigger/list",
device_id: deviceId,
}),
reduceDeviceThings,
{}
),
useDeviceConditionCapalities: createUseThing<
DeviceTypeAction,
DeviceTypeCapability,
Partial<DeviceTypeCapability>
>(
(condition) => ({
type: "device_automation/condition/capabilities",
condition,
}),
(data) => data,
{}
),
useDeviceConditions: createUseThing<
{ deviceId: string },
DeviceConditionType[],
Record<string, BaseOption<{ data: DeviceConditionType[] }>>
>(
({ deviceId }) => ({
type: "device_automation/condition/list",
device_id: deviceId,
}),
reduceDeviceThings,
{}
),
};
};
+69
View File
@@ -0,0 +1,69 @@
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;
}
export interface SelectorColorTemp {
min_mireds: number;
max_mireds: number;
}
export interface SelectorNumber {
min: number;
max: number;
unit_of_measurement?: string;
mode?: "box";
step?: number;
}
interface SelectorSelect {
options: OptionElement[];
}
type OptionElement = OptionClass | string;
interface OptionClass {
label: string;
value: string;
}
export interface SelectorText {
multiline: boolean;
}
+217 -173
View File
@@ -1,190 +1,234 @@
import { entitiesColl, servicesColl } from "home-assistant-js-websocket"
import { servicesColl } from "home-assistant-js-websocket";
import { Namer } from "utils/formatting";
import { deviceRegistryColl } from "./DeviceRegistry";
import { entityRegistryColl } from "./EntityRegistry";
import { DeviceRegistryItem } from "./types";
import { useHassCollection } from "./useHassCollection"
import {
deviceRegistryColl,
entityRegistryColl,
} from "./additionalCollections";
import { DeviceRegistryItem, HASendMessage } from "./types";
import { useHassCollection } from "./useHassCollection";
import { useHAConnection } from "./connection";
import { useSnackbar } from "notistack";
import { TypedHassService } from "./fieldTypes";
import { Option } from "components/Inputs/InputAutoComplete";
import { getDeviceExtraWsCalls } from "./extras";
import { useHAEntities } from "./HAEntities";
export type Option<T = {}> = string | ({
id: string,
label: string,
} & T)
export type EntityOption = Option<{ domain: string; }>
export type HAEntitiesState = ReturnType<typeof useHAEntities>;
export const useHAEntities = () => {
const entities = useHassCollection(entitiesColl, state => ({
domains: Array.from(new Set(Object.keys(state).map(x => x.split('.')[0])).keys()).sort(),
}));
const methods = {
getDomainList(): string[] {
return entities.additional?.domains ?? []
},
validateOptions(options: string[], restrictedDomains?: string[]): null | string[] {
if (restrictedDomains) {
const domains = restrictedDomains.map(x => x.toLowerCase())
const domainsStr = domains.length > 1 ?
`one of "${domains.join(', ')}"` :
`"${domains[0]}"`
return options.reduce<string[]>((all = [], key) => {
if (!domains.includes(key.toLowerCase().split('.')[0])) {
return [
...all,
`${methods.getLabel(key)} is not ${domainsStr}`
]
}
return all
}, [])
}
return null
},
getOptions(restrictToDomain?: string[]): EntityOption[] {
if (!entities.ready) {
return []
}
let keys = Object.keys(entities.collection.state);
if (restrictToDomain) {
const domains = restrictToDomain.map(x => x.toLowerCase())
keys = keys.filter(key => domains.includes(key.toLowerCase().split('.')[0]))
}
return keys.map(key => ({
id: key,
label: entities.collection.state[key].attributes.friendly_name ?? key,
domain: key.split('.')[0] ?? "n/a",
}))
},
getLabel: (opt: EntityOption): string => {
if (typeof opt === 'string') {
if (entities.ready) {
return entities.collection.state[opt]?.attributes.friendly_name ?? opt;
}
return opt
}
return opt.label ?? opt.id
},
getID: (opt: EntityOption): string => {
if (typeof opt === 'string') {
return opt
}
return opt.id
}
}
return {
...entities,
...methods
}
}
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 = {
getOptions(): ServiceOption[] {
if (!services.ready) {
return []
}
return Object.keys(services.collection.state).reduce<ServiceOption[]>((all, domain) => {
const opts = Object.keys(services.collection.state[domain]).map<ServiceOption>(
action => ({
id: `${domain}.${action}`,
label: services.collection.state[domain][action].name ?? `${domain}.${action}`,
description: services.collection.state[domain][action].description ?? "",
domain,
action,
})
)
return all.concat(opts);
}, [])
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 [];
}
return Object.keys(services.collection.state).reduce<ServiceOption[]>(
(all, domain) => {
const opts = Object.keys(
services.collection.state[domain]
).map<ServiceOption>((action) => ({
id: `${domain}.${action}`,
label:
services.collection.state[domain][action].name ??
`${domain}.${action}`,
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);
},
getLabel: (opt: ServiceOption): string => {
if (typeof opt === 'string') {
if (services.ready) {
try {
const [domain, action] = opt.split('.');
return services.collection.state[domain][action].name ?? opt;
} catch (_) { }
}
return opt
}
return opt.label ?? opt.id
},
getID: (opt: DeviceRegistryOption): string => {
if (typeof opt === 'string') {
return opt
}
return opt.id
[]
);
},
getLabel: (opt: ServiceOption): string => {
if (typeof opt === "string") {
if (services.ready) {
try {
const [domain, action] = opt.split(".");
return services.collection.state[domain][action].name ?? opt;
} catch (_) {}
}
}
return opt;
}
return opt.label ?? opt.id;
},
getID: (opt: ServiceOption): string => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
},
};
return { ...services, ...methods }
}
return { ...services, ...methods };
};
export type DeviceRegistryOption = Option<{ manufacturer: string }>;
export type HADeviceRegistry = ReturnType<typeof useHADeviceRegistry>;
export const useHADeviceRegistry = () => {
const dr = useHassCollection(deviceRegistryColl)
const getLabelForItem = (item: DeviceRegistryItem) => item ? item.name_by_user ??
item.name ??
item.id :
"";
const methods = {
getOptions(): DeviceRegistryOption[] {
if (!dr.ready) {
return []
}
const keys = Object.keys(dr.collection.state);
return keys.map(key => ({
id: key,
label: getLabelForItem(dr.collection.state[key]) ?? key,
manufacturer: dr.collection.state[key].manufacturer ?? "",
}))
},
getLabel: (opt: DeviceRegistryOption): string => {
if (typeof opt === 'string') {
if (dr.ready) {
return getLabelForItem(dr.collection.state[opt]) ?? opt
}
return opt
}
return opt.label ?? opt.id
},
getID: (opt: DeviceRegistryOption): string => {
if (typeof opt === 'string') {
return opt
}
return opt.id
const dr = useHassCollection(deviceRegistryColl);
const getLabelForItem = (item: DeviceRegistryItem) =>
item ? item.name_by_user ?? item.name ?? item.id : "";
const methods = {
getOptions(): DeviceRegistryOption[] {
if (!dr.ready) {
return [];
}
const keys = Object.keys(dr.collection.state);
return keys.map((key) => ({
id: key,
label: getLabelForItem(dr.collection.state[key]) ?? key,
manufacturer: dr.collection.state[key].manufacturer ?? "",
}));
},
getLabel: (opt: DeviceRegistryOption): string => {
if (typeof opt === "string") {
if (dr.ready) {
return getLabelForItem(dr.collection.state[opt]) ?? opt;
}
}
return { ...dr, ...methods }
}
return opt;
}
return opt.label ?? opt.id;
},
getID: (opt: DeviceRegistryOption): string => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
},
};
return { ...dr, ...methods };
};
export const useHAEntityRegistry = () => {
const dr = useHassCollection(entityRegistryColl)
return dr
}
const dr = useHassCollection(entityRegistryColl);
return dr;
};
export type HAService = ReturnType<typeof useHA>;
export const useHA = () => {
const entities = useHAEntities();
const devices = useHADeviceRegistry();
const services = useHAServices();
const entities = useHAEntities();
const devices = useHADeviceRegistry();
const services = useHAServices();
const conn = useHAConnection();
const { enqueueSnackbar } = useSnackbar();
const namer: Namer = {
getDeviceName(device_id) {
return devices.getLabel(device_id)
},
getEntityName(entity_id, maxEntities = 1) {
if (Array.isArray(entity_id)) {
return entity_id.slice(0, maxEntities).map(entities.getLabel).join(', ')
}
return entities.getLabel(entity_id)
},
getServiceName(service) {
return services.getLabel(service)
},
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",
}
);
}
};
return {
entities,
devices,
services,
namer,
const callHA: HASendMessage = async (sendMsg) => {
if (conn.status === "loaded") {
return await conn.connection.sendMessagePromise(sendMsg);
}
}
};
const namer: Namer = {
getDeviceName(device_id) {
return devices.getLabel(device_id);
},
getEntityName(entity_id, maxEntities = 1) {
if (Array.isArray(entity_id)) {
return entity_id
.slice(0, maxEntities)
.map(entities.getLabel)
.join(", ");
}
return entities.getLabel(entity_id);
},
getServiceName(service) {
return services.getLabel(service);
},
};
return {
entities,
devices,
services,
namer,
callService,
callHA,
deviceExtras: getDeviceExtraWsCalls(callHA),
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.info(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>
};
);
};
+111 -35
View File
@@ -1,40 +1,116 @@
import { MessageBase } from "home-assistant-js-websocket";
import { AutomationDeviceState } from "types/automations/common";
export type EntityRegisteryItem = {
area_id: string | null;
config_entry_id: string | null;
device_id: string | null;
disabled_by:
| "integration"
| "user"
| "config_entry"
| string
| null
;
entity_category:
| "diagnostic"
| "config"
| string
| null
;
hidden_by:
| "integration"
| "user"
| string
| null
;
icon: string | null;
name: string | null;
platform: string | null;
}
area_id: null | string;
config_entry_id: null | string;
device_id: null | string;
disabled_by: "integration" | "user" | "config_entry" | string | null;
entity_category: "diagnostic" | "config" | string | null;
hidden_by: "integration" | "user" | string | null;
entity_id: string;
icon: null | string;
name: null | string;
platform: string;
};
export type DeviceRegistryItem = {
id: string;
name: string;
name_by_user: string | null;
manufacturer: string | null;
entry_type: 'service' | string | null;
disabled_by: EntityRegisteryItem['disabled_by'];
area_id: string | null;
}
id: string;
name: string;
name_by_user: string | null;
manufacturer: string | null;
entry_type: "service" | string | null;
disabled_by: EntityRegisteryItem["disabled_by"];
area_id: string | null;
};
export type HassDevices = Array<DeviceRegistryItem>;
export type HassEntitiesRegistry = Array<EntityRegisteryItem>;
export type HassEntitiesRegistry = Array<EntityRegisteryItem>;
export type HASendMessage = (sendMsg: MessageBase) => Promise<any>;
export type DeviceBaseType = AutomationDeviceState & {
metadata: Record<string, any>;
} & Record<string, any>;
export type DeviceTypeAction = DeviceBaseType;
export type DeviceTriggerType = DeviceBaseType & {
platform: "device";
};
export type DeviceConditionType = DeviceBaseType & {
condition: "device";
};
export type DeviceTypeCapability = {
extra_fields: Array<HaFormSchema>;
};
export type HaFormSchema =
| HaFormConstantSchema
| HaFormStringSchema
| HaFormIntegerSchema
| HaFormFloatSchema
| HaFormBooleanSchema
| HaFormSelectSchema
| HaFormMultiSelectSchema
| HaFormTimeSchema
| HaFormGridSchema;
export interface HaFormBaseSchema {
name: string;
default?: any;
required?: boolean;
description?: {
suffix?: string;
suggested_value?: any;
};
}
export interface HaFormGridSchema extends HaFormBaseSchema {
type: "grid";
name: "";
column_min_width?: string;
schema: HaFormSchema[];
}
export interface HaFormConstantSchema extends HaFormBaseSchema {
type: "constant";
value?: string;
}
export interface HaFormIntegerSchema extends HaFormBaseSchema {
type: "integer";
valueMin?: number;
valueMax?: number;
}
export interface HaFormSelectSchema extends HaFormBaseSchema {
type: "select";
options: Array<[string, string]>;
}
export interface HaFormMultiSelectSchema extends HaFormBaseSchema {
type: "multi_select";
options: Record<string, string> | string[] | Array<[string, string]>;
}
export interface HaFormFloatSchema extends HaFormBaseSchema {
type: "float";
}
export interface HaFormStringSchema extends HaFormBaseSchema {
type: "string";
format?: string;
}
export interface HaFormBooleanSchema extends HaFormBaseSchema {
type: "boolean";
}
export interface HaFormTimeSchema extends HaFormBaseSchema {
type: "positive_time_period_dict";
}
export interface EntitySource {
domain: string;
custom_component: boolean;
source: "config_entry" | "platform_config";
config_entry?: string;
}
+9 -10
View File
@@ -1,25 +1,24 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './styles/root.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import React from "react";
import ReactDOM from "react-dom";
import "./styles/root.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// to log results (for example: reportWebVitals(console.info))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
reportWebVitals(console.info);
// import { createRoot } from 'react-dom/client';
// const container = document.getElementById('root');
// const root = createRoot(container!);
// root.render(<React.StrictMode>
// <App />
// </React.StrictMode>);
// </React.StrictMode>);
+6 -5
View File
@@ -1,7 +1,8 @@
import * as st from 'superstruct'
import * as st from "superstruct";
import * as v from "types/validators/common";
export type AutomationTime = st.Infer<typeof v.AutomationTime>
export type AutomationTimeObject = st.Infer<typeof v.AutomationTimeObject>
export type AutomationTimeString = st.Infer<typeof v.AutomationTimeString>
export type EntityId = st.Infer<typeof v.EntityId>;
export type AutomationTime = st.Infer<typeof v.AutomationTime>;
export type AutomationTimeObject = st.Infer<typeof v.AutomationTimeObject>;
export type AutomationTimeString = st.Infer<typeof v.AutomationTimeString>;
export type EntityId = st.Infer<typeof v.EntityId>;
export type AutomationDeviceState = st.Infer<typeof v.AutomationDeviceState>;
+18 -15
View File
@@ -1,26 +1,29 @@
import { AutomationTime } from "./common";
import * as st from 'superstruct';
import * as st from "superstruct";
import * as v from "types/validators/conditions";
type AutomationConditionNodeBase<Name extends String, Data extends Object> = {
condition: Name;
enabled?: boolean;
condition: Name;
enabled?: boolean;
} & Data;
export type LogicCondition = AutomationConditionNodeBase<'and' | 'or' | 'not', {
export type LogicCondition = AutomationConditionNodeBase<
"and" | "or" | "not",
{
conditions: AutomationCondition[];
}>;
}
>;
export type NumericCondition = st.Infer<typeof v.NumericCondition>;
export type DeviceCondition = st.Infer<typeof v.DeviceCondition>;
export type StateCondition = st.Infer<typeof v.StateCondition>;
export type TemplateCondition = st.Infer<typeof v.TemplateCondition>;
export type TimeCondition = st.Infer<typeof v.TimeCondition>;
export type TriggerCondition = st.Infer<typeof v.TriggerCondition>;
export type ZoneCondition = st.Infer<typeof v.ZoneCondition>;
export type AutomationCondition =
| LogicCondition
| NumericCondition
| StateCondition
| TemplateCondition
| TimeCondition
| TriggerCondition
| ZoneCondition
;
export type ConditionType = AutomationCondition['condition'];
| LogicCondition
| DeviceCondition
| NumericCondition
| StateCondition
| TemplateCondition
| TimeCondition
| TriggerCondition
| ZoneCondition;
export type ConditionType = AutomationCondition["condition"];
+48 -55
View File
@@ -1,78 +1,71 @@
import * as st from 'superstruct'
import { AutomationTime } from './common';
import { AutomationTrigger } from './triggers';
import * as st from "superstruct";
import { AutomationDeviceState, AutomationTime } from "./common";
import { AutomationTrigger } from "./triggers";
export const AutomationActionNodeBase = st.type({
alias: st.optional(st.string()),
variables: st.optional(st.record(st.string(), st.any())),
enabled: st.optional(st.boolean())
})
alias: st.optional(st.string()),
variables: st.optional(st.record(st.string(), st.any())),
enabled: st.optional(st.boolean()),
});
export const ServiceAction = st.intersection([
AutomationActionNodeBase,
st.type({
data: st.any(),
target: st.any(),
service: st.string(),
})
AutomationActionNodeBase,
st.type({
data: st.any(),
target: st.any(),
service: st.string(),
}),
]);
export const RepeatAction = st.intersection([
AutomationActionNodeBase,
st.type({
repeat: st.object({
count: st.number(),
sequence: st.array(st.object()),
})
})
AutomationActionNodeBase,
st.type({
repeat: st.object({
count: st.number(),
sequence: st.array(st.object()),
}),
}),
]);
export const WaitAction = st.intersection([
AutomationActionNodeBase,
st.type({
timeout: st.optional(AutomationTime),
continue_on_timeout: st.optional(st.boolean()),
wait_template: st.optional(st.string()),
wait_for_trigger: st.optional(st.array(AutomationTrigger)),
}),
AutomationActionNodeBase,
st.type({
timeout: st.optional(AutomationTime),
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
})
AutomationActionNodeBase,
st.type({
delay: AutomationTime,
}),
]);
export const FireEventAction = st.intersection([
AutomationActionNodeBase,
st.type({
event: st.string(),
event_data: st.any(),
})
AutomationActionNodeBase,
st.type({
event: st.string(),
event_data: st.any(),
}),
]);
export const DeviceAction = st.intersection([
AutomationActionNodeBase,
st.type({
type: st.optional(st.string()),
device_id: st.optional(st.string()),
entity_id: st.optional(st.string()),
domain: st.optional(st.string()),
})
AutomationActionNodeBase,
st.partial(AutomationDeviceState),
]);
export const ChooseAction = st.intersection([
AutomationActionNodeBase,
st.type({
choose: st.array(st.type({
conditions: st.array(st.object()),
sequence: st.array(st.object()),
})),
default: st.optional(st.array(st.object())),
})
AutomationActionNodeBase,
st.type({
choose: st.array(
st.type({
conditions: st.array(st.object()),
sequence: st.array(st.object()),
})
),
default: st.optional(st.array(st.object())),
}),
]);
+49 -44
View File
@@ -1,52 +1,57 @@
import * as st from 'superstruct'
import * as st from "superstruct";
export const EntityId = st.union([
st.string(),
st.array(st.string()),
])
export const AutomationTimeString = st.refine(st.string(), 'TimeString', (v, c) => {
export const EntityId = st.union([st.string(), st.array(st.string())]);
export const AutomationTimeString = st.refine(
st.string(),
"TimeString",
(v, c) => {
// https://www.home-assistant.io/docs/automation/trigger/#time-string
const bits: string[] = v.split(':')
if ((bits.length !== 2) && (bits.length !== 3)) {
return {
"branch": c.branch,
"message": "Time string should be either in the form 'HH:MM' or 'HH:MM:SS' as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string",
"path": c.path,
}
const bits: string[] = v.split(":");
if (bits.length !== 2 && bits.length !== 3) {
return {
branch: c.branch,
message:
"Time string should be either in the form 'HH:MM' or 'HH:MM:SS' as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string",
path: c.path,
};
}
for (let i = 0; i < bits.length; i++) {
const b = bits[i];
const num = Number(b);
if (Number.isInteger(num)) {
let max = 23;
if (i > 0) {
max = 59;
}
if ((num < 0) || (num > max)) {
return {
"branch": c.branch,
"message": `Time string should contain only positive numbers between 0-${max} as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`,
"path": c.path.concat(
bits.slice(0, i)
).concat([`<<${b}>>`])
}
}
} else {
return {
"branch": c.branch,
"message": `Time string should contain only positive numbers as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`,
"path": c.path.concat(
bits.slice(0, i)
).concat([`<<${b}>>`])
}
const b = bits[i];
const num = Number(b);
if (Number.isInteger(num)) {
let max = 23;
if (i > 0) {
max = 59;
}
if (num < 0 || num > max) {
return {
branch: c.branch,
message: `Time string should contain only positive numbers between 0-${max} as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`,
path: c.path.concat(bits.slice(0, i)).concat([`<<${b}>>`]),
};
}
} else {
return {
branch: c.branch,
message: `Time string should contain only positive numbers as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`,
path: c.path.concat(bits.slice(0, i)).concat([`<<${b}>>`]),
};
}
}
return true
})
return true;
}
);
export const AutomationTimeObject = st.object({
hours: st.optional(st.number()),
minutes: st.optional(st.number()),
seconds: st.optional(st.number()),
milliseconds: st.optional(st.number()),
hours: st.optional(st.number()),
minutes: st.optional(st.number()),
seconds: st.optional(st.number()),
milliseconds: st.optional(st.number()),
});
export const AutomationTime = st.union([st.string(), AutomationTimeObject]);
export const AutomationDeviceState = st.type({
subtype: st.optional(st.string()),
entity_id: st.optional(st.string()),
type: st.string(),
device_id: st.string(),
domain: st.string(),
});
export const AutomationTime = st.union([st.string(), AutomationTimeObject])
+72 -68
View File
@@ -1,71 +1,75 @@
import * as st from 'superstruct'
import { AutomationTime, EntityId } from './common';
import * as st from "superstruct";
import { AutomationDeviceState, AutomationTime, EntityId } from "./common";
export const AutomationConditionNodeBase = st.type({
enabled: st.optional(st.boolean())
enabled: st.optional(st.boolean()),
});
export const LogicCondition = st.intersection([
AutomationConditionNodeBase,
st.type({
condition: st.enums(['and', 'or', 'not']),
conditions: st.array(st.object())
})
])
export const NumericCondition = st.intersection([
AutomationConditionNodeBase,
st.type({
condition: st.literal('numeric_state'),
entity_id: EntityId,
above: st.optional(st.string()),
below: st.optional(st.string()),
attribute: st.optional(st.string()),
value_template: st.optional(st.string()),
})
]);
export const StateCondition = st.intersection([
AutomationConditionNodeBase,
st.type({
condition: st.literal('state'),
entity_id: EntityId,
state: st.union([st.array(st.string()), st.string()]),
for: st.optional(AutomationTime),
attribute: st.optional(st.string()),
})
]);
export const TemplateCondition = st.intersection([
AutomationConditionNodeBase,
st.type({
condition: st.literal('template'),
value_template: st.string(),
})
]);
export const TriggerCondition = st.intersection([
AutomationConditionNodeBase,
st.type({
condition: st.literal('trigger'),
id: st.string(),
})
]);
export const TimeCondition = st.intersection([
AutomationConditionNodeBase,
st.type({
condition: st.literal('time'),
after: st.optional(AutomationTime),
before: st.optional(AutomationTime),
weekday: st.optional(st.enums([
'mon', 'tue', 'wed',
'thu', 'fri', 'sat',
'sun',
]))
})
]);
export const ZoneCondition = st.intersection([
AutomationConditionNodeBase,
st.type({
condition: st.literal('zone'),
zone: st.string(),
entity_id: EntityId,
state: st.union([st.array(st.string()), st.string()]),
})
]);
export const LogicCondition = st.assign(
AutomationConditionNodeBase,
st.type({
condition: st.enums(["and", "or", "not"]),
conditions: st.array(st.object()),
})
);
export const NumericCondition = st.assign(
AutomationConditionNodeBase,
st.type({
condition: st.literal("numeric_state"),
entity_id: EntityId,
above: st.optional(st.string()),
below: st.optional(st.string()),
attribute: st.optional(st.string()),
value_template: st.optional(st.string()),
})
);
export const StateCondition = st.assign(
AutomationConditionNodeBase,
st.type({
condition: st.literal("state"),
entity_id: EntityId,
state: st.union([st.array(st.string()), st.string()]),
for: st.optional(AutomationTime),
attribute: st.optional(st.string()),
})
);
export const DeviceCondition = st.assign(
AutomationConditionNodeBase,
st.type({
condition: st.literal("device"),
}),
AutomationDeviceState
);
export const TemplateCondition = st.assign(
AutomationConditionNodeBase,
st.type({
condition: st.literal("template"),
value_template: st.string(),
})
);
export const TriggerCondition = st.assign(
AutomationConditionNodeBase,
st.type({
condition: st.literal("trigger"),
id: st.string(),
})
);
export const TimeCondition = st.assign(
AutomationConditionNodeBase,
st.type({
condition: st.literal("time"),
after: st.optional(AutomationTime),
before: st.optional(AutomationTime),
weekday: st.optional(
st.enums(["mon", "tue", "wed", "thu", "fri", "sat", "sun"])
),
})
);
export const ZoneCondition = st.assign(
AutomationConditionNodeBase,
st.type({
condition: st.literal("zone"),
zone: st.string(),
entity_id: EntityId,
state: st.union([st.array(st.string()), st.string()]),
})
);
+91 -91
View File
@@ -1,119 +1,119 @@
import * as st from 'superstruct'
import { AutomationTimeString, AutomationTime, EntityId } from './common'
import * as st from "superstruct";
import {
AutomationTimeString,
AutomationTime,
AutomationDeviceState,
} from "./common";
const AutomationTriggerBase = {
id: st.optional(st.string()),
enabled: st.optional(st.boolean()),
}
id: st.optional(st.string()),
enabled: st.optional(st.boolean()),
};
export const AutomationTriggerEvent = st.type({
...AutomationTriggerBase,
platform: st.literal('event'),
event_type: st.union([st.string(), st.array(st.string())]),
event_data: st.any(),
context: st.any(),
})
...AutomationTriggerBase,
platform: st.literal("event"),
event_type: st.union([st.string(), st.array(st.string())]),
event_data: st.any(),
context: st.any(),
});
export const AutomationTriggerHA = st.type({
...AutomationTriggerBase,
platform: st.literal('homeassistant'),
event: st.enums(['start', 'shutdown']),
})
...AutomationTriggerBase,
platform: st.literal("homeassistant"),
event: st.enums(["start", "shutdown"]),
});
export const AutomationTriggerMQTT = st.type({
...AutomationTriggerBase,
platform: st.literal('mqtt'),
topic: st.string(),
payload: st.string(),
value_template: st.string(),
})
...AutomationTriggerBase,
platform: st.literal("mqtt"),
topic: st.string(),
payload: st.string(),
value_template: st.string(),
});
export const AutomationTriggerNumericState = st.type({
...AutomationTriggerBase,
platform: st.literal('numeric_state'),
entity_id: st.union([st.string(), st.array(st.string())]),
attribute: st.optional(st.string()),
value_template: st.optional(st.string()),
above: st.optional(st.string()),
below: st.optional(st.string()),
for: st.optional(AutomationTime),
})
...AutomationTriggerBase,
platform: st.literal("numeric_state"),
entity_id: st.union([st.string(), st.array(st.string())]),
attribute: st.optional(st.string()),
value_template: st.optional(st.string()),
above: st.optional(st.string()),
below: st.optional(st.string()),
for: st.optional(AutomationTime),
});
export const AutomationTriggerState = st.type({
...AutomationTriggerBase,
platform: st.literal('state'),
entity_id: st.union([st.string(), st.array(st.string())]),
attribute: st.optional(st.string()),
from: st.optional(st.string()),
to: st.optional(st.string()),
for: st.optional(AutomationTime),
})
...AutomationTriggerBase,
platform: st.literal("state"),
entity_id: st.union([st.string(), st.array(st.string())]),
attribute: st.optional(st.string()),
from: st.optional(st.string()),
to: st.optional(st.string()),
for: st.optional(AutomationTime),
});
export const AutomationTriggerTag = st.type({
...AutomationTriggerBase,
platform: st.literal('tag'),
tag_id: st.string(),
device_id: st.union([st.string(), st.array(st.string())]),
})
...AutomationTriggerBase,
platform: st.literal("tag"),
tag_id: st.string(),
device_id: st.union([st.string(), st.array(st.string())]),
});
export const AutomationTriggerTemplate = st.type({
...AutomationTriggerBase,
platform: st.literal('template'),
value_template: st.string(),
for: st.optional(AutomationTime),
})
...AutomationTriggerBase,
platform: st.literal("template"),
value_template: st.string(),
for: st.optional(AutomationTime),
});
export const AutomationTriggerTime = st.type({
...AutomationTriggerBase,
platform: st.literal('time'),
at: AutomationTimeString,
})
...AutomationTriggerBase,
platform: st.literal("time"),
at: AutomationTimeString,
});
export const AutomationTriggerTimePattern = st.type({
...AutomationTriggerBase,
platform: st.literal('time_pattern'),
hours: st.optional(st.string()),
minutes: st.optional(st.string()),
seconds: st.optional(st.string()),
})
...AutomationTriggerBase,
platform: st.literal("time_pattern"),
hours: st.optional(st.string()),
minutes: st.optional(st.string()),
seconds: st.optional(st.string()),
});
export const AutomationTriggerWebhook = st.type({
...AutomationTriggerBase,
platform: st.literal('webhook'),
webhook_id: st.string(),
})
...AutomationTriggerBase,
platform: st.literal("webhook"),
webhook_id: st.string(),
});
export const AutomationTriggerZone = st.type({
...AutomationTriggerBase,
platform: st.literal('zone'),
entity_id: st.union([st.string(), st.array(st.string())]),
zone: st.string(),
event: st.enums(['enter', 'leave'])
})
...AutomationTriggerBase,
platform: st.literal("zone"),
entity_id: st.union([st.string(), st.array(st.string())]),
zone: st.string(),
event: st.enums(["enter", "leave"]),
});
export const AutomationTriggerDevice = st.type({
export const AutomationTriggerDevice = st.assign(
st.partial(AutomationDeviceState),
st.type({
...AutomationTriggerBase,
platform: st.literal('device'),
entity_id: st.optional(EntityId),
device_id: st.optional(st.string()),
domain: st.optional(st.string()),
type: st.optional(st.string()),
subtype: st.optional(st.string()),
})
platform: st.literal("device"),
})
);
export const AutomationTrigger = st.union([
AutomationTriggerEvent,
AutomationTriggerHA,
AutomationTriggerMQTT,
AutomationTriggerNumericState,
AutomationTriggerState,
AutomationTriggerTag,
AutomationTriggerTemplate,
AutomationTriggerTime,
AutomationTriggerTimePattern,
AutomationTriggerWebhook,
AutomationTriggerZone,
AutomationTriggerDevice
])
AutomationTriggerEvent,
AutomationTriggerHA,
AutomationTriggerMQTT,
AutomationTriggerNumericState,
AutomationTriggerState,
AutomationTriggerTag,
AutomationTriggerTemplate,
AutomationTriggerTime,
AutomationTriggerTimePattern,
AutomationTriggerWebhook,
AutomationTriggerZone,
AutomationTriggerDevice,
]);
+221 -179
View File
@@ -1,196 +1,238 @@
import * as v from "types/validators";
import { AutomationNode, AutomationNodeMapping, AutomationNodeSubtype, AutomationNodeTypes } from "types/automations";
import { AutomationTrigger, TriggerType } from 'types/automations/triggers';
import {
AutomationNode,
AutomationNodeMapping,
AutomationNodeSubtype,
AutomationNodeTypes,
} from "types/automations";
import { AutomationTrigger, TriggerType } from "types/automations/triggers";
import { MiniFailure } from "types/validators/helper";
import { getFailures } from '../types/validators/helper';
import { getFailures } from "../types/validators/helper";
import { ActionType } from "types/automations/actions";
import { ConditionType } from "types/automations/conditions";
import * as st from 'superstruct';
import * as st from "superstruct";
export const getNodeTypeAndValidate = (node: AutomationNode, allowedTypes: AutomationNodeTypes[]) => {
const nodeType = getNodeType(node);
if (allowedTypes.includes(nodeType)) {
return nodeType
}
throw new Error(`Detected '${nodeType}' but expected one of {${allowedTypes}}`)
}
export const getNodeTypeAndValidate = (
node: AutomationNode,
allowedTypes: AutomationNodeTypes[]
) => {
const nodeType = getNodeType(node);
if (allowedTypes.includes(nodeType)) {
return nodeType;
}
throw new Error(
`Detected '${nodeType}' but expected one of {${allowedTypes}}`
);
};
export const getNodeType = (node: AutomationNode): AutomationNodeTypes => {
if ('condition' in node) {
return 'condition'
} else if ('platform' in node) {
return 'trigger'
} else {
return 'action'
}
}
if ("condition" in node) {
return "condition";
} else if ("platform" in node) {
return "trigger";
} else {
return "action";
}
};
export const getSubTypeList = <T extends AutomationNodeTypes>(nodeType: T): AutomationNodeSubtype<T>[] => {
switch (nodeType) {
case 'action':
return [
"service",
"repeat",
"wait",
"device",
"choose",
] as any
case "condition":
return [
'or',
'and',
'not',
'numeric_state',
'state',
'template',
'time',
'trigger',
'zone',
] as any
case 'trigger':
return [
'event',
'homeassistant',
'mqtt',
'numeric_state',
'state',
'tag',
'template',
'time',
'time_pattern',
'webhook',
'zone',
'device',
] as any
default:
return [];
}
}
export const makeDefault = (nodeType: keyof AutomationNodeMapping): AutomationNode => {
switch (nodeType) {
case 'action':
return {
'data': {},
'service': '',
'target': {},
}
case 'condition':
return {
condition: 'and',
conditions: []
}
default:
return {
platform: 'device',
device_id: '',
domain: '',
type: '',
subtype: '',
} as AutomationTrigger
}
}
export const getSubTypeList = <T extends AutomationNodeTypes>(
nodeType: T
): AutomationNodeSubtype<T>[] => {
switch (nodeType) {
case "action":
return ["service", "repeat", "wait", "device", "choose"] as any;
case "condition":
return [
"or",
"and",
"not",
"state",
"device",
"numeric_state",
"template",
"time",
"trigger",
"zone",
] as any;
case "trigger":
return [
"device",
"state",
"numeric_state",
"time",
"time_pattern",
"zone",
"event",
"homeassistant",
"mqtt",
"tag",
"template",
"webhook",
] as any;
default:
return [];
}
};
export const makeDefault = (
nodeType: keyof AutomationNodeMapping
): AutomationNode => {
switch (nodeType) {
case "action":
return {
data: {},
service: "",
target: {},
};
case "condition":
return {
condition: "and",
conditions: [],
};
default:
return {
platform: "device",
device_id: "",
domain: "",
type: "",
subtype: "",
} as AutomationTrigger;
}
};
export const getNodeSubType = <T extends AutomationNodeTypes>(
node: AutomationNode<T>
node: AutomationNode<T>
): AutomationNodeSubtype<T> => {
if ('condition' in node) {
return node.condition as any;
} else if ('platform' in node) {
return node.platform as any;
} else if ('service' in node) {
return 'service' as any
} else if ('repeat' in node) {
return 'repeat' as any
} else if (('wait_template' in node) || ('wait_for_trigger' in node)) {
return 'wait' as any
} else if ('event' in node) {
return 'event' as any
} else if ('device_id' in node) {
return 'device' as any
} else if ('choose' in node) {
return 'choose' as any
} else if ('delay' in node) {
return 'wait' as any
} else {
throw new Error("Invalid node type!")
if ("condition" in node) {
return node.condition as any;
} else if ("platform" in node) {
return node.platform as any;
} else if ("service" in node) {
return "service" as any;
} else if ("repeat" in node) {
return "repeat" as any;
} else if ("wait_template" in node || "wait_for_trigger" in node) {
return "wait" as any;
} else if ("event" in node) {
return "event" as any;
} else if ("device_id" in node) {
return "device" as any;
} else if ("choose" in node) {
return "choose" as any;
} else if ("delay" in node) {
return "wait" as any;
} else {
throw new Error("Invalid node type!");
}
};
export const TriggerValidators: Record<TriggerType, any> = {
homeassistant: v.triggers.AutomationTriggerHA,
device: v.triggers.AutomationTriggerDevice,
event: v.triggers.AutomationTriggerEvent,
mqtt: v.triggers.AutomationTriggerMQTT,
numeric_state: v.triggers.AutomationTriggerNumericState,
state: v.triggers.AutomationTriggerState,
tag: v.triggers.AutomationTriggerTag,
template: v.triggers.AutomationTriggerTemplate,
time: v.triggers.AutomationTriggerTime,
time_pattern: v.triggers.AutomationTriggerTimePattern,
webhook: v.triggers.AutomationTriggerWebhook,
zone: v.triggers.AutomationTriggerZone,
};
export const ActionValidators: Record<ActionType, any> = {
choose: v.actions.ChooseAction,
device: v.actions.DeviceAction,
event: v.actions.FireEventAction,
repeat: v.actions.RepeatAction,
service: v.actions.ServiceAction,
wait: st.union([v.actions.DelayAction, v.actions.WaitAction]),
};
export const ConditionValidators: Record<ConditionType, any> = {
and: v.conditions.LogicCondition,
or: v.conditions.LogicCondition,
not: v.conditions.LogicCondition,
device: v.conditions.DeviceCondition,
numeric_state: v.conditions.NumericCondition,
state: v.conditions.StateCondition,
template: v.conditions.TemplateCondition,
time: v.conditions.TimeCondition,
trigger: v.conditions.TriggerCondition,
zone: v.conditions.ZoneCondition,
};
export const AllValidators: Record<AutomationNodeTypes, any> = {
action: ActionValidators,
condition: ConditionValidators,
trigger: TriggerValidators,
};
export const validateNode = (
node: AutomationNode,
allowedNodeTypes: AutomationNodeTypes[] = []
): MiniFailure[] | null => {
let nodeType = getNodeType(node);
let errors: MiniFailure[] = [];
if (allowedNodeTypes.length > 0 && !allowedNodeTypes.includes(nodeType)) {
errors.push({
message: [
`Got node of type "${nodeType}" but expected one of {${allowedNodeTypes}}`,
],
path: "",
});
nodeType = allowedNodeTypes[0];
}
let nodeSubType: null | AutomationNodeSubtype = null;
try {
nodeSubType = getNodeSubType(node);
} catch (err) {
errors.push({ message: [`Failed to identifiy subtype`], path: "" });
}
if (nodeSubType) {
const failures = getFailures(node, AllValidators[nodeType][nodeSubType]);
if (failures) {
errors = errors.concat(failures);
}
}
}
if (errors.length > 0) {
return errors;
} else {
return null;
}
};
const TriggerValidators: Record<TriggerType, any> = {
"homeassistant": v.triggers.AutomationTriggerHA,
"device": v.triggers.AutomationTriggerDevice,
"event": v.triggers.AutomationTriggerEvent,
"mqtt": v.triggers.AutomationTriggerMQTT,
'numeric_state': v.triggers.AutomationTriggerNumericState,
"state": v.triggers.AutomationTriggerState,
"tag": v.triggers.AutomationTriggerTag,
"template": v.triggers.AutomationTriggerTemplate,
"time": v.triggers.AutomationTriggerTime,
"time_pattern": v.triggers.AutomationTriggerTimePattern,
"webhook": v.triggers.AutomationTriggerWebhook,
"zone": v.triggers.AutomationTriggerZone,
}
export const getEntityDomains = (entityIds: string | string[]): string[] => {
if (typeof entityIds === "string") {
return [entityIds.toLowerCase().split(".")[0] ?? ""];
} else {
const all = new Set<string>();
entityIds.forEach((eid) =>
getEntityDomains(eid).forEach((domain) => all.add(domain))
);
return Array.from(all.keys());
}
};
const ActionValidators: Record<ActionType, any> = {
"choose": v.actions.ChooseAction,
"device": v.actions.DeviceAction,
"event": v.actions.FireEventAction,
"repeat": v.actions.RepeatAction,
"service": v.actions.ServiceAction,
"wait": st.union([
v.actions.DelayAction,
v.actions.WaitAction
]),
}
export const binaryStateDomains = [
"binary_sensor",
"switch",
"light",
"automation",
"input_boolean",
"script",
];
const ConditionValidators: Record<ConditionType, any> = {
"and": v.conditions.LogicCondition,
"or": v.conditions.LogicCondition,
"not": v.conditions.LogicCondition,
"numeric_state": v.conditions.NumericCondition,
"state": v.conditions.StateCondition,
"template": v.conditions.TemplateCondition,
"time": v.conditions.TimeCondition,
"trigger": v.conditions.TriggerCondition,
"zone": v.conditions.ZoneCondition,
}
const AllValidators: Record<AutomationNodeTypes, any> = {
"action": ActionValidators,
"condition": ConditionValidators,
"trigger": TriggerValidators,
}
export const validateNode = (node: AutomationNode, allowedNodeTypes: AutomationNodeTypes[] = []): MiniFailure[] | null => {
let nodeType = getNodeType(node);
let errors: MiniFailure[] = []
if (allowedNodeTypes.length > 0 && !allowedNodeTypes.includes(nodeType)) {
errors.push(
{ "message": [`Got node of type "${nodeType}" but expected one of {${allowedNodeTypes}}`], path: "" }
)
nodeType = allowedNodeTypes[0]
export const entityDomainsAreBinary = (domains: string[]): boolean => {
if (domains.length === 1) {
return binaryStateDomains.includes(domains[0]);
} else {
for (const domain of domains) {
if (!entityDomainsAreBinary([domain])) {
return false;
}
}
let nodeSubType: null | AutomationNodeSubtype = null;
try {
nodeSubType = getNodeSubType(node);
} catch (err) {
errors.push(
{ "message": [`Failed to identifiy subtype`], path: "" }
)
}
if (nodeSubType) {
const failures = getFailures(node, AllValidators[nodeType][nodeSubType]);
if (failures) {
errors = errors.concat(failures)
}
}
if (errors.length > 0) {
return errors
} else {
return null
}
}
return true;
}
};
+74 -59
View File
@@ -1,62 +1,77 @@
import { AutomationCondition, LogicCondition, NumericCondition, StateCondition, TemplateCondition, TimeCondition, TriggerCondition, ZoneCondition } from "types/automations/conditions";
import { AutomationData } from 'types/automations';
import {
AutomationCondition,
LogicCondition,
NumericCondition,
StateCondition,
TemplateCondition,
TimeCondition,
TriggerCondition,
ZoneCondition,
} from "types/automations/conditions";
import { AutomationData } from "types/automations";
export const getConditionDefaultValues = (condition: AutomationCondition['condition']): AutomationCondition => {
if (
(condition === 'or') ||
(condition === 'and') ||
(condition === 'not')
) {
return {
condition,
conditions: []
} as LogicCondition
} else if (condition === 'template') {
return {
condition,
value_template: ""
} as TemplateCondition
} else if (condition === 'numeric_state') {
return {
condition,
entity_id: []
} as NumericCondition
} else if (condition === 'state') {
return {
condition,
entity_id: [],
state: [],
} as StateCondition
} else if (condition === 'time') {
return {
condition,
} as TimeCondition
} else if (condition === 'trigger') {
return {
condition,
id: ""
} as TriggerCondition
} else if (condition === 'zone') {
return {
condition,
zone: "",
entity_id: [],
state: [],
} as ZoneCondition
}
throw new Error("NOT IMPLEMENTED!")
}
export const getConditionDefaultValues = (
condition: AutomationCondition["condition"]
): AutomationCondition => {
if (condition === "or" || condition === "and" || condition === "not") {
return {
condition,
conditions: [],
} as LogicCondition;
} else if (condition === "template") {
return {
condition,
value_template: "",
} as TemplateCondition;
} else if (condition === "numeric_state") {
return {
condition,
entity_id: [],
} as NumericCondition;
} else if (condition === "state") {
return {
condition,
entity_id: [],
state: [],
} as StateCondition;
} else if (condition === "time") {
return {
condition,
} as TimeCondition;
} else if (condition === "trigger") {
return {
condition,
id: "",
} as TriggerCondition;
} else if (condition === "zone") {
return {
condition,
zone: "",
entity_id: [],
state: [],
} as ZoneCondition;
} else if (condition === "device") {
return {
condition,
device_id: "",
domain: "",
type: "",
};
}
return {
condition,
} as any;
};
export const defaultAutomation = (id: string): AutomationData => ({
metadata: {
id,
alias: "New Automation",
description: "",
mode: "single",
},
tags: {},
trigger: [],
sequence: [],
condition: [],
})
metadata: {
id,
alias: "New Automation",
description: "",
mode: "single",
},
tags: {},
trigger: [],
sequence: [],
condition: [],
});
+271 -135
View File
@@ -1,170 +1,306 @@
import { convertTimeToString, getDescriptionFromAutomationNode, Namer, prettyName } from "./formatting";
import {
convertTimeToString,
getDescriptionFromAutomationNode,
Namer,
prettyName,
} from "./formatting";
const dummyNamer: Namer = {
getDeviceName(device_id) {
return device_id
},
getServiceName(service) {
return service
},
getEntityName(entity_id, maxEntities = 1) {
if (Array.isArray(entity_id)) {
return entity_id.slice(0, maxEntities).join(' and ')
} else {
return entity_id
}
},
}
test('converting time to a string', () => {
expect(convertTimeToString({ hours: 1 })).toEqual('01:00:00:00')
expect(convertTimeToString({ hours: 1, minutes: 5 })).toEqual('01:05:00:00')
expect(convertTimeToString({ hours: 1, minutes: 5, seconds: 24 })).toEqual('01:05:24:00')
expect(convertTimeToString({ hours: 1, milliseconds: 100 })).toEqual('01:00:00:100')
})
getDeviceName(device_id) {
return device_id;
},
getServiceName(service) {
return service;
},
getEntityName(entity_id, maxEntities = 1) {
if (Array.isArray(entity_id)) {
return entity_id.slice(0, maxEntities).join(" and ");
} else {
return entity_id;
}
},
};
test("converting time to a string", () => {
expect(convertTimeToString({ hours: 1 })).toEqual("01:00:00:00");
expect(convertTimeToString({ hours: 1, minutes: 5 })).toEqual("01:05:00:00");
expect(convertTimeToString({ hours: 1, minutes: 5, seconds: 24 })).toEqual(
"01:05:24:00"
);
expect(convertTimeToString({ hours: 1, milliseconds: 100 })).toEqual(
"01:00:00:100"
);
});
test('using alias as description', () => {
expect(getDescriptionFromAutomationNode({
test("using alias as description", () => {
expect(
getDescriptionFromAutomationNode(
{
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
service: "media_player.play_media",
target: {
entity_id: "media_player.kitchen_dot"
entity_id: "media_player.kitchen_dot",
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}, dummyNamer)).toEqual("Start Music In Kitchen")
})
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
},
},
dummyNamer,
false
)
).toEqual("Start Music In Kitchen");
});
test('get service action description', () => {
expect(getDescriptionFromAutomationNode({
service: 'media_player.play_media',
test("get service action description", () => {
expect(
getDescriptionFromAutomationNode(
{
service: "media_player.play_media",
target: {
entity_id: "media_player.kitchen_dot"
entity_id: "media_player.kitchen_dot",
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}, dummyNamer)).toEqual("media_player.play_media")
})
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
},
},
dummyNamer,
false
)
).toEqual("media_player.play_media");
});
test('get repeat action description', () => {
expect(getDescriptionFromAutomationNode({
test("get repeat action description", () => {
expect(
getDescriptionFromAutomationNode(
{
repeat: {
count: 10,
sequence: []
}
}, dummyNamer)).toEqual("Repeat 10")
})
count: 10,
sequence: [],
},
},
dummyNamer,
false
)
).toEqual("Repeat 10");
});
test('get wait action description', () => {
expect(getDescriptionFromAutomationNode({
wait_template: "states(switch.kitchen_light) == 'on'"
}, dummyNamer)).toEqual("Wait on states(switch.kitchen_light) == 'on'")
expect(getDescriptionFromAutomationNode({
test("get wait action description", () => {
expect(
getDescriptionFromAutomationNode(
{
wait_template: "states(switch.kitchen_light) == 'on'",
},
dummyNamer,
false
)
).toEqual("Wait on states(switch.kitchen_light) == 'on'");
expect(
getDescriptionFromAutomationNode(
{
wait_template: "states(switch.kitchen_light) == 'on'",
timeout: {
'minutes': 1,
}
}, dummyNamer)).toEqual("Wait on states(switch.kitchen_light) == 'on' for 00:01:00:00")
})
minutes: 1,
},
},
dummyNamer,
false
)
).toEqual("Wait on states(switch.kitchen_light) == 'on' for 00:01:00:00");
});
test('get fire event action description', () => {
expect(getDescriptionFromAutomationNode({
event: 'test_event',
test("get fire event action description", () => {
expect(
getDescriptionFromAutomationNode(
{
event: "test_event",
event_data: {},
}, dummyNamer)).toEqual("Trigger test_event")
})
},
dummyNamer,
false
)
).toEqual("Trigger test_event");
});
test('get device action description', () => {
expect(getDescriptionFromAutomationNode({
test("get device action description", () => {
expect(
getDescriptionFromAutomationNode(
{
device_id: "12310das01231",
domain: "zwave_js",
type: "set_value"
}, dummyNamer)).toEqual("set_value on 12310das01231")
})
type: "set_value",
},
dummyNamer,
false
)
).toEqual("Set Value 12310das01231");
});
test('get choose action description', () => {
expect(getDescriptionFromAutomationNode({
test("get choose action description", () => {
expect(
getDescriptionFromAutomationNode(
{
choose: [],
default: [],
}, dummyNamer)).toEqual("Choose")
})
},
dummyNamer,
false
)
).toEqual("Switch (choose)");
});
test('get and/or/not condition description', () => {
expect(getDescriptionFromAutomationNode({
condition: 'and',
test("get and/or/not condition description", () => {
expect(
getDescriptionFromAutomationNode(
{
condition: "and",
conditions: [],
}, dummyNamer)).toEqual("Logic")
expect(getDescriptionFromAutomationNode({
condition: 'or',
},
dummyNamer,
false
)
).toEqual("Logic");
expect(
getDescriptionFromAutomationNode(
{
condition: "or",
conditions: [],
}, dummyNamer)).toEqual("Logic")
expect(getDescriptionFromAutomationNode({
condition: 'not',
},
dummyNamer,
false
)
).toEqual("Logic");
expect(
getDescriptionFromAutomationNode(
{
condition: "not",
conditions: [],
}, dummyNamer)).toEqual("Logic")
})
},
dummyNamer,
false
)
).toEqual("Logic");
});
test('get Numeric State condition description', () => {
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
}, dummyNamer)).toEqual("sensor.temperature?>?<")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: ""
}, dummyNamer)).toEqual("Numeric State Condition")
expect(getDescriptionFromAutomationNode({
test("get Numeric State condition description", () => {
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
},
dummyNamer,
false
)
).toEqual("sensor.temperature?>?<");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "",
},
dummyNamer,
false
)
).toEqual("Numeric State Condition");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
above: "17",
},
dummyNamer,
false
)
).toEqual("sensor.temperature > 17");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
below: "5",
},
dummyNamer,
false
)
).toEqual("sensor.temperature < 5");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
above: "17",
below: "20",
},
dummyNamer,
false
)
).toEqual("17 < sensor.temperature < 20");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
above: "17",
below: "20",
value_template: "{{ float(state.state) + 2 }}",
},
dummyNamer,
false
)
).toEqual("17 < sensor.temperature < 20");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: 'sensor.temperature',
above: '17',
}, dummyNamer)).toEqual("sensor.temperature > 17")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
below: '5',
}, dummyNamer)).toEqual("sensor.temperature < 5")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
above: '17',
below: '20',
}, dummyNamer)).toEqual("17 < sensor.temperature < 20")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
above: '17',
below: '20',
value_template: "{{ float(state.state) + 2 }}"
}, dummyNamer)).toEqual("17 < sensor.temperature < 20")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: [
"sensor.kitchen_temperature",
"sensor.living_room_temperature"
"sensor.kitchen_temperature",
"sensor.living_room_temperature",
],
above: '17',
below: '20',
value_template: "{{ float(state.state) + 2 }}"
}, dummyNamer)).toEqual("17 < ... < 20")
})
above: "17",
below: "20",
value_template: "{{ float(state.state) + 2 }}",
},
dummyNamer,
false
)
).toEqual("17 < ... < 20");
});
test('get State condition description', () => {
expect(getDescriptionFromAutomationNode({
condition: 'state',
entity_id: 'switch.kitchen_light',
state: "on"
}, dummyNamer)).toEqual("switch.kitchen_light is 'on'")
})
test("get State condition description", () => {
expect(
getDescriptionFromAutomationNode(
{
condition: "state",
entity_id: "switch.kitchen_light",
state: "on",
},
dummyNamer,
false
)
).toEqual("switch.kitchen_light is 'on'");
});
test("pretty naming", () => {
expect(prettyName("sensor")).toEqual("Sensor");
expect(prettyName("sensor.phone")).toEqual("Sensor Phone");
expect(prettyName("device_tracker")).toEqual("Device Tracker");
expect(prettyName("Baby Name")).toEqual("Baby Name");
});
test('pretty naming', () => {
expect(prettyName('sensor')).toEqual("Sensor")
expect(prettyName('sensor.phone')).toEqual("Sensor Phone")
expect(prettyName('device_tracker')).toEqual("Device Tracker")
})
test("get descrption for device triggerr", () => {
expect(
getDescriptionFromAutomationNode(
{
platform: "device",
type: "no_motion",
device_id: "d148a585c041a9a1b352a670d64e0c58",
entity_id: "binary_sensor.motion_office_inv",
domain: "binary_sensor",
},
dummyNamer,
false
)
).toEqual("binary_sensor.motion_office_inv No Motion");
});
-135
View File
@@ -1,135 +0,0 @@
import { AutomationNode, AutomationNodeTypes } from "types/automations";
import { AutomationTime } from "types/automations/common";
export interface Namer {
getEntityName(entity_id: string | string[], maxEntities?: number): string;
getDeviceName(device_id: string): string;
getServiceName(service: string): string;
}
export const convertTimeToString = (t: AutomationTime) => {
if (typeof t === 'string') {
return t
} else {
const {
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0,
} = t
return [hours, minutes, seconds, milliseconds].map(n => String(n).padStart(2, '0')).join(':')
}
}
export const getDescriptionFromAutomationNode = <N extends AutomationNodeTypes>(
node: AutomationNode<N>,
namer: Namer,
): string => {
if (('alias' in node) && node.alias) {
return node.alias;
}
if ('platform' in node) {
if (node.id) {
return node.id ?? '';
}
if (node.platform === 'time') {
return node.at
}
if (node.platform === 'homeassistant') {
if (node.event === 'start') {
return 'HA is starting'
} else {
return 'HA is shutting down'
}
}
if (node.platform === 'tag') {
return `Tag = ${node.tag_id}`
}
if (node.platform === 'state') {
let out = "";
if (typeof node.entity_id === 'string') {
out = namer.getEntityName(node.entity_id)
} else {
out = namer.getEntityName(node.entity_id[0]) + " and more"
}
if (node.from) {
out += ` from ${node.from}`
}
if (node.to) {
out += ` to ${node.to}`
}
return out
}
if (node.platform === 'device') {
return node.device_id ? namer.getDeviceName(node.device_id) : node.entity_id ? namer.getEntityName(node.entity_id) : node.platform
}
return node.platform
}
if ('condition' in node) {
if (
(node.condition === 'and') ||
(node.condition === 'or') ||
(node.condition === 'not')
) {
return "Logic"
} else {
switch (node.condition) {
case "numeric_state":
if (node.entity_id) {
const center = (Array.isArray(node.entity_id) && node.entity_id.length > 1) ?
'...' :
namer.getEntityName(node.entity_id);
if (node.above) {
if (node.below) {
return `${node.above} < ${center} < ${node.below}`
}
return `${center} > ${node.above}`
}
if (node.below) {
return `${center} < ${node.below}`
}
return `${center}?>?<`
}
return "Numeric State Condition"
case "state":
return `${namer.getEntityName(node.entity_id)} is '${node.state}'`
case 'template':
return node.value_template
default:
return 'n/a'
}
}
}
if ('service' in node) {
return namer.getServiceName(node.service)
}
if ('repeat' in node) {
return 'Repeat ' + node.repeat.count
}
if ('delay' in node) {
return `Wait for ${convertTimeToString(node.delay)}`
}
if ('wait_template' in node) {
let out = 'Wait on ' + node.wait_template;
if (node.timeout) {
out += (' for ' + convertTimeToString(node.timeout))
}
return out;
}
if ('event' in node) {
return `Trigger ${node.event}`
}
if ('device_id' in node) {
return `${node.type ?? ""} on ${node.device_id ? namer.getDeviceName(node.device_id) : ''}`
}
if ('choose' in node) {
return "Choose"
}
return 'n/a'
}
export const prettyName = (n: string) => {
const clean = n.replaceAll(/[.-_]/g, ' ');
return clean.split(' ').map(x => x.slice(0, 1).toUpperCase() + x.slice(1)).join(' ')
}
+184
View File
@@ -0,0 +1,184 @@
import { AutomationNode, AutomationNodeTypes } from "types/automations";
import AltRouteOutlinedIcon from "@mui/icons-material/AltRouteOutlined";
import { ReactNode } from "react";
import {
AutomationDeviceState,
AutomationTime,
} from "types/automations/common";
export interface Namer {
getEntityName(entity_id: string | string[], maxEntities?: number): string;
getDeviceName(device_id: string): string;
getServiceName(service: string): string;
}
export const convertTimeToString = (t: AutomationTime) => {
if (typeof t === "string") {
return t;
} else {
const { hours = 0, minutes = 0, seconds = 0, milliseconds = 0 } = t;
return [hours, minutes, seconds, milliseconds]
.map((n) => String(n).padStart(2, "0"))
.join(":");
}
};
export const getDescriptionFromAutomationNode = <
N extends AutomationNodeTypes,
AllowJS extends true | false
>(
node: AutomationNode<N>,
namer: Namer,
allowJs: AllowJS
): AllowJS extends true ? ReactNode : string => {
if ("alias" in node && node.alias) {
return node.alias;
}
if ("platform" in node) {
if (node.id) {
return node.id ?? "";
}
if (node.platform === "time") {
return node.at;
}
if (node.platform === "homeassistant") {
if (node.event === "start") {
return "HA is starting";
} else {
return "HA is shutting down";
}
}
if (node.platform === "tag") {
return `Tag = ${node.tag_id}`;
}
if (node.platform === "state") {
let out = "";
if (typeof node.entity_id === "string") {
out = namer.getEntityName(node.entity_id);
} else {
out = namer.getEntityName(node.entity_id[0]) + " and more";
}
if (node.from) {
out += ` from ${node.from}`;
}
if (node.to) {
out += ` to ${node.to}`;
}
return out;
}
if (node.platform === "device") {
return getDescriptionForDeviceType(node as any, namer, true);
}
return node.platform;
}
if ("condition" in node) {
if (
node.condition === "and" ||
node.condition === "or" ||
node.condition === "not"
) {
return "Logic";
} else {
switch (node.condition) {
case "numeric_state":
if (node.entity_id) {
const center =
Array.isArray(node.entity_id) && node.entity_id.length > 1
? "..."
: namer.getEntityName(node.entity_id);
if (node.above) {
if (node.below) {
return `${node.above} < ${center} < ${node.below}`;
}
return `${center} > ${node.above}`;
}
if (node.below) {
return `${center} < ${node.below}`;
}
return `${center}?>?<`;
}
return "Numeric State Condition";
case "state":
return `${namer.getEntityName(node.entity_id)} is '${node.state}'`;
case "template":
return node.value_template;
case "device":
return getDescriptionForDeviceType(node, namer, true);
case "trigger":
return node.id;
default:
return JSON.stringify(node);
}
}
}
if ("service" in node) {
return namer.getServiceName(node.service);
}
if ("repeat" in node) {
return "Repeat " + node.repeat.count;
}
if ("delay" in node) {
return `Wait for ${convertTimeToString(node.delay)}`;
}
if ("wait_template" in node) {
let out = "Wait on " + node.wait_template;
if (node.timeout) {
out += " for " + convertTimeToString(node.timeout);
}
return out;
}
if ("event" in node) {
return `Trigger ${node.event}`;
}
if ("device_id" in node) {
return getDescriptionForDeviceType(node as any, namer, false);
}
if ("choose" in node) {
if (allowJs) {
return (
<AltRouteOutlinedIcon
style={{
transform: "rotate(90deg)",
}}
color="secondary"
/>
) as any;
}
return "Switch (choose)";
}
return "n/a";
};
const getDescriptionForDeviceType = (
node: AutomationDeviceState,
namer: Namer,
actionToEnd: boolean = false
) => {
let out = "";
let actionPort = "";
if (node.type) {
actionPort += `${prettyName(node.type ?? "")} `;
}
if (node.subtype) {
actionPort += node.subtype;
}
actionPort = actionPort.trim();
if (node.entity_id) {
out += namer.getEntityName(node.entity_id);
} else if (node.device_id) {
out += namer.getDeviceName(node.device_id);
}
out = out.trim();
if (actionToEnd) {
return out + " " + actionPort;
}
return actionPort + " " + out;
};
export const prettyName = (n: string) => {
const clean = n.replaceAll(/[.\-_]/g, " ");
return clean
.split(" ")
.map((x) => x.slice(0, 1).toUpperCase() + x.slice(1))
.join(" ");
};