Compare commits

...
63 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
ari c17783064c update config 2022-06-12 22:44:16 -04:00
ari d824a93695 delay fixes 2022-06-12 22:23:30 -04:00
ari 5207c48f8d v0.1.20 2022-06-12 22:11:58 -04:00
ari b30f4ed59a enabled flag 2022-06-12 21:55:32 -04:00
ari e3a816f2c8 wait template 2022-06-12 21:39:45 -04:00
ari 240f8faef7 latest work 2022-06-12 16:42:44 -04:00
ari 651ba865b1 fixed up inputtime 2022-06-11 18:54:33 -04:00
ari a3e9d19c45 added icon for flip 2022-06-09 17:13:34 -04:00
ari 942867d646 adjusted tasks 2022-06-08 09:38:58 -04:00
ari 041c2f02d5 added tasks + timestring validation 2022-06-08 09:34:52 -04:00
ari fb30d577aa clean up 2022-06-06 22:42:08 -04:00
ari c4a90fcd1c clean up 2022-06-06 22:39:30 -04:00
ari 4c3b34195a service autocomplete 2022-06-06 22:37:34 -04:00
ari 78494ee74d fixed up some styling issues 2022-06-06 19:40:20 -04:00
ari d3fff074e5 fixed up linting 2022-06-06 17:35:35 -04:00
ari 0ee0a06737 more reliable ws 2022-06-06 17:34:06 -04:00
ari 61000f2ff1 namer in conditions 2022-06-06 11:28:51 -04:00
ari ac1ee86cc7 namer 2022-06-06 11:27:25 -04:00
ari c934a4afcb using cookies to remember where we are 2022-06-06 11:02:06 -04:00
116 changed files with 7947 additions and 3496 deletions

No files matched your search

+24 -6
View File
@@ -1,5 +1,25 @@
# 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
- Added delay action / wait_on_triggers action
- Added enabled/disabled flag in node editor
- Optional flip vertical during desktop mode
- Fixed up modal clipping
## [0.1.19] - Vertical mobile mode
- in mobile mode we draw the graphs vertically now
@@ -7,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
@@ -33,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
@@ -87,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
@@ -33,7 +33,7 @@ test:
coverage:
$(VENV_BIN)/coverage run -m unittest discover tests
$(VENV_BIN)/coverage report -m --fail-under=85
$(VENV_BIN)/coverage report -m --fail-under=80
clean:
rm -rf dist *.sqlite *.egg-info build .mypy_cache .coverage
+12 -2
View File
@@ -1,11 +1,13 @@
import asyncio
import json
from fastapi import APIRouter, WebSocket
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from src.logger import get_logger
from src.ws_redirect import WSRedirector
router = APIRouter()
logger = get_logger(__name__)
@router.websocket("/api/websocket")
@@ -19,7 +21,15 @@ async def websocket_endpoint(websocket: WebSocket):
async def wait_for_data():
while True:
await conn.send(await websocket.receive_text())
try:
msg_str = await websocket.receive_text()
msg_d = json.loads(msg_str)
if msg_d.get("type") != "auth":
await conn.send(msg_str)
except WebSocketDisconnect:
logger.info("Websocket closed.")
await conn.close()
break
await websocket.accept()
+4
View File
@@ -14,3 +14,7 @@ else:
logging.basicConfig(level=logging.NOTSET)
logger = logging.getLogger()
def get_logger(name: str):
return logging.getLogger(name)
+20 -10
View File
@@ -1,12 +1,15 @@
import asyncio
import json
from typing import Any, Callable, Coroutine, Optional
from typing import Callable, Coroutine, Optional
import websockets
from websockets.client import WebSocketClientProtocol, connect
from websockets.exceptions import ConnectionClosedOK
from src.env import HASSIO_TOKEN, HASSIO_WS
from src.logger import logger
from src.logger import get_logger, logger
OnMessage = Callable[[str], Coroutine]
logger = get_logger(__name__)
class WSRedirector:
@@ -19,7 +22,7 @@ class WSRedirector:
self._host = host
self._token = token
self._on_message = on_message
self._client: Optional[Any] = None
self._client: Optional[WebSocketClientProtocol] = None
self._close: bool = False
@property
@@ -31,19 +34,26 @@ class WSRedirector:
return await self._client.send(msg)
async def start(self):
async with websockets.connect(self._host) as websocket:
async with connect(self._host) as websocket:
self._client = websocket
await websocket.send(json.dumps({"type": "auth", "access_token": self._token}))
while not self.is_closed:
msg = await websocket.recv()
logger.debug(f"WS:MSG: {msg}")
await self.process_message(msg)
try:
msg = await websocket.recv()
# logger.debug(f"HA MSG :--> {msg} {self.is_closed}")
await self.process_message(msg)
except ConnectionClosedOK:
pass
logger.info("Closing socket...")
await websocket.close()
logger.info("Closed socket")
async def process_message(self, msg: str):
await self._on_message(msg)
def close(self):
async def close(self):
self._close = True
await self._client.close()
def __del__(self):
self.close()
asyncio.create_task(self.close())
+29
View File
@@ -0,0 +1,29 @@
import os
import yaml
from pathlib import Path
print(Path().absolute())
CONFIG_YAML = Path("config.yaml").absolute()
CHANGELOG_MD = Path("CHANGELOG.md").absolute()
print(CONFIG_YAML)
print(CHANGELOG_MD)
version = os.environ["VERSION"]
version_name = os.environ["NAME"]
change = os.environ["CHANGELOG"].splitlines()
config = yaml.load(CONFIG_YAML.read_text(), yaml.Loader)
changelog = CHANGELOG_MD.read_text().splitlines()
with CHANGELOG_MD.open("w") as fp:
for i, log in enumerate(changelog):
if i == 2:
fp.write(f"## [{version}] - {version_name}\n\n")
for clog in change:
fp.write(f"- {clog.strip()}\n")
fp.write(log.strip() + "\n")
CONFIG_YAML.write_text(yaml.dump(config))
+1 -1
View File
@@ -1,5 +1,5 @@
name: Shortumation
version: v0.1.19
version: v0.1.22
slug: shortumation
image: asosnovsky/shortumation-{arch}
url: "https://github.com/asosnovsky/Shortumation"
+59
View File
@@ -0,0 +1,59 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "tsc",
"problemMatcher": [],
"label": "npm: tsc",
"detail": "tsc -w",
"presentation": {
"reveal": "always",
"panel": "shared"
},
"runOptions": {
"runOn": "folderOpen"
},
"group": "test"
},
{
"type": "npm",
"script": "test",
"problemMatcher": [],
"label": "npm: test",
"detail": "test",
"presentation": {
"reveal": "always",
"panel": "shared"
},
"runOptions": {
"runOn": "folderOpen"
},
"group": "test",
},
{
"type": "npm",
"script": "storybook",
"problemMatcher": [],
"label": "npm: storybook",
"detail": "start-storybook -p 6006 -s public",
"promptOnClose": true
},
{
"type": "npm",
"script": "build",
"problemMatcher": [],
"label": "npm: build",
"detail": "react-scripts build",
"group": "build"
},
{
"type": "npm",
"script": "start",
"problemMatcher": [],
"label": "npm: start",
"detail": "react-scripts start",
"promptOnClose": true
},
]
}
+3
View File
@@ -6,6 +6,7 @@
"dependencies": {
"@emotion/react": "^11.9.0",
"@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.8.3",
"@mui/material": "^5.8.0",
"@mui/styles": "^5.8.0",
"@types/jest": "^27.5.1",
@@ -19,8 +20,10 @@
"jss": "^10.8.2",
"notistack": "^2.0.5",
"react": "^18.1.0",
"react-cookie": "^4.1.1",
"react-dom": "^18.1.0",
"react-flow-renderer": "^10.1.2",
"react-imask": "^6.4.2",
"react-jss": "^10.8.2",
"react-router-dom": "6",
"react-scripts": "5.0.1",
+8 -5
View File
@@ -3,6 +3,7 @@ import { Routes, Route, BrowserRouter } from "react-router-dom";
import { AutomationRoute } from 'routes/automation';
import { useConnectedApiService } from 'apiService';
import { ErrorBoundary } from 'components/ErrorBoundary';
import { CookiesProvider } from "react-cookie";
function App() {
const api = useConnectedApiService();
@@ -10,11 +11,13 @@ function App() {
return (
<div className="app">
<ErrorBoundary>
<BrowserRouter>
<Routes>
<Route path="*" element={<AutomationRoute api={api} />} />
</Routes>
</BrowserRouter>
<CookiesProvider>
<BrowserRouter>
<Routes>
<Route path="*" element={<AutomationRoute api={api} />} />
</Routes>
</BrowserRouter>
</CookiesProvider>
</ErrorBoundary>
</div>
);
+1 -1
View File
@@ -7,7 +7,7 @@ import { useMockAPI } from "./mock";
const locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i);
const baseURL = new URL(
process.env.NODE_ENV === 'development' ?
"http://localhost:8000" :
`http://${window.location.hostname}:8000` :
window.location.origin + (!locationPrefixWeb ? '' : locationPrefixWeb[1])
);
export const wsURL = baseURL + "socket"
+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>
}
);
};
@@ -28,13 +28,9 @@
.automation-editor--flow-wrapper--toolbar {
display: flex;
flex-direction: row;
gap: 0.25em;
justify-content: flex-end;
}
.automation-editor--flow-wrapper.unchanged>.automation-editor--flow-wrapper--toolbar {
height: 0;
opacity: 0;
overflow: hidden;
margin-top: 0.25em;
}
.automation-editor--flow-wrapper.changed>.automation-editor--flow-wrapper--toolbar * {
@@ -65,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 {
+161 -104
View File
@@ -1,18 +1,21 @@
import "./index.css";
import { ArrowIcon, CheckMarkIcon } from "components/Icons";
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;
@@ -37,117 +40,171 @@ export const AutomationEditor: FC<Props> = ({
save,
saveAndUpdate,
} = useAutomatioEditorState(propsAutos, propsOnUpdate);
const [closeInfo, setCloseInfo] = useState(false);
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">
<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}
);
}
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>
);
};
@@ -3,6 +3,7 @@ import { useState } from "react";
import { AutomationListBox } from "./AutomationListBox";
import { createMockAuto } from "utils/mocks";
import { Page } from "components/Page";
import { CookiesProvider } from "react-cookie";
export default {
title: 'App/AutomationList/Box',
@@ -16,10 +17,12 @@ export default {
const Template: ComponentStory<typeof AutomationListBox> = args => {
const [selected, setSelected] = useState(args.selected)
return <Page>
<AutomationListBox {...args} automations={args.automations} selected={selected} onSelectAutomation={(i) => {
setSelected(i)
args.onSelectAutomation(i)
}} />
<CookiesProvider>
<AutomationListBox {...args} automations={args.automations} selected={selected} onSelectAutomation={(i) => {
setSelected(i)
args.onSelectAutomation(i)
}} />
</CookiesProvider>
</Page>
}
@@ -1,95 +1,142 @@
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";
import { Button } from "components/Inputs/Button";
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,
// 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] = useState('');
const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>([]);
const filteredAutomations = filterAutomations(automations, searchText, 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,7 +64,15 @@
.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;
}
.automation-list--root.mobile .automation-editor--flow-wrapper.unchanged>.automation-editor--flow-wrapper--toolbar {
height: 0;
opacity: 0;
overflow: hidden;
}
+118 -62
View File
@@ -3,17 +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 { useHA } from "haService";
import { ArrowBack } from "@mui/icons-material";
interface AutomationListParams {
automations: AutomationData[];
@@ -24,6 +25,32 @@ interface AutomationListParams {
children?: ReactNode;
}
export const useAutomationListState = () => {
const [
cookies,
setCookies,
// eslint-disable-next-line
_,
] = useCookies(["alCurrent"]);
let initialCurrent = 0;
try {
initialCurrent = Number(cookies.alCurrent ?? "0");
} catch (_) {}
const [hideList, setHideList] = useState(false);
const [current, setCurrent] = useState(initialCurrent);
return {
hideList,
setHideList,
current,
setCurrent(i: number) {
setCurrent(i);
setCookies("alCurrent", String(i));
},
};
};
export const AutomationList: FC<AutomationListParams> = ({
automations,
onUpdate,
@@ -33,50 +60,65 @@ export const AutomationList: FC<AutomationListParams> = ({
children,
}) => {
// state
const [hideList, setHideList] = useState(false);
const [current, setCurrent] = useState(0);
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;
@@ -84,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";
@@ -9,125 +9,152 @@ import { getEditor } from "./editorRender";
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();
// 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} />
} 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,216 +1,324 @@
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";
import { ConditionNode } from "./ConditionNode";
import { genUpdateMethods } from "./nestedUpdater";
import InputTime from "components/Inputs/InputTime";
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,43 +1,53 @@
import { FC } from "react";
import { AutomationCondition, LogicCondition } from "types/automations/conditions";
import { getDescriptionFromAutomationNode } from "utils/formatting";
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;
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)}
</>
}
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)}
/>
);
})}
</>
);
};
+162 -130
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";
@@ -16,143 +21,170 @@ import { AutomationCondition } from "types/automations/conditions";
import { makeConditionPoint } from "./flowDataMods";
import { convertToFlowNode } from "./helpers";
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);
// 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"]}
/>
);
}
}
// modal
let modalBody = <></>
console.log(modalState)
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,
}
}
// 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, {
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,
}
: {
x: dims.padding.x + dims.nodeWidth * dims.distanceFactor,
y: dims.padding.y + dims.nodeHeight * 0.25,
},
makeSequenceUpdater(sequence, onSequenceUpdate, setModalState),
);
// 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 -267
View File
@@ -1,306 +1,380 @@
import { AutomationSequenceNode } from 'types/automations';
import { DAGAutomationFlowDims, FlowData } from './types';
import { getDescriptionFromAutomationNode } 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,
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, 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)
});
}
} else {
addSingleNode(flowData, node, position, nodeId, dims, {
onEditClick: updater.makeOnModalOpenForNode(i, node),
onXClick: () => updater.removeNode(i)
});
}
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;
}
) => 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),
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,
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),
});
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,
},
}, 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,
},
}, 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,66 +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,
conditionWidth,
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),
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
)
);
};
+2
View File
@@ -5,6 +5,7 @@ import { DAGNodeProps } from './DAGNode';
import { AutomationTrigger } from 'types/automations/triggers';
import { MultiNodeEditorProps } from 'components/MultiNodeEditors/types';
import { DAGErrorNodeProps } from './DAGErrorNode';
import { Namer } from 'utils/formatting';
export type DAGAutomationFlowDims = {
@@ -28,6 +29,7 @@ export type TriggerMakerOptions = {
onAdd: () => void,
onEdit: (i: number) => void,
onDelete: (i: number) => void,
namer: Namer,
}
export type UpdateModalState<T extends AutomationSequenceNode | AutomationTrigger = any> = (
+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
/>
);
};
@@ -0,0 +1,47 @@
.input-autocomplete .BaseBadge-root {
max-width: 100%;
}
.input-autocomplete--chip>span {
display: flex;
flex-direction: row;
gap: 0.15em;
}
.input-autocomplete--chip>span>small::before {
content: "/ ";
}
.input-autocomplete--chip>span>small {
size: 0.15em;
}
.input-autocomplete--errors {
margin-top: 0.75em;
}
.input-autocomplete--errors ul {
padding: 0 0 0 1em;
margin: 0;
max-height: 2.5em;
overflow-y: auto;
overflow-x: hidden;
}
.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);
});
@@ -0,0 +1,256 @@
import "./InputAutoComplete.css";
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;
} & InputAutoCompletePropsBase;
export type InputAutoCompletePropsBase = {
label?: string;
className?: string;
disabled?: boolean;
required?: boolean;
onlyShowLabel?: boolean;
helperText?: ReactNode;
endAdornment?: ReactNode;
} & (
| {
value: string | null;
multiple?: false;
onChange: (v: string | null) => void;
}
| {
value: string | string[];
multiple: true;
onChange: (v: string[]) => void;
}
);
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);
}}
/>
)}
/>
);
}
+62 -5
View File
@@ -1,20 +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>
<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>
);
}
@@ -0,0 +1,150 @@
import "./InputTime.css";
import { useState, useEffect, FC } from "react";
import TextField from "@mui/material/TextField";
import EditIcon from "@mui/icons-material/Edit";
import CloseIcon from "@mui/icons-material/Close";
import { AutomationTime, AutomationTimeObject } from "types/automations/common";
import {
convertAutomationTimeToTimeObject,
convertObjectToAutomationTimeString,
} from "utils/time";
import { convertAutomationTimeToTimeString } from "utils/time";
import { prettyName } from "utils/formatting";
import InputLabel from "@mui/material/InputLabel";
import { ButtonIcon } from "components/Icons/ButtonIcons";
// constants
const fields: Array<keyof AutomationTimeObject> = [
"hours",
"minutes",
"seconds",
"milliseconds",
];
export interface Props {
label: string;
value?: AutomationTime;
onChange: (v?: AutomationTimeObject) => void;
}
export const InputTime: FC<Props> = (props) => {
// state
const [disabled, setDisabled] = useState(!props.value);
const [displayValue, setDisplayValue] = useState(
convertAutomationTimeToTimeObject(props.value)
);
// process display input
const updateOne = (k: keyof AutomationTimeObject) => (v: string) => {
if (Number(v) < 0) {
setDisplayValue({
...displayValue,
[k]: 0,
});
} else if (k === "hours") {
setDisplayValue({
...displayValue,
[k]: Number(v),
});
} else if (k === "minutes") {
let minutes = Number(v);
let { hours = 0 } = displayValue;
if (minutes > 59) {
const additonalHours = Math.floor(minutes / 60);
hours += additonalHours;
minutes = minutes - additonalHours * 60;
}
setDisplayValue({
...displayValue,
minutes,
hours,
});
} else if (k === "seconds") {
let seconds = Number(v);
let { hours = 0, minutes = 0 } = displayValue;
if (seconds > 59) {
const additonalHours = Math.floor(seconds / (60 * 60));
hours += additonalHours;
seconds = seconds - additonalHours * 60;
}
if (seconds > 59) {
const additionalMinutes = Math.floor(seconds / 60);
minutes += additionalMinutes;
seconds = seconds - additionalMinutes * 60;
}
setDisplayValue({
...displayValue,
minutes,
hours,
seconds,
});
} else if (k === "milliseconds") {
let milliseconds = Number(v);
let { hours = 0, minutes = 0, seconds = 0 } = displayValue;
if (milliseconds > 1000) {
const additonalHours = Math.floor(milliseconds / (60 * 60 * 1000));
hours += additonalHours;
milliseconds = milliseconds - additonalHours * 60 * 60 * 1000;
}
if (milliseconds > 1000) {
const additionalMinutes = Math.floor(milliseconds / (60 * 1000));
minutes += additionalMinutes;
milliseconds = milliseconds - additionalMinutes * 60 * 1000;
}
if (milliseconds > 1000) {
const additionalSeconds = Math.floor(milliseconds / 1000);
seconds += additionalSeconds;
milliseconds = milliseconds - additionalSeconds * 1000;
}
setDisplayValue({
...displayValue,
minutes,
hours,
seconds,
milliseconds,
});
}
};
// effect
useEffect(() => {
if (disabled && !props.value) {
return;
}
if (disabled) {
props.onChange(undefined);
} else {
const pVal = convertAutomationTimeToTimeString(props.value);
const cVal = convertObjectToAutomationTimeString(displayValue);
if (pVal !== cVal) {
props.onChange(displayValue);
}
}
// 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)}
/>
))}
<ButtonIcon
onClick={() => setDisabled(!disabled)}
icon={disabled ? <EditIcon /> : <CloseIcon />}
/>
</div>
</div>
);
};
@@ -32,5 +32,5 @@ export const Single = Template.bind({})
Single.args = {
...Single.args,
multiple: false,
value: 'sensor.bathroom'
value: 'sensor.humidity_bathroom'
} as any
+18 -113
View File
@@ -1,117 +1,22 @@
import "./InputEntities.css";
import { FC } from "react";
import { useHADeviceRegistry } from 'haService';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Chip from '@mui/material/Chip';
import { EntityId } from 'types/automations/common';
import { Badge } from "@mui/material";
import { SearchItem } from "./extras";
import { prettyName } from 'utils/formatting';
import { useHADeviceRegistry } from "haService";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
export type InputEntityProps = {
label?: string,
} & ({
value: string | null;
multiple?: false;
onChange: (v: string | null) => void;
} | {
value: EntityId;
multiple: true;
onChange: (v: string[]) => void;
})
export type InputDeviceProps = InputAutoCompletePropsBase;
export const InputDevice: FC<InputEntityProps> = props => {
// state
const dr = useHADeviceRegistry();
// processing of inputs
const options = dr.getOptions();
const value = Array.isArray(props.value) ? props.value : !!props.value ? [props.value] : [];
// 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-entities"
multiple={true}
freeSolo
value={value}
options={options}
onChange={onChange}
getOptionLabel={dr.getLabel}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.manufacturer) : ''}
filterOptions={(opts, s) => {
const searchTerm = s.inputValue.toLocaleLowerCase();
return opts.map(opt => {
let similarityScore = 0;
const eid = dr.getID(opt);
if (eid.toLocaleLowerCase().includes(searchTerm)) {
similarityScore = Math.abs(eid.length - searchTerm.length)
}
const name = dr.getLabel(opt);
if (name.toLocaleLowerCase().includes(searchTerm)) {
similarityScore = Math.abs(eid.length - searchTerm.length)
}
return {
label: name,
id: eid,
similarityScore,
manufacturer: (typeof opt === 'string') ? '' : opt.manufacturer ?? ""
}
}).filter(opt => opt.similarityScore > 0).sort((a, b) => {
return (a.similarityScore > b.similarityScore) ? 1 : -1
})
}}
renderOption={(prop, option, { inputValue }) => {
const label = dr.getLabel(option);
const id = dr.getID(option);
return <SearchItem
listProps={prop}
id={id}
label={label}
searchTerm={inputValue}
/>
}}
renderInput={params => <TextField
{...params}
variant="filled"
label={props.label ?? "Device"}
/>}
renderTags={(tagValue, getTagProps) => <Badge badgeContent={tagValue.length} color="info">
<div className="input-entities--tags">
{tagValue.map((option, index) => {
const label = dr.getLabel(option);
const id = dr.getID(option);
const props = getTagProps({ index });
props.className += ' input-entities--chip'
return (
<Chip
size="medium"
label={<>
{(id === label) ? <span>{label}</span> : <b>{label}</b>}
{(id !== label) && <small>{id}</small>}
</>}
{...props}
/>
)
})}
</div>
</Badge>
}
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>
);
}
@@ -1,35 +0,0 @@
.input-entities .BaseBadge-root {
max-width: 100%;
}
.input-entities--chip>span {
display: flex;
flex-direction: row;
gap: 0.15em;
}
.input-entities--chip>span>small::before {
content: "/ ";
}
.input-entities--chip>span>small {
size: 0.15em;
}
.input-entities--errors {
margin-top: 0.75em;
}
.input-entities--errors ul {
padding: 0 0 0 1em;
margin: 0;
max-height: 2.5em;
overflow-y: auto;
overflow-x: hidden;
}
.input-entities--tags {
max-height: 5em;
max-width: 100%;
overflow: auto;
}
+50 -130
View File
@@ -1,138 +1,58 @@
import "./InputEntities.css";
import { FC } from "react";
import { useHAEntities } from 'haService';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Chip from '@mui/material/Chip';
import { useHAEntities } from "haService/HAEntities";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { prettyName } from "utils/formatting";
import { EntityId } from 'types/automations/common';
import { Badge } from "@mui/material";
import { SearchItem } from "./extras";
export type InputEntityProps = {
restrictToDomain?: string[],
label?: string,
} & ({
value: string | null;
multiple?: false;
onChange: (v: string | null) => void;
} | {
value: EntityId;
multiple: true;
onChange: (v: string[]) => void;
})
export type InputEntityProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[];
restrictedIntegrations?: string[];
preSelectedEntityIds?: string[];
};
export const InputEntity: FC<InputEntityProps> = props => {
// state
const entities = useHAEntities();
// processing of inputs
const options = entities.getOptions(props.restrictToDomain);
const value = Array.isArray(props.value) ? props.value : !!props.value ? [props.value] : [];
const errors = entities.validateOptions(value, props.restrictToDomain);
// processing of errors
let helperText = <></>;
let error: boolean = false;
if (errors !== null) {
error = true
if (errors.length > 0) {
helperText = <Badge
className="input-entities--errors"
badgeContent={errors.length} color="error"
>
<ul title={errors.join(', and')}>{errors.map((msg, i) => <li key={i}>
{msg}
</li>)}</ul>
</Badge>
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`);
}
});
}
// 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])
}
errors.concat(
entities.validateOptions(
v,
props.restrictToDomain,
props.restrictedIntegrations
) ?? []
);
if (errors.length > 0) {
return errors;
}
return <Autocomplete
className="input-entities"
multiple={true}
freeSolo
value={value}
options={options}
onChange={onChange}
getOptionLabel={entities.getLabel}
filterOptions={(opts, s) => {
const searchTerm = s.inputValue.toLocaleLowerCase();
return opts.map(opt => {
let similarityScore = 0;
const eid = entities.getID(opt);
if (eid.toLocaleLowerCase().includes(searchTerm)) {
similarityScore = Math.abs(eid.length - searchTerm.length)
}
const name = entities.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={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''}
renderOption={(prop, option, { inputValue }) => {
const label = entities.getLabel(option);
const id = entities.getID(option);
return <SearchItem
listProps={prop}
id={id}
label={label}
searchTerm={inputValue}
/>
}}
renderInput={params => <TextField
{...params}
variant="filled"
label={props.label ?? "Entity ID"}
helperText={helperText}
error={error}
/>}
renderTags={(tagValue, getTagProps) => <Badge badgeContent={tagValue.length} color="info">
<div className="input-entities--tags">
{tagValue.map((option, index) => {
const label = entities.getLabel(option);
const id = entities.getID(option);
const props = getTagProps({ index });
props.className += ' input-entities--chip'
return (
<Chip
size="medium"
label={<>
{(id === label) ? <span>{label}</span> : <b>{label}</b>}
{(id !== label) && <small>{id}</small>}
</>}
{...props}
/>
)
})}
</div>
</Badge>
}
return null;
};
return (
<InputAutoComplete
{...props}
validateOption={validateOptions}
options={options}
getID={entities.getID}
getLabel={entities.getLabel}
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
/>
}
);
};
+63 -36
View File
@@ -1,52 +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;
}
export const InputList: FC<Props<any>> = ({
prettyOptionLabels?: boolean;
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,
}) => {
const invalidCurrent = current && !options.includes(current);
return <FormControl variant="filled" sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}>
<InputLabel id="demo-simple-select-filled-label">{label}</InputLabel>
<Select
prettyOptionLabels = true,
getKey = String,
placeholder,
title,
helperText,
endAdornment,
disabled,
}: Props<T>) {
const invalidCurrent =
current && !options.map(getKey).includes(getKey(current));
return (
<FormControl
className={className}
autoWidth
id={id}
value={current}
onChange={(e) => {
onChange(e.target.value)
}}
label={label}
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}
>
{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;
}
+71 -28
View File
@@ -1,43 +1,86 @@
import InputWrapper from "./InputWrapper";
import { useInputNumberStyles } from "./styles";
import "./InputNumber.css";
import Close from "@mui/icons-material/Close";
import TextField from "@mui/material/TextField";
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 { classes } = useInputNumberStyles({});
return <InputWrapper className={className} label={label} labelSize={value !== undefined ? 'small' : 'normal'}>
<input
className={classes.input}
type="number"
value={value ?? ""}
onChange={e => {
e.preventDefault();
let v = Number(e.target.value);
if (max) {
v = Math.min(v, max)
}
if (min) {
v = Math.max(v, min)
}
onChange(v)
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,
},
}}
step={step}
min={min}
max={max}
/>
{value && <button className={classes.deleteIcon} onClick={() => onChange(undefined)}>X</button>}
</InputWrapper>
);
}
@@ -0,0 +1,36 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { InputService } from "./InputService";
export default {
title: 'Inputs/InputService',
component: InputService,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputService>;
const Template: ComponentStory<typeof InputService> = args => {
const [value, setValue] = useState(args.value)
return <Page>
<div style={{
maxWidth: 200
}}>
<InputService {...args} value={value as any} onChange={(v: any) => {
setValue(v)
args.onChange(v as any)
}} />
</div>
</Page>
}
export const Single = Template.bind({})
Single.args = {
...Single.args,
multiple: false,
value: ''
} as any
@@ -0,0 +1,19 @@
import { FC } from "react";
import { useHAServices } from 'haService';
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete';
import { prettyName } from 'utils/formatting';
export type InputServiceProps = InputAutoCompletePropsBase & { multiple?: false };
export const InputService: FC<InputServiceProps> = props => {
const services = useHAServices();
return <InputAutoComplete
{...props}
label={props.label ?? "Service"}
options={services.getOptions()}
getID={services.getID}
getLabel={services.getLabel}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''}
/>
}
+45 -20
View File
@@ -1,47 +1,73 @@
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;
additionalTooltipFilters?: Record<string, string>;
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,
}: PropsWithChildren<Props>) {
className,
placeholder,
required,
}: Props) {
const tooltip = useToolTip();
const [isFocused, setIsFocused] = useState(false)
return <InputWrapper 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(),
@@ -51,10 +77,9 @@ export default function InputText({
filterObjects: additionalTooltipFilters,
},
onChange
)
);
}
}}
/>
{children}
</InputWrapper>
);
}
@@ -0,0 +1,15 @@
.input-time>.input-time--inner {
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 {
width: 4em;
}
@@ -3,7 +3,7 @@ import { Page } from "components/Page";
import { useState } from "react";
import { AutomationTime } from "types/automations/common";
import InputTime from "./InputTime";
import { InputTime } from "./InputTime";
export default {
title: 'Inputs/InputTime',
@@ -16,11 +16,19 @@ const Template: ComponentStory<typeof InputTime> = args => {
const [value, setValue] = useState<AutomationTime | undefined>(undefined);
return <Page>
<InputTime {...args} value={value} onChange={setValue} />
<div style={{
padding: '1em'
}}>
<InputTime {...args} value={value} onChange={t => {
setValue(t)
args.onChange(t)
}} />
</div>
</Page>
}
export const SimpleText = Template.bind({})
SimpleText.args = {
label: "Time Stamp",
value: "10"
}
+142 -52
View File
@@ -1,60 +1,150 @@
import { PropsWithChildren, useState } from "react";
import "./InputTime.css";
import { useState, useEffect, FC } from "react";
import TextField from "@mui/material/TextField";
import EditIcon from "@mui/icons-material/Edit";
import CloseIcon from "@mui/icons-material/Close";
import { AutomationTime, AutomationTimeObject } from "types/automations/common";
import { milisecondsToObject } from "utils/time";
import InputWrapper from "./InputWrapper";
import { useInputTimeStyles } from "./styles";
import { convertStringToAutomationTimeObject } from 'utils/time';
import {
convertAutomationTimeToTimeObject,
convertObjectToAutomationTimeString,
convertAutomationTimeToTimeString,
} from "utils/time";
import { prettyName } from "utils/formatting";
import { ButtonIcon } from "components/Icons/ButtonIcons";
// constants
const fields: Array<keyof AutomationTimeObject> = [
"hours",
"minutes",
"seconds",
"milliseconds",
];
export interface Props {
textBoxFor?: string;
label: string;
value?: AutomationTime;
onChange: (v?: AutomationTimeObject) => void;
onEnter?: () => void;
className?: string;
}
export default function InputTime({
label,
textBoxFor,
value = {},
onChange,
onEnter = () => { },
children,
}: PropsWithChildren<Props>) {
let cleanValue = '';
if (value) {
if (typeof value === 'string') {
value = convertStringToAutomationTimeObject(value);
export const InputTime: FC<Props> = (props) => {
// state
const [disabled, setDisabled] = useState(!props.value);
const [displayValue, setDisplayValue] = useState(
convertAutomationTimeToTimeObject(props.value)
);
// process display input
const updateOne = (k: keyof AutomationTimeObject) => (v: string) => {
if (Number(v) < 0) {
setDisplayValue({
...displayValue,
[k]: 0,
});
} else if (k === "hours") {
setDisplayValue({
...displayValue,
[k]: Number(v),
});
} else if (k === "minutes") {
let minutes = Number(v);
let { hours = 0 } = displayValue;
if (minutes > 59) {
const additonalHours = Math.floor(minutes / 60);
hours += additonalHours;
minutes = minutes - additonalHours * 60;
}
setDisplayValue({
...displayValue,
minutes,
hours,
});
} else if (k === "seconds") {
let seconds = Number(v);
let { hours = 0, minutes = 0 } = displayValue;
if (seconds > 59) {
const additonalHours = Math.floor(seconds / (60 * 60));
hours += additonalHours;
seconds = seconds - additonalHours * 60;
}
if (seconds > 59) {
const additionalMinutes = Math.floor(seconds / 60);
minutes += additionalMinutes;
seconds = seconds - additionalMinutes * 60;
}
setDisplayValue({
...displayValue,
minutes,
hours,
seconds,
});
} else if (k === "milliseconds") {
let milliseconds = Number(v);
let { hours = 0, minutes = 0, seconds = 0 } = displayValue;
if (milliseconds > 1000) {
const additonalHours = Math.floor(milliseconds / (60 * 60 * 1000));
hours += additonalHours;
milliseconds = milliseconds - additonalHours * 60 * 60 * 1000;
}
if (milliseconds > 1000) {
const additionalMinutes = Math.floor(milliseconds / (60 * 1000));
minutes += additionalMinutes;
milliseconds = milliseconds - additionalMinutes * 60 * 1000;
}
if (milliseconds > 1000) {
const additionalSeconds = Math.floor(milliseconds / 1000);
seconds += additionalSeconds;
milliseconds = milliseconds - additionalSeconds * 1000;
}
setDisplayValue({
...displayValue,
minutes,
hours,
seconds,
milliseconds,
});
}
const {
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0,
} = value;
cleanValue = [hours, minutes, seconds].map(x => String(x).padStart(2, '0')).join(':') + `.${String(milliseconds).padStart(3, '0')}`;
}
const { classes } = useInputTimeStyles({});
const [isFocused, setIsFocused] = useState(false)
return <InputWrapper className={classes.wrapper} label={label} labelSize={(value === '') && !isFocused ? 'normal' : 'small'}>
<input
className={classes.input}
type="time"
step={0.001}
value={cleanValue}
onKeyDown={e => {
if (e.key === 'Enter') {
onEnter();
}
}}
onChange={e => {
e.preventDefault();
onChange(milisecondsToObject(e.target.valueAsNumber))
}}
onBlur={e => {
setIsFocused(false)
}}
/>
<button onClick={() => onChange()} className={classes.cancel}>X</button>
{children}
</InputWrapper>
}
};
// effect
useEffect(() => {
if (disabled && !props.value) {
return;
}
if (disabled) {
props.onChange(undefined);
} else {
const pVal = convertAutomationTimeToTimeString(props.value);
const cVal = convertObjectToAutomationTimeString(displayValue);
if (pVal !== cVal) {
props.onChange(displayValue);
}
}
// 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)}
/>
))}
<ButtonIcon
onClick={() => setDisabled(!disabled)}
icon={disabled ? <EditIcon /> : <CloseIcon />}
/>
</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;
}
+90 -35
View File
@@ -1,61 +1,116 @@
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>({
export default function InputYaml<T extends {}>({
label,
error: incmError,
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 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: 'absolute',
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: '80%',
maxHeight: '90%',
minHeight: 'fit-content',
minWidth: 'fit-content',
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 InputText from "components/Inputs/InputText";
import InputYaml from 'components/Inputs/InputYaml';
import { InputService } from "components/Inputs/InputService";
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,31 +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 <>
<InputText
textBoxFor="service"
label="Service"
value={service}
onChange={service => update({ 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,
})
}
/>
)}
</>
);
},
};
@@ -0,0 +1,33 @@
.node-editor--action-wait {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.node-editor--action-wait .for {
flex: 2;
}
.node-editor--action-wait .for .input-time--inner {
justify-content: center;
}
.node-editor--action-wait .template {
margin: 0;
flex: 2;
}
.node-editor--action-wait .triggers {
width: 100%;
}
.node-editor--action-wait .wait-type {
flex: 1;
}
.node-editor--action-wait .wait-options {
width: 100%;
display: flex;
justify-content: space-evenly;
align-items: center;
}
@@ -1,41 +1,109 @@
import "./ActionWait.css";
import InputBoolean from "components/Inputs/InputBoolean";
import { InputList } from "components/Inputs/InputList";
import InputNumber from "components/Inputs/InputNumber";
import InputText from "components/Inputs/InputText";
import { WaitAction } from "types/automations/actions";
import { InputTime } from "components/Inputs/InputTime";
import { useState } from "react";
import { DelayAction, WaitAction } from "types/automations/actions";
import { OptionManager, updateActionData } from './OptionManager';
import InputYaml from "components/Inputs/InputYaml";
type ThisAction = WaitAction | DelayAction;
type Option = 'delay' | 'template' | 'trigger'
const getCurrentOption = (node: ThisAction): Option => {
if ('delay' in node) {
return 'delay'
} else {
return 'template'
}
}
export const ActionWaitState: OptionManager<WaitAction> = {
export const ActionWaitState: OptionManager<ThisAction> = {
defaultState: () => ({
alias: "Wait",
wait_template: "",
// timeout: 0,
continue_on_timeout: false,
delay: "",
}),
isReady: ({
alias, wait_template
}) => (
alias !== '' &&
wait_template !== ""
),
renderOptionList: (state, setState) => {
isReady: () => true,
Component: ({ state, setState }) => {
// state
const update = updateActionData(state, setState);
return <>
<InputText
textBoxFor="template"
label="Template"
value={state.wait_template}
onChange={wait_template => update({ wait_template })}
/>
{/* <InputNumber
label="Timeout"
value={state.timeout ?? 0}
onChange={(timeout = 0) => update({ timeout })}
/> */}
<InputBoolean
label="Continue on Timeout"
value={state.continue_on_timeout ?? false}
onChange={continue_on_timeout => update({ continue_on_timeout })}
/>
</>
const [current, _setCurrent] = useState(getCurrentOption(state));
const setCurrent = (opt: Option) => {
const base: any = {
alias: state.alias,
variables: state.variables,
}
if (opt === 'delay') {
setState({
...base,
delay: (state as any).delay ?? "",
})
} else {
base.timeout = (state as any).timeout
base.continue_on_timeout = (state as any).continue_on_timeout
if (opt === 'template') {
setState({
...base,
wait_template: (state as any).wait_template ?? "",
})
} else {
setState({
...base,
wait_for_trigger: (state as any).wait_for_trigger ?? "",
})
}
}
_setCurrent(opt)
}
// determine options
let option: JSX.Element = <></>;
if (current === "delay") {
option = <>
<InputTime className="for" label="for" value={(state as any).delay} onChange={delay => update({ delay })} />
</>
} else if (current === 'template') {
state = state as WaitAction;
option = <>
<InputText
label="Template"
className="template"
value={state.wait_template ?? ""}
onChange={wait_template => update({ wait_template })}
/>
</>
} else if (current === 'trigger') {
state = state as WaitAction;
option = <>
<InputYaml
className="triggers"
label="Triggers"
value={state.wait_for_trigger ?? []}
onChange={wait_for_trigger => update({ wait_for_trigger })}
/>
</>
}
// render
return <div className="node-editor--action-wait">
<InputList
className="wait-type"
label="Wait Type" prettyOptionLabels
options={["template", 'trigger', "delay"]}
current={current} onChange={setCurrent} />
{option}
{current !== 'delay' ? <div className="wait-options">
<InputNumber
label="Timeout"
value={(state as any).timeout ? Number((state as any).timeout) : undefined}
onChange={timeout => update({ timeout: timeout === undefined ? undefined : String(timeout) })}
/>
<InputBoolean
label="Continue on Timeout"
value={(state as any).continue_on_timeout ?? false}
onChange={continue_on_timeout => update({ continue_on_timeout })}
/>
</div> : <></>}
</div>
}
}
@@ -1,29 +1,54 @@
import { HAEntitiesState } from 'haService';
import { AutomationAction } from 'types/automations/actions';
import { AutomationCondition } from 'types/automations/conditions';
export interface OptionManager<T> {
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;
}
} & (
| {
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];
}
});
return clean;
};
export const updateConditionData = <T extends AutomationCondition>(
setState: (s: T) => void
) => (
state: T,
data: Partial<T>,
) => setState({
...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({
...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 })}
/>
</>
);
},
};
@@ -3,8 +3,7 @@ import { AutomationTriggerNumericState } from 'types/automations/triggers';
import InputText from 'components/Inputs/InputText';
import { InputEntity } from 'components/Inputs/InputEntities';
import InputNumber from 'components/Inputs/InputNumber';
import InputTime from 'components/Inputs/InputTime';
import InputYaml from 'components/Inputs/InputYaml';
import { InputTime } from 'components/Inputs/InputTime'; import InputYaml from 'components/Inputs/InputYaml';
export const TriggerNumericState: OptionManager<AutomationTriggerNumericState> = {
@@ -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,7 +1,7 @@
import { OptionManager } from './OptionManager';
import { AutomationTriggerTemplate } from 'types/automations/triggers';
import InputText from 'components/Inputs/InputText';
import InputTime from 'components/Inputs/InputTime';
import { InputTime } from 'components/Inputs/InputTime';
export const TriggerTemplate: OptionManager<AutomationTriggerTemplate> = {
@@ -1,6 +1,6 @@
import { OptionManager } from './OptionManager';
import { AutomationTriggerTime } from 'types/automations/triggers';
import InputTime from 'components/Inputs/InputTime';
import { InputTime } from 'components/Inputs/InputTime';
import { convertObjectToAutomationTimeString } from 'utils/time';
@@ -40,6 +40,8 @@ export const getOptionManager = <T extends AutomationNodeTypes>(
return ActionCallServiceState;
case "wait":
return ActionWaitState;
case "delay":
return ActionWaitState;
}
}
if (nodeType === 'condition') {
@@ -1,44 +1,61 @@
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { AutomationNode, AutomationNodeTypes } from 'types/automations';
import { AutomationNodeSubtype } from 'types/automations';
import { getOptionManager } from './getOptionManager';
import { getNodeSubType, getSubTypeList, validateNode } from 'utils/automations';
import InputYaml from 'components/Inputs/InputYaml';
import InputText from 'components/Inputs/InputText';
import { getDescriptionFromAutomationNode } from 'utils/formatting';
import { useHAEntities } from 'haService';
import { Generic } from './Generic';
import { getNodeTypeAndValidate } from '../../../utils/automations';
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { AutomationNode, AutomationNodeTypes } from "types/automations";
import { AutomationNodeSubtype } from "types/automations";
import { getOptionManager } from "./getOptionManager";
import {
getNodeSubType,
getSubTypeList,
validateNode,
} from "utils/automations";
import InputYaml from "components/Inputs/InputYaml";
import InputText from "components/Inputs/InputText";
import { getDescriptionFromAutomationNode } from "utils/formatting";
import { useHA } from "haService";
import { Generic } from "./Generic";
import { getNodeTypeAndValidate } from "utils/automations";
type UseState = <S>(s: S) => [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 = useHAEntities();
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,
@@ -47,7 +64,7 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
subType,
subTypes,
optionManager,
} = createData(originalNode, currentNode, allowedTypes)
} = createData(originalNode, currentNode, allowedTypes);
// publuc
return {
nodeType,
@@ -59,84 +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() {
console.log('rendering option list')
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)}
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}
{optionManager.renderOptionList(currentNode, setState, 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;
@@ -148,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,
@@ -165,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: <></>,
};
}
}
};
@@ -8,6 +8,14 @@
margin-top: 0.5em;
}
.node-editor--root.disabled {
background-color: var(--secondary);
}
.node-editor--root.disabled .enabled-flag {
color: var(--secondary-accent);
}
.node-editor--root.modded {
border: 1px solid var(--change);
border-radius: 5px;
@@ -63,4 +71,20 @@
align-items: flex-start;
padding: 0 0.5em 0 1.5em;
margin: 0;
}
.node-editor--error>li {
text-align: left;
}
.node-editor--body-flags {
padding-left: 1em;
display: flex;
flex-direction: column;
justify-content: space-evenly;
}
.node-editor--body-flags .MuiCheckbox-root {
margin: 0;
padding: 0 0 0 0;
}
@@ -1,86 +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 ServiceExample = Action.bind({});
ServiceExample.args = {
...ServiceExample.args,
node: {
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({});
DelayExample.args = {
...DelayExample.args,
node: {
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",
},
}
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>
};
+87 -47
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,50 +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' : ''].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}
/> : <></>}
<InputBoolean label="Yaml" onChange={state.setYamlMode} value={state.yamlMode} disabled={state.isErrored} />
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);
@@ -1,27 +0,0 @@
import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { Page } from "components/Page";
import { useHAConnection } from './connection';
const Test: FC = () => {
const conn = useHAConnection();
return <code>
{JSON.stringify(conn, null, 4)}
</code>
}
export default {
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} />
</Page>
};
+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;
}
+225 -114
View File
@@ -1,123 +1,234 @@
import { entitiesColl, servicesColl } from "home-assistant-js-websocket"
import { deviceRegistryColl } from "./DeviceRegistry";
import { entityRegistryColl } from "./EntityRegistry";
import { DeviceRegistryItem } from "./types";
import { useHassCollection } from "./useHassCollection"
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
}
}
import { servicesColl } from "home-assistant-js-websocket";
import { Namer } from "utils/formatting";
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 ServiceOption = Option<{
domain: string;
action: string;
description: string;
data: TypedHassService;
}>;
export type HAServicesState = ReturnType<typeof useHAServices>;
export const useHAServices = () => {
const services = useHassCollection(servicesColl);
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: ServiceOption): string => {
if (typeof opt === "string") {
return opt;
}
return opt.id;
},
};
return services
}
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)
const dr = useHassCollection(entityRegistryColl);
return dr;
};
return dr
}
export type HAService = ReturnType<typeof useHA>;
export const useHA = () => {
const entities = useHAEntities();
const devices = useHADeviceRegistry();
const services = useHAServices();
const conn = useHAConnection();
const { enqueueSnackbar } = useSnackbar();
const callService = async (
domain: string,
service: string,
data: any = {},
target: any = {}
) => {
if (conn.status === "loaded") {
try {
const result = await conn.connection.sendMessagePromise({
type: "call_service",
domain,
service,
target,
service_data: data,
});
enqueueSnackbar(`Successfully called ${domain}.${service}`, {
variant: "success",
});
return result;
} catch (err: any) {
let msg = JSON.stringify(err);
if ("message" in err) {
msg = err.message;
}
enqueueSnackbar(
`Failed to call ${domain}.${service} because '${msg}'`,
{
variant: "error",
}
);
return;
}
}
if (conn.status === "error") {
enqueueSnackbar(
`Failed to call service because connection is '${conn.status}' -- ${conn.error}`,
{
variant: "error",
}
);
} else {
enqueueSnackbar(
`Failed to call service because connection is '${conn.status}'`,
{
variant: "error",
}
);
}
};
const 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"),
};
};
+219
View File
@@ -0,0 +1,219 @@
import React, { FC, useEffect, useState } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useHA } from "haService";
import InputYaml from "components/Inputs/InputYaml";
import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button";
import { ServiceEditor } from "components/ServiceEditor";
const Test: FC = () => {
const { services, callService } = useHA();
const data = services.collection?.state ?? {};
const options = Object.keys(data).sort();
// 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,
// }
// 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]
// }))
// })
// }
// )
// })
// console.info(flattened)
// 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> }>> = {}
// 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))
// })
// 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))
// })
// 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 [domain, setDomain] = useState(options[0] ?? "");
const domains = Object.keys(data[domain] ?? "").sort();
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}>
<b>{t}</b> ({summary[k][t].total})
<ul style={{ maxHeight: '200px', overflow: 'auto' }}>
{Array.from(summary[k][t].values.values()).sort().map((v, i) => <li key={i}>
{v}
</li>)}
</ul>
</li>)}
</ul>
</li>)}
</ul>
<h1>Fields</h1>
<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}>
<b>{t}</b> ({fields[k][t].total})
<ul style={{ maxHeight: '200px', overflow: 'auto' }}>
{Array.from(fields[k][t].values.values()).sort().map((v, i) => <li key={i}>
{v}
</li>)}
</ul>
</li>)}
</ul>
</li>)}
</ul>
<h1>Targets</h1>
<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}>
<b>{t}</b> ({target[k][t].total})
<ul style={{ maxHeight: '200px', overflow: 'auto' }}>
{Array.from(target[k][t].values.values()).sort().map((v, i) => <li key={i}>
{v}
</li>)}
</ul>
</li>)}
</ul>
</li>)}
</ul> */}
</div>
);
};
export default {
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} />
</Page>
);
};
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more