Compare commits
19
Commits
v0.1.16.pre2
...
v0.1.19
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
359958aada | ||
|
|
7a73af4434 | ||
|
|
55bb941399 | ||
|
|
afb765024d | ||
|
|
911f867518 | ||
|
|
25bb19dbe5 | ||
|
|
9960ce2909 | ||
|
|
c2fde70954 | ||
|
|
5ca9c4a361 | ||
|
|
c27f2d13f0 | ||
|
|
26c81effd6 | ||
|
|
e72c83b980 | ||
|
|
e222c42150 | ||
|
|
e7b88fc6f6 | ||
|
|
079f353dbf | ||
|
|
e6e51be5a5 | ||
|
|
3a6b21a117 | ||
|
|
f42df5a70f | ||
|
|
0c3e9b5ace |
No files matched your search
@@ -1,6 +1,4 @@
|
||||
name: Deploy
|
||||
env:
|
||||
MONITORED_FILES: "apparmor.txt build.yaml config.yaml Dockerfile data rootfs"
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
|
||||
@@ -100,5 +100,6 @@ jobs:
|
||||
with:
|
||||
args: |
|
||||
--${{ matrix.arch }} \
|
||||
--no-latest \
|
||||
--version ${{ needs.metadata.outputs.version }} \
|
||||
--target .
|
||||
+14
-1
@@ -1,6 +1,19 @@
|
||||
# Changelog 
|
||||
|
||||
## [0.1.14] - Material UI + Autocomplete v2
|
||||
## [0.1.19] - Vertical mobile mode
|
||||
|
||||
- in mobile mode we draw the graphs vertically now
|
||||
|
||||
## [0.1.17] - Websockets
|
||||
|
||||
- Connected to HA main websocket -- now we retrieve real-time information about
|
||||
|
||||
* Device names
|
||||
* Entity names/ids
|
||||
|
||||
- Autocomplete for devices and entities
|
||||
|
||||
## [0.1.14] - Material UI + Autocomplete
|
||||
|
||||
- Brought some Material UI elements for input and text
|
||||
- Autocomplete for tags
|
||||
|
||||
@@ -9,9 +9,7 @@ WORKDIR /app
|
||||
ARG BUILD_VERSION
|
||||
|
||||
# <--- Environment Variables -->
|
||||
ENV HASSIO_TOKEN ""
|
||||
ENV BUILD_VERSION $BUILD_VERSION
|
||||
ENV HASS_URL "http://supervisor/"
|
||||
|
||||
# <--- System Wide Dependencies -->
|
||||
ENV LANG C.UTF-8
|
||||
|
||||
@@ -24,7 +24,6 @@ push:
|
||||
$(DC) push
|
||||
|
||||
start:
|
||||
$(MAKE) build
|
||||
$(DC) up -d
|
||||
sleep 1
|
||||
$(DC) ps
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
[](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml)
|
||||

|
||||
| | Stable | amd64-edge | i386-edge | armv7-edge | aarch64-edge | armhf-edge |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| Version |  |  |  |  |  |  |
|
||||
| | Stable | Edge
|
||||
| --- | --- | ---
|
||||
| Version |  | 
|
||||
|
||||
A better way to write automations in home-assistant without having to install and run a seperate automation engine!
|
||||
|
||||
@@ -21,9 +21,9 @@ A [home-assistant addon](https://www.home-assistant.io/addons/) for a better UI
|
||||
- [X] See all automations in one common view
|
||||
- [X] Automation Manager
|
||||
- [X] Tags for automation organization
|
||||
- [X] Autocomplete fields for entities/devices
|
||||
- [ ] Script Manager
|
||||
- [ ] Use secrets and global parameters
|
||||
- [ ] Autocomplete fields for entities/devices
|
||||
- [ ] Autocomplete fields for template editor
|
||||
- [ ] Autocomplete fields for referencing scripts
|
||||
|
||||
|
||||
+13
-16
@@ -1,17 +1,14 @@
|
||||
list_autos # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:16)
|
||||
upsert_auto # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:27)
|
||||
delete_auto # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:31)
|
||||
read_ping # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/details.py:12)
|
||||
read_ping # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/ping.py:9)
|
||||
params # unused variable (/home/ari/Projects/Shortumation/api/src/api/types.py:16)
|
||||
total_items # unused variable (/home/ari/Projects/Shortumation/api/src/api/types.py:17)
|
||||
id # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:6)
|
||||
alias # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:7)
|
||||
description # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:8)
|
||||
trigger_variables # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:9)
|
||||
mode # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:10)
|
||||
list_autos # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:17)
|
||||
upsert_auto # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:28)
|
||||
delete_auto # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/automations.py:32)
|
||||
read_details # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/details.py:10)
|
||||
read_ping # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/ping.py:10)
|
||||
websocket_endpoint # unused function (/home/ari/Projects/Shortumation/api/src/api/routes/socket.py:9)
|
||||
params # unused variable (/home/ari/Projects/Shortumation/api/src/api/types.py:18)
|
||||
total_items # unused variable (/home/ari/Projects/Shortumation/api/src/api/types.py:19)
|
||||
id # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:8)
|
||||
alias # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:9)
|
||||
description # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:10)
|
||||
trigger_variables # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:11)
|
||||
mode # unused variable (/home/ari/Projects/Shortumation/api/src/automations/types.py:12)
|
||||
json_dumps # unused function (/home/ari/Projects/Shortumation/api/src/json_serializer.py:5)
|
||||
logger # unused variable (/home/ari/Projects/Shortumation/api/src/logger.py:16)
|
||||
_.to_yaml # unused method (/home/ari/Projects/Shortumation/api/src/yaml_serializer/types.py:13)
|
||||
_.to_yaml # unused method (/home/ari/Projects/Shortumation/api/src/yaml_serializer/types.py:30)
|
||||
_.to_yaml # unused method (/home/ari/Projects/Shortumation/api/src/yaml_serializer/types.py:54)
|
||||
+1
-1
@@ -33,7 +33,7 @@ test:
|
||||
|
||||
coverage:
|
||||
$(VENV_BIN)/coverage run -m unittest discover tests
|
||||
$(VENV_BIN)/coverage report -m --fail-under=90
|
||||
$(VENV_BIN)/coverage report -m --fail-under=85
|
||||
|
||||
clean:
|
||||
rm -rf dist *.sqlite *.egg-info build .mypy_cache .coverage
|
||||
|
||||
+10
-5
@@ -3,16 +3,16 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from src.automations.manager import AutomationManager
|
||||
from src.env import ORIGIN, ROOT_FOLDER
|
||||
from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER
|
||||
|
||||
from .routes import automations, details, ping
|
||||
from .routes import automations, details, ping, socket
|
||||
|
||||
|
||||
def make_app(automation_mgr: AutomationManager) -> FastAPI:
|
||||
app = FastAPI()
|
||||
if (ROOT_FOLDER / "web").exists():
|
||||
app.mount(
|
||||
"/web",
|
||||
f"{API_PREFIX}/web",
|
||||
StaticFiles(
|
||||
directory=ROOT_FOLDER / "web",
|
||||
html=True,
|
||||
@@ -29,6 +29,11 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
|
||||
allow_headers=["*"],
|
||||
)
|
||||
app.include_router(ping.router, prefix="/ping")
|
||||
app.include_router(automations.make_automation_router(automation_mgr), prefix="/automations")
|
||||
app.include_router(details.make_details_router(automation_mgr.hass_config), prefix="/details")
|
||||
app.include_router(
|
||||
automations.make_automation_router(automation_mgr), prefix=f"{API_PREFIX}/automations"
|
||||
)
|
||||
app.include_router(
|
||||
details.make_details_router(automation_mgr.hass_config), prefix=f"{API_PREFIX}/details"
|
||||
)
|
||||
app.include_router(socket.router, prefix=f"{API_PREFIX}/socket")
|
||||
return app
|
||||
@@ -1,6 +1,6 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from src.env import BUILD_VERSION, HASS_URL, HASSIO_TOKEN
|
||||
from src.env import BUILD_VERSION, HASSIO_TOKEN, HASSIO_WS
|
||||
from src.hass_config import HassConfig
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ def make_details_router(hass_config: HassConfig) -> APIRouter:
|
||||
return {
|
||||
"version": BUILD_VERSION,
|
||||
"hassio_token": HASSIO_TOKEN,
|
||||
"hass_url": HASS_URL,
|
||||
"hassio_url": HASSIO_WS,
|
||||
"config": hass_config.get_configuration_path(),
|
||||
"tags": hass_config.get_automation_tags_path(),
|
||||
"autos": hass_config.get_automation_path(),
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, WebSocket
|
||||
|
||||
from src.ws_redirect import WSRedirector
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.websocket("/api/websocket")
|
||||
async def websocket_endpoint(websocket: WebSocket):
|
||||
async def on_message(msg: str):
|
||||
await websocket.send_text(msg)
|
||||
|
||||
conn = WSRedirector(
|
||||
on_message=on_message,
|
||||
)
|
||||
|
||||
async def wait_for_data():
|
||||
while True:
|
||||
await conn.send(await websocket.receive_text())
|
||||
|
||||
await websocket.accept()
|
||||
|
||||
await asyncio.gather(
|
||||
conn.start(),
|
||||
wait_for_data(),
|
||||
)
|
||||
+3
-2
@@ -4,7 +4,8 @@ from decouple import Csv, config
|
||||
|
||||
ROOT_FOLDER = Path(__file__).parent.parent.absolute()
|
||||
BUILD_VERSION = config("BUILD_VERSION", "0.0.0")
|
||||
HASSIO_TOKEN = config("HASSIO_TOKEN", "")
|
||||
HASS_URL = config("HASS_URL", "/")
|
||||
HASSIO_TOKEN = config("SUPERVISOR_TOKEN", "")
|
||||
HASSIO_WS = config("HASSIO_WS", "ws://supervisor/core/websocket")
|
||||
LOG_LEVEL = config("LOG_LEVEL", "INFO")
|
||||
API_PREFIX = config("API_PREFIX", "")
|
||||
ORIGIN = config("ORIGIN", cast=Csv(), default="*")
|
||||
@@ -0,0 +1,49 @@
|
||||
import json
|
||||
from typing import Any, Callable, Coroutine, Optional
|
||||
|
||||
import websockets
|
||||
|
||||
from src.env import HASSIO_TOKEN, HASSIO_WS
|
||||
from src.logger import logger
|
||||
|
||||
OnMessage = Callable[[str], Coroutine]
|
||||
|
||||
|
||||
class WSRedirector:
|
||||
def __init__(
|
||||
self,
|
||||
on_message: OnMessage,
|
||||
token: str = HASSIO_TOKEN,
|
||||
host: str = HASSIO_WS,
|
||||
) -> None:
|
||||
self._host = host
|
||||
self._token = token
|
||||
self._on_message = on_message
|
||||
self._client: Optional[Any] = None
|
||||
self._close: bool = False
|
||||
|
||||
@property
|
||||
def is_closed(self):
|
||||
return self._close
|
||||
|
||||
async def send(self, msg: str):
|
||||
if self._client:
|
||||
return await self._client.send(msg)
|
||||
|
||||
async def start(self):
|
||||
async with websockets.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)
|
||||
|
||||
async def process_message(self, msg: str):
|
||||
await self._on_message(msg)
|
||||
|
||||
def close(self):
|
||||
self._close = True
|
||||
|
||||
def __del__(self):
|
||||
self.close()
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
name: Shortumation
|
||||
version: v0.1.14
|
||||
version: v0.1.19
|
||||
slug: shortumation
|
||||
image: ghcr.io/asosnovsky/shortumation-{arch}
|
||||
image: asosnovsky/shortumation-{arch}
|
||||
url: "https://github.com/asosnovsky/Shortumation"
|
||||
description: "A homeassitant addon which provides better UI for automations & scripts."
|
||||
arch:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: '3'
|
||||
services:
|
||||
addon:
|
||||
image: "ghcr.io/asosnovsky/shortumation-${ARCH:-amd64}:${BUILD_TAG:-edge}"
|
||||
image: "asosnovsky/shortumation-${ARCH:-amd64}:${BUILD_TAG:-edge}"
|
||||
build:
|
||||
context: "./"
|
||||
dockerfile: "./Dockerfile"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -4,16 +4,15 @@ import { makeRemoteAPI } from "./base";
|
||||
import { useAPIService } from './core';
|
||||
import { useMockAPI } from "./mock";
|
||||
|
||||
const locationPrefixWeb = window.location.pathname.match(/(.+)\/web/i);
|
||||
const baseURL = process.env.NODE_ENV === 'development' ?
|
||||
"http://localhost:8000" :
|
||||
(!locationPrefixWeb ? '' : locationPrefixWeb[1]);
|
||||
|
||||
export const remoteDetailsAPI = makeRemoteAPI(
|
||||
baseURL + "/details"
|
||||
const locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i);
|
||||
const baseURL = new URL(
|
||||
process.env.NODE_ENV === 'development' ?
|
||||
"http://localhost:8000" :
|
||||
window.location.origin + (!locationPrefixWeb ? '' : locationPrefixWeb[1])
|
||||
);
|
||||
export const wsURL = baseURL + "socket"
|
||||
export const remoteAutoAPI = makeRemoteAPI(
|
||||
baseURL + "/automations"
|
||||
baseURL + "automations"
|
||||
);
|
||||
export const useConnectedApiService = () => useAPIService(
|
||||
makeAutomationAPI(remoteAutoAPI)
|
||||
|
||||
@@ -67,7 +67,10 @@ export const AutomationList: FC<AutomationListParams> = ({
|
||||
{currentAuto ? <AutomationEditor
|
||||
automation={currentAuto}
|
||||
onUpdate={a => onUpdate(current, a)}
|
||||
dims={dims}
|
||||
dims={{
|
||||
...dims,
|
||||
flipped: isMobile
|
||||
}}
|
||||
tagDB={tagDB}
|
||||
/> : <></>}
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,7 @@ export interface DAGCircleProps {
|
||||
backgroundColor?: string;
|
||||
disableSource?: boolean;
|
||||
disableTarget?: boolean;
|
||||
flipped: boolean;
|
||||
}
|
||||
export const makeFlowCircle = (
|
||||
circleId: string,
|
||||
@@ -32,6 +33,7 @@ export const DAGCircle: FC<{ data: DAGCircleProps }> = ({
|
||||
backgroundColor,
|
||||
disableSource = false,
|
||||
disableTarget = false,
|
||||
flipped,
|
||||
}
|
||||
}) => {
|
||||
const { classes } = useCircleStyles({
|
||||
@@ -41,8 +43,8 @@ export const DAGCircle: FC<{ data: DAGCircleProps }> = ({
|
||||
backgroundColor,
|
||||
});
|
||||
return <>
|
||||
{!disableSource && <Handle type="source" position={Position.Right} />}
|
||||
{!disableTarget && <Handle type="target" position={Position.Left} />}
|
||||
{!disableSource && <Handle type="source" position={flipped ? Position.Bottom : Position.Right} />}
|
||||
{!disableTarget && <Handle type="target" position={flipped ? Position.Top : Position.Left} />}
|
||||
<div className={classes.root}>
|
||||
{
|
||||
onAdd ?
|
||||
|
||||
@@ -3,21 +3,21 @@ import { Handle, Position } from 'react-flow-renderer';
|
||||
import { FC } from 'react';
|
||||
import { InfoIcon, PencilIcon } from 'components/Icons';
|
||||
|
||||
|
||||
export interface DAGErrorNodeProps {
|
||||
height: number;
|
||||
width: number;
|
||||
flipped: boolean;
|
||||
hasInput?: boolean;
|
||||
error?: any,
|
||||
onEdit: () => void;
|
||||
}
|
||||
export const DAGErrorNode: FC<DAGErrorNodeProps> = ({
|
||||
height, width, hasInput, error, onEdit
|
||||
height, width, hasInput, error, onEdit, flipped
|
||||
}) => {
|
||||
// render
|
||||
return <>
|
||||
{hasInput && <Handle type="target" position={Position.Left} />}
|
||||
<Handle type="source" position={Position.Right} />
|
||||
{hasInput && <Handle type="target" position={flipped ? Position.Top : Position.Left} />}
|
||||
<Handle type="source" position={flipped ? Position.Bottom : Position.Right} />
|
||||
<div className={["dagnode-error"].join(' ')} style={{
|
||||
height,
|
||||
width,
|
||||
|
||||
@@ -14,6 +14,7 @@ export interface DAGNodeProps {
|
||||
label: string;
|
||||
hasInput?: boolean;
|
||||
accentBackground?: boolean;
|
||||
flipped: boolean;
|
||||
}
|
||||
export const DAGNode: FC<DAGNodeProps> = ({
|
||||
label,
|
||||
@@ -24,6 +25,7 @@ export const DAGNode: FC<DAGNodeProps> = ({
|
||||
color,
|
||||
hasInput = false,
|
||||
accentBackground = false,
|
||||
flipped,
|
||||
}) => {
|
||||
const { classes, theme } = useNodeStyles({
|
||||
color,
|
||||
@@ -32,8 +34,8 @@ export const DAGNode: FC<DAGNodeProps> = ({
|
||||
accentBackground,
|
||||
});
|
||||
return <>
|
||||
{hasInput && <Handle type="target" position={Position.Left} />}
|
||||
<Handle type="source" position={Position.Right} />
|
||||
{hasInput && <Handle type="target" position={flipped ? Position.Top : Position.Left} />}
|
||||
<Handle type="source" position={flipped ? Position.Bottom : Position.Right} />
|
||||
<div className={classes.root}>
|
||||
<div className={classes.inner}>
|
||||
<div className={classes.leftEdge} onClick={onXClick}>
|
||||
|
||||
@@ -19,4 +19,5 @@ export const DEFAULT_DIMS = {
|
||||
x: PADDING,
|
||||
y: PADDING,
|
||||
},
|
||||
flipped: false,
|
||||
} as DAGAutomationFlowDims
|
||||
@@ -1,19 +1,22 @@
|
||||
import { makeFlowCircle } from "./DAGCircle"
|
||||
import { DAGCircleProps, makeFlowCircle } from "./DAGCircle"
|
||||
import { DAGAutomationFlowDims } from "./types"
|
||||
import { XYPosition } from 'react-flow-renderer';
|
||||
import { Node, XYPosition } from 'react-flow-renderer';
|
||||
import { DAGNodeProps } from "./DAGNode";
|
||||
|
||||
export const makeAddButton = (
|
||||
id: string,
|
||||
position: XYPosition,
|
||||
{
|
||||
circleSize,
|
||||
flipped,
|
||||
}: DAGAutomationFlowDims,
|
||||
onAdd: () => void,
|
||||
disableTarget: boolean = true,
|
||||
) => makeFlowCircle(
|
||||
): Node<DAGCircleProps> => makeFlowCircle(
|
||||
id,
|
||||
position,
|
||||
{
|
||||
flipped,
|
||||
size: circleSize,
|
||||
onAdd,
|
||||
disableSource: true,
|
||||
@@ -25,22 +28,17 @@ export const makeConditionPoint = (
|
||||
id: string,
|
||||
position: XYPosition,
|
||||
{
|
||||
padding,
|
||||
conditionWidth,
|
||||
conditionHeight,
|
||||
nodeWidth,
|
||||
nodeHeight,
|
||||
circleSize,
|
||||
distanceFactor,
|
||||
flipped,
|
||||
}: DAGAutomationFlowDims,
|
||||
totalConditions: number,
|
||||
onEditClick: () => void,
|
||||
) => ({
|
||||
): Node<DAGNodeProps> => ({
|
||||
id,
|
||||
type: 'dagnode',
|
||||
position,
|
||||
data: {
|
||||
size: circleSize,
|
||||
color: 'lblue',
|
||||
accentBackground: true,
|
||||
label: `${totalConditions} Condition${totalConditions !== 1 ? 's' : ''}`,
|
||||
@@ -48,5 +46,6 @@ export const makeConditionPoint = (
|
||||
width: conditionWidth,
|
||||
hasInput: true,
|
||||
onEditClick,
|
||||
flipped,
|
||||
}
|
||||
})
|
||||
@@ -92,7 +92,10 @@ Complex.args = {
|
||||
{
|
||||
"platform": "homeassistant",
|
||||
"event": "start",
|
||||
}
|
||||
},
|
||||
{
|
||||
"bad": "node"
|
||||
} as any
|
||||
],
|
||||
sequence: [
|
||||
{
|
||||
@@ -120,6 +123,9 @@ Complex.args = {
|
||||
"media_content_type": "SPOTIFY"
|
||||
}
|
||||
},
|
||||
{
|
||||
"alias": "Bad Node",
|
||||
},
|
||||
{
|
||||
"choose": [
|
||||
{
|
||||
@@ -231,4 +237,27 @@ Errors.args = {
|
||||
"choose": {}
|
||||
} as any
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
export const ComplexFlipped = Complex.bind({})
|
||||
|
||||
ComplexFlipped.args = {
|
||||
...Complex.args,
|
||||
dims: {
|
||||
...dgconst.DEFAULT_DIMS,
|
||||
...Complex.args.dims,
|
||||
flipped: true,
|
||||
}
|
||||
}
|
||||
|
||||
export const SimpleFlipped = Simple.bind({})
|
||||
|
||||
SimpleFlipped.args = {
|
||||
...Simple.args,
|
||||
dims: {
|
||||
...dgconst.DEFAULT_DIMS,
|
||||
...Complex.args.dims,
|
||||
flipped: true,
|
||||
}
|
||||
}
|
||||
@@ -60,13 +60,17 @@ export const DAGAutomationFlow: FC<DAGAutomationFlowProps> = ({
|
||||
|
||||
// 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); }}
|
||||
onSave={n => {
|
||||
modalState.update(n as any);
|
||||
setModalState(null);
|
||||
}}
|
||||
allowedTypes={modalState.allowedTypes}
|
||||
saveBtnCreateText={modalState.saveBtnCreateText}
|
||||
/>
|
||||
@@ -81,7 +85,11 @@ export const DAGAutomationFlow: FC<DAGAutomationFlowProps> = ({
|
||||
}
|
||||
|
||||
// convert automation to flow data
|
||||
const condPoint = makeConditionPoint('c', {
|
||||
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(
|
||||
@@ -120,7 +128,10 @@ export const DAGAutomationFlow: FC<DAGAutomationFlowProps> = ({
|
||||
sequence,
|
||||
condPoint.id,
|
||||
{
|
||||
...dims, padding: {
|
||||
...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,
|
||||
}
|
||||
|
||||
@@ -25,12 +25,18 @@ export const sequenceToFlow = (
|
||||
const nodeId = `${prefix}n-${i}`;
|
||||
let position: XYPosition;
|
||||
if (lasPos) {
|
||||
position = {
|
||||
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 = {
|
||||
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
|
||||
};
|
||||
@@ -67,7 +73,14 @@ export const sequenceToFlow = (
|
||||
// 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) :
|
||||
@@ -104,6 +117,7 @@ const addSingleNode = (
|
||||
position: XYPosition,
|
||||
nodeId: string,
|
||||
{
|
||||
flipped,
|
||||
nodeHeight,
|
||||
nodeWidth,
|
||||
}: DAGAutomationFlowDims,
|
||||
@@ -120,6 +134,7 @@ const addSingleNode = (
|
||||
width: nodeWidth,
|
||||
color: getNodeType(node) === 'action' ? 'green' : 'blue',
|
||||
hasInput: true,
|
||||
flipped,
|
||||
...opts,
|
||||
},
|
||||
position,
|
||||
@@ -172,10 +187,14 @@ const addChooseNode = (
|
||||
node.choose.forEach(({ sequence, conditions }, j) => {
|
||||
const sequenceId = `${nodeId}.${j}`;
|
||||
// edit/delete circle
|
||||
const circle = makeFlowCircle(`${sequenceId}>delete`, {
|
||||
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,
|
||||
@@ -187,7 +206,10 @@ const addChooseNode = (
|
||||
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,
|
||||
},
|
||||
@@ -201,7 +223,10 @@ const addChooseNode = (
|
||||
// actual sub sequence
|
||||
const lastPoint = sequenceToFlow(flowData, sequence, condNode.id, {
|
||||
...dims,
|
||||
padding: {
|
||||
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,
|
||||
},
|
||||
@@ -209,7 +234,13 @@ const addChooseNode = (
|
||||
if (lastPoint.position) {
|
||||
lastPos = xyApply(lastPos, lastPoint.position, Math.max)
|
||||
} else {
|
||||
lastPos = xyApply(lastPos, { x: lastPos.x, y: lastPos.y + dims.nodeHeight * dims.distanceFactor }, Math.max)
|
||||
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;
|
||||
@@ -217,7 +248,10 @@ const addChooseNode = (
|
||||
// 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,
|
||||
},
|
||||
@@ -238,15 +272,21 @@ const addChooseNode = (
|
||||
addEdge(flowData, nodeId, addCirlce.id, true)
|
||||
|
||||
// else
|
||||
const elseCircle = makeFlowCircle(`${nodeId}>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 })
|
||||
}, { 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: {
|
||||
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,
|
||||
},
|
||||
|
||||
@@ -16,6 +16,9 @@ export const triggerToFlow = (
|
||||
nodeWidth,
|
||||
padding,
|
||||
conditionHeight,
|
||||
conditionWidth,
|
||||
circleSize,
|
||||
flipped,
|
||||
} = dims;
|
||||
// convert all triggers to dag nodes
|
||||
trigger.forEach((t, i) => {
|
||||
@@ -27,11 +30,18 @@ export const triggerToFlow = (
|
||||
label: getDescriptionFromAutomationNode(t),
|
||||
height: nodeHeight,
|
||||
width: nodeWidth,
|
||||
flipped,
|
||||
color: 'red',
|
||||
onEditClick: () => opts.onEdit(i),
|
||||
onXClick: () => opts.onDelete(i),
|
||||
},
|
||||
position: { x: padding.x, y: padding.y + nodeHeight * distanceFactor * 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})`,
|
||||
@@ -43,7 +53,10 @@ export const triggerToFlow = (
|
||||
// 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,
|
||||
},
|
||||
|
||||
@@ -15,6 +15,7 @@ export type DAGAutomationFlowDims = {
|
||||
conditionHeight: number;
|
||||
circleSize: number;
|
||||
distanceFactor: number;
|
||||
flipped: boolean;
|
||||
}
|
||||
|
||||
export type DAGAutomationFlowNode = Node<DAGNodeProps | DAGCircleProps | DAGErrorNodeProps | any>;
|
||||
|
||||
@@ -27,19 +27,23 @@ export const makeSequenceUpdater = (
|
||||
choose: [],
|
||||
default: [],
|
||||
},
|
||||
update: n => onChange([
|
||||
...sequence,
|
||||
n,
|
||||
]),
|
||||
update: n => {
|
||||
onChange([
|
||||
...sequence,
|
||||
n,
|
||||
])
|
||||
},
|
||||
allowedTypes: ['action', 'condition']
|
||||
})
|
||||
},
|
||||
updateNode(i: number, node: AutomationSequenceNode) {
|
||||
return onChange([
|
||||
...sequence.slice(0, i),
|
||||
node,
|
||||
...sequence.slice(i + 1),
|
||||
])
|
||||
if (JSON.stringify(node) !== JSON.stringify(sequence[i])) {
|
||||
return onChange([
|
||||
...sequence.slice(0, i),
|
||||
node,
|
||||
...sequence.slice(i + 1),
|
||||
])
|
||||
}
|
||||
},
|
||||
updateChooseActionData(i: number, data: ChooseAction) {
|
||||
const node = sequence[i] as ChooseAction;
|
||||
|
||||
@@ -7,7 +7,7 @@ export interface Props {
|
||||
labelSize?: 'normal' | 'small';
|
||||
noMargin?: boolean;
|
||||
className?: string;
|
||||
error?: string;
|
||||
error?: JSX.Element | string;
|
||||
children: ReactNode;
|
||||
}
|
||||
const InputWrapper: FC<Props> = ({ error, label, children, labelSize = 'normal', noMargin = false, className = "" }) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as yaml from "js-yaml";
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useDelayEffect } from 'utils/useDelay';
|
||||
|
||||
import CodeMirror from '@uiw/react-codemirror';
|
||||
@@ -10,18 +10,20 @@ export interface Props<T extends {}> {
|
||||
label: string;
|
||||
value: T;
|
||||
onChange: (v: T) => void;
|
||||
error?: JSX.Element | string,
|
||||
}
|
||||
export default function InputYaml<T>({
|
||||
label,
|
||||
error: incmError,
|
||||
value = {} as any,
|
||||
onChange,
|
||||
}: Props<T>) {
|
||||
const [{ text, error }, setState] = useState<{
|
||||
text: string,
|
||||
error: undefined | string,
|
||||
error: undefined | JSX.Element | string,
|
||||
}>({
|
||||
text: yaml.dump(value),
|
||||
error: undefined
|
||||
error: incmError,
|
||||
});
|
||||
const setText = (t: string) => {
|
||||
try {
|
||||
@@ -31,6 +33,12 @@ export default function InputYaml<T>({
|
||||
setState({ text: t, error: "! Invalid Yaml !" })
|
||||
}
|
||||
}
|
||||
useEffect(() => {
|
||||
setState({
|
||||
text: yaml.dump(value),
|
||||
error: incmError,
|
||||
})
|
||||
}, [value, incmError])
|
||||
useDelayEffect(() => {
|
||||
if (!error && (yaml.dump(value) !== text)) {
|
||||
if (text) {
|
||||
|
||||
@@ -33,4 +33,16 @@
|
||||
|
||||
.multinode-editor.modded .multinode-editor--total {
|
||||
color: var(--green-light)
|
||||
}
|
||||
|
||||
.multinode-editor.modded .node-editor--footer--save {
|
||||
border-color: var(--green-opaque);
|
||||
background-color: var(--green-light);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.multinode-editor.modded .node-editor--footer--save:hover {
|
||||
border-color: var(--green-light);
|
||||
background-color: var(--green-opaque);
|
||||
color: var(--green-light);
|
||||
}
|
||||
@@ -19,19 +19,18 @@ export const MultiNodeEditor: FC<MultiNodeEditorProps> = props => {
|
||||
</Button>;
|
||||
// branch
|
||||
if (state.isEmpty) {
|
||||
return <div className='column center' style={{
|
||||
return <div className={["multinode-editor", state.isModified ? "modded" : '', isMobile ? 'mobile' : ''].join(' ')} style={{
|
||||
minWidth: '20vw',
|
||||
}}>
|
||||
<div style={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'flex-start',
|
||||
}}>
|
||||
<div className="multinode-editor--navbar">
|
||||
{nextOrAddBtn}
|
||||
</div>
|
||||
<div className='column center' style={{ marginTop: '1em' }}>
|
||||
<div className='node-editor--footer' style={{ marginTop: '1em' }}>
|
||||
<Button onClick={state.onClose}>Close</Button>
|
||||
<Button onClick={state.onSaveEmpty} className="node-editor--footer--save">Save</Button>
|
||||
</div>
|
||||
<div className='column center'>
|
||||
<span>{state.currentSlideNumber}/<u className="multinode-editor--total">{state.totalSlides}</u></span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -107,9 +107,9 @@ export const useMultiNodeEditorState = (props: MultiNodeEditorProps) => {
|
||||
slides.slice(slide + 1)
|
||||
),
|
||||
multiNode: {
|
||||
isModified: multiNode.isModified,
|
||||
isModified: true,
|
||||
isSaved: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
},
|
||||
onSave(node: AutomationNode) {
|
||||
@@ -129,6 +129,17 @@ export const useMultiNodeEditorState = (props: MultiNodeEditorProps) => {
|
||||
internalNodeModified: false,
|
||||
})
|
||||
},
|
||||
onSaveEmpty() {
|
||||
justSaved.current = true
|
||||
setState({
|
||||
...state,
|
||||
multiNode: {
|
||||
isModified: multiNode.isModified,
|
||||
isSaved: true,
|
||||
},
|
||||
internalNodeModified: false,
|
||||
})
|
||||
},
|
||||
onClose() {
|
||||
if (!multiNode.isSaved && multiNode.isModified) {
|
||||
if (!window.confirm("You haven't saved your work, are you ok with losing it?")) {
|
||||
@@ -136,6 +147,9 @@ export const useMultiNodeEditorState = (props: MultiNodeEditorProps) => {
|
||||
}
|
||||
props.onSave && props.onSave(slides)
|
||||
}
|
||||
if (justSaved.current) {
|
||||
props.onSave && props.onSave(slides)
|
||||
}
|
||||
props.onClose && props.onClose()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,42 +2,44 @@ import { Dispatch, SetStateAction, useEffect, useState } from 'react';
|
||||
import { AutomationNode, AutomationNodeTypes } from 'types/automations';
|
||||
import { AutomationNodeSubtype } from 'types/automations';
|
||||
import { getOptionManager } from './getOptionManager';
|
||||
import { getNodeType, getNodeSubType, getSubTypeList, validateNode } from 'utils/automations';
|
||||
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';
|
||||
|
||||
type UseState = <S>(s: S) => [S, Dispatch<SetStateAction<S>>]
|
||||
|
||||
export const useEditorNodeState = (originalNode: AutomationNode, isErrored: boolean, 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)
|
||||
...computeInvalidYaml(originalNode, allowedTypes)
|
||||
});
|
||||
const entities = useHAEntities();
|
||||
// aliases
|
||||
const { node: currentNode, isModified, yamlMode, invalidManualYaml } = allState;
|
||||
// effects
|
||||
useEffect(() => {
|
||||
setAllState({ ...allState, node: originalNode, isModified: false, })
|
||||
// eslint-disable-next-line
|
||||
}, [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 setStateForManualYaml = (yaml: any) => {
|
||||
try {
|
||||
createData(yaml, yaml)
|
||||
setAllState({
|
||||
...allState,
|
||||
...computeInvalidYaml(yaml)
|
||||
})
|
||||
} catch (err) {
|
||||
setAllState({ ...allState, invalidManualYaml: <>{String(err)}</>, isErrored: true, })
|
||||
}
|
||||
setAllState({
|
||||
...allState,
|
||||
...computeInvalidYaml(yaml, allowedTypes)
|
||||
})
|
||||
}
|
||||
// value aliases
|
||||
const {
|
||||
originalNodeType,
|
||||
originalNodeSubType,
|
||||
@@ -45,7 +47,8 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
|
||||
subType,
|
||||
subTypes,
|
||||
optionManager,
|
||||
} = createData(originalNode, currentNode);
|
||||
} = createData(originalNode, currentNode, allowedTypes)
|
||||
// publuc
|
||||
return {
|
||||
nodeType,
|
||||
subType,
|
||||
@@ -54,6 +57,13 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
|
||||
invalidManualYaml,
|
||||
isModified,
|
||||
isErrored: allState.isErrored,
|
||||
get prettyNodeType() {
|
||||
if (nodeType) {
|
||||
return `${nodeType.slice(0, 1).toUpperCase()}${nodeType.slice(1)} Type`
|
||||
} else {
|
||||
return 'n/a'
|
||||
}
|
||||
},
|
||||
get yamlMode() {
|
||||
return allState.isErrored || yamlMode
|
||||
},
|
||||
@@ -61,9 +71,11 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
|
||||
return currentNode
|
||||
},
|
||||
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({
|
||||
@@ -74,6 +86,7 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
|
||||
}
|
||||
if (nodeType === 'action') {
|
||||
aliasEditor = <InputText
|
||||
key="alias"
|
||||
label="Alias"
|
||||
value={getDescriptionFromAutomationNode(allState.node)}
|
||||
onChange={alias => setState({
|
||||
@@ -89,8 +102,8 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
|
||||
label=''
|
||||
value={currentNode}
|
||||
onChange={setStateForManualYaml}
|
||||
error={invalidManualYaml}
|
||||
/>
|
||||
<div className="node-editor--error">{invalidManualYaml}</div>
|
||||
</>
|
||||
}
|
||||
return <>
|
||||
@@ -108,25 +121,43 @@ export const useEditorNodeState = (originalNode: AutomationNode, isErrored: bool
|
||||
setState(getOptionManager(newType, getSubTypeList(newType)[0]).defaultState())
|
||||
}
|
||||
},
|
||||
setSubType(newSubType: AutomationNodeSubtype<typeof nodeType>) {
|
||||
setSubType(newSubType: AutomationNodeSubtype) {
|
||||
if (newSubType === originalNodeSubType) {
|
||||
setState(originalNode)
|
||||
} else {
|
||||
setState(getOptionManager(nodeType, newSubType as any).defaultState())
|
||||
if (nodeType) {
|
||||
setState(getOptionManager(nodeType, newSubType as any).defaultState())
|
||||
} else {
|
||||
setState(getOptionManager(allowedTypes[0], newSubType as any).defaultState())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const createData = (originalNode: AutomationNode, currentNode: AutomationNode) => {
|
||||
const originalNodeType = getNodeType(originalNode);
|
||||
const originalNodeSubType = getNodeSubType(originalNode);
|
||||
const nodeType = getNodeType(currentNode);
|
||||
const subType = getNodeSubType(currentNode);
|
||||
const subTypes = getSubTypeList(nodeType)
|
||||
const optionManager = getOptionManager(nodeType, subType as any);
|
||||
const createData = (originalNode: AutomationNode, currentNode: AutomationNode, allowedTypes: AutomationNodeTypes[]) => {
|
||||
let originalNodeType: AutomationNodeTypes = allowedTypes[0];
|
||||
let originalNodeSubType: AutomationNodeSubtype | null = null;
|
||||
let nodeType: AutomationNodeTypes = originalNodeType;
|
||||
let subType: AutomationNodeSubtype | null = originalNodeSubType;
|
||||
let subTypes: AutomationNodeSubtype[] = getSubTypeList(allowedTypes[0]);
|
||||
let optionManager = Generic;
|
||||
|
||||
try {
|
||||
originalNodeType = getNodeTypeAndValidate(originalNode, allowedTypes);
|
||||
originalNodeSubType = getNodeSubType(originalNode);
|
||||
} catch (err) {
|
||||
console.error(`ORIGINAL NODE ERROR ${JSON.stringify(originalNode)}`)
|
||||
}
|
||||
try {
|
||||
nodeType = getNodeTypeAndValidate(currentNode, allowedTypes);
|
||||
subType = getNodeSubType(currentNode);
|
||||
subTypes = getSubTypeList(nodeType)
|
||||
optionManager = getOptionManager(nodeType, subType as any);
|
||||
} catch (err) {
|
||||
console.error(`CURRENT NODE ERROR ${JSON.stringify(currentNode)}`)
|
||||
}
|
||||
return {
|
||||
originalNodeType,
|
||||
originalNodeSubType,
|
||||
@@ -137,13 +168,14 @@ const createData = (originalNode: AutomationNode, currentNode: AutomationNode) =
|
||||
}
|
||||
}
|
||||
|
||||
const computeInvalidYaml = (node: AutomationNode) => {
|
||||
const errors = validateNode(node);
|
||||
const computeInvalidYaml = (node: AutomationNode, allowedNodeTypes: AutomationNodeTypes[]) => {
|
||||
const errors = validateNode(node, allowedNodeTypes);
|
||||
if (errors) {
|
||||
console.log({ errors })
|
||||
return {
|
||||
node,
|
||||
isErrored: true,
|
||||
invalidManualYaml: <ul key={'error'}>
|
||||
invalidManualYaml: <ul key={'error'} className="node-editor--error">
|
||||
{errors.map(({ message, path }, i) => <li key={i}>
|
||||
<b>{path}</b>: {message}
|
||||
</li>)}
|
||||
|
||||
@@ -58,4 +58,9 @@
|
||||
max-width: 30em;
|
||||
overflow: auto;
|
||||
max-height: 10em;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
padding: 0 0.5em 0 1.5em;
|
||||
margin: 0;
|
||||
}
|
||||
@@ -29,7 +29,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
|
||||
isErrored = false,
|
||||
}) => {
|
||||
// state
|
||||
const state = useEditorNodeState(node, isErrored);
|
||||
const state = useEditorNodeState(node, isErrored, allowedTypes);
|
||||
|
||||
// alias
|
||||
const isModified = state.isModified;
|
||||
@@ -53,7 +53,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
|
||||
onChange={state.setNodeType}
|
||||
/> : <></>}
|
||||
{state.nodeType !== 'condition' ? <InputList
|
||||
label={`${state.nodeType.slice(0, 1).toUpperCase()}${state.nodeType.slice(1)} Type`}
|
||||
label={state.prettyNodeType}
|
||||
current={state.subType as any}
|
||||
options={state.subTypes}
|
||||
onChange={state.setSubType}
|
||||
@@ -68,11 +68,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
|
||||
className="node-editor--footer--save"
|
||||
onClick={() => {
|
||||
if (areYouSureNotReady('save')) {
|
||||
if (JSON.stringify(state.data) !== JSON.stringify(node)) {
|
||||
onSave(state.data)
|
||||
} else {
|
||||
onClose()
|
||||
}
|
||||
onSave(state.data)
|
||||
}
|
||||
}}
|
||||
title={
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
ERR_INVALID_HTTPS_TO_HTTP,
|
||||
createConnection as _createConnection,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { remoteDetailsAPI } from 'apiService';
|
||||
import { wsURL } from 'apiService';
|
||||
|
||||
export type HAConnection = {
|
||||
status: 'loading'
|
||||
@@ -43,60 +43,18 @@ const translateErrorCodes = (errorCode: number) => {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
type ReturnedToken = {
|
||||
hassURL: string;
|
||||
longToken: string
|
||||
} | {
|
||||
hassURL: string;
|
||||
hassioToken: string
|
||||
} | {
|
||||
error: any;
|
||||
}
|
||||
const getToken = async (): Promise<ReturnedToken> => {
|
||||
const data = await remoteDetailsAPI.makeCall({
|
||||
"path": "/",
|
||||
"method": "GET",
|
||||
});
|
||||
if (!data.ok) {
|
||||
return {
|
||||
error: {
|
||||
message: "Failed to get token from api.",
|
||||
originalError: data.error,
|
||||
}
|
||||
}
|
||||
}
|
||||
const hassURL = data.data.hass_url;
|
||||
const hassioToken = data.data.hassio_token;
|
||||
if (!hassioToken) {
|
||||
return {
|
||||
error: {
|
||||
message: [
|
||||
"Missing HASSIO Token, Please make sure the token is correctly passing to the container!",
|
||||
"Make sure the token `HASSIO_TOKEN` and `HASS_URL` are set properly."
|
||||
].join('\n'),
|
||||
}
|
||||
}
|
||||
}
|
||||
return { hassioToken, hassURL }
|
||||
}
|
||||
|
||||
const createConnection = async () => {
|
||||
const tokens = await getToken();
|
||||
try {
|
||||
if ('hassioToken' in tokens) {
|
||||
return _createConnection({
|
||||
auth: createLongLivedTokenAuth(tokens.hassURL, tokens.hassioToken),
|
||||
});
|
||||
}
|
||||
return _createConnection({
|
||||
auth: createLongLivedTokenAuth(wsURL, 'xxx'),
|
||||
});
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line
|
||||
throw {
|
||||
originalError: JSON.stringify(error),
|
||||
message: translateErrorCodes(error as any),
|
||||
tokens,
|
||||
}
|
||||
}
|
||||
throw tokens
|
||||
}
|
||||
|
||||
async function startHAConnection() {
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
import * as v from "types/validators";
|
||||
import { AutomationNode, AutomationNodeMapping, AutomationNodeSubtype, AutomationNodeTypes } from "types/automations";
|
||||
import { AutomationTrigger } from 'types/automations/triggers';
|
||||
import { AutomationTrigger, TriggerType } from 'types/automations/triggers';
|
||||
import { MiniFailure } from "types/validators/helper";
|
||||
import { getFailures } from '../types/validators/helper';
|
||||
import { Struct } from "superstruct";
|
||||
import { ActionType } from "types/automations/actions";
|
||||
import { ConditionType } from "types/automations/conditions";
|
||||
|
||||
export const getNodeTypeAndValidate = (node: AutomationNode, allowedTypes: AutomationNodeTypes[]) => {
|
||||
const nodeType = getNodeType(node);
|
||||
if (allowedTypes.includes(nodeType)) {
|
||||
return nodeType
|
||||
}
|
||||
throw new Error(`Detected '${nodeType}' but expected one of {${allowedTypes}}`)
|
||||
}
|
||||
|
||||
export const getNodeType = (node: AutomationNode): AutomationNodeTypes => {
|
||||
if ('condition' in node) {
|
||||
@@ -107,72 +117,75 @@ export const getNodeSubType = <T extends AutomationNodeTypes>(
|
||||
}
|
||||
}
|
||||
|
||||
const TriggerValidators: Record<TriggerType, any> = {
|
||||
"homeassistant": v.triggers.AutomationTriggerHA,
|
||||
"device": v.triggers.AutomationTriggerDevice,
|
||||
"event": v.triggers.AutomationTriggerEvent,
|
||||
"mqtt": v.triggers.AutomationTriggerMQTT,
|
||||
'numeric_state': v.triggers.AutomationTriggerNumericState,
|
||||
"state": v.triggers.AutomationTriggerState,
|
||||
"tag": v.triggers.AutomationTriggerTag,
|
||||
"template": v.triggers.AutomationTriggerTemplate,
|
||||
"time": v.triggers.AutomationTriggerTime,
|
||||
"time_pattern": v.triggers.AutomationTriggerTimePattern,
|
||||
"webhook": v.triggers.AutomationTriggerWebhook,
|
||||
"zone": v.triggers.AutomationTriggerZone,
|
||||
}
|
||||
|
||||
export const validateNode = (node: AutomationNode): MiniFailure[] | null => {
|
||||
const nodeType = getNodeType(node);
|
||||
const ActionValidators: Record<ActionType, any> = {
|
||||
"choose": v.actions.ChooseAction,
|
||||
"device": v.actions.DeviceAction,
|
||||
"event": v.actions.FireEventAction,
|
||||
"repeat": v.actions.RepeatAction,
|
||||
"service": v.actions.ServiceAction,
|
||||
"wait": v.actions.WaitAction,
|
||||
}
|
||||
|
||||
const ConditionValidators: Record<ConditionType, any> = {
|
||||
"and": v.conditions.LogicCondition,
|
||||
"or": v.conditions.LogicCondition,
|
||||
"not": v.conditions.LogicCondition,
|
||||
"numeric_state": v.conditions.NumericCondition,
|
||||
"state": v.conditions.StateCondition,
|
||||
"template": v.conditions.TemplateCondition,
|
||||
"time": v.conditions.TimeCondition,
|
||||
"trigger": v.conditions.TriggerCondition,
|
||||
"zone": v.conditions.ZoneCondition,
|
||||
}
|
||||
|
||||
const AllValidators: Record<AutomationNodeTypes, any> = {
|
||||
"action": ActionValidators,
|
||||
"condition": ConditionValidators,
|
||||
"trigger": TriggerValidators,
|
||||
}
|
||||
|
||||
export const validateNode = (node: AutomationNode, allowedNodeTypes: AutomationNodeTypes[] = []): MiniFailure[] | null => {
|
||||
let nodeType = getNodeType(node);
|
||||
let errors: MiniFailure[] = []
|
||||
if (allowedNodeTypes.length > 0 && !allowedNodeTypes.includes(nodeType)) {
|
||||
errors.push(
|
||||
{ "message": [`Got node of type "${nodeType}" but expected one of {${allowedNodeTypes}}`], path: "" }
|
||||
)
|
||||
nodeType = allowedNodeTypes[0]
|
||||
}
|
||||
let nodeSubType: null | AutomationNodeSubtype = null;
|
||||
try {
|
||||
const nodeSubType = getNodeSubType(node);
|
||||
if (nodeType === 'action') {
|
||||
if (nodeSubType === 'service') {
|
||||
return getFailures(node, v.actions.ServiceAction)
|
||||
} else if (nodeSubType === 'repeat') {
|
||||
return getFailures(node, v.actions.RepeatAction)
|
||||
} else if (nodeSubType === 'wait') {
|
||||
return getFailures(node, v.actions.WaitAction)
|
||||
} else if (nodeSubType === 'event') {
|
||||
return getFailures(node, v.actions.FireEventAction)
|
||||
} else if (nodeSubType === 'device') {
|
||||
return getFailures(node, v.actions.DeviceAction)
|
||||
} else if (nodeSubType === 'choose') {
|
||||
return getFailures(node, v.actions.ChooseAction)
|
||||
}
|
||||
} else if (nodeType === 'trigger') {
|
||||
if (nodeSubType === 'event') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerEvent)
|
||||
} else if (nodeSubType === 'homeassistant') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerHA)
|
||||
} else if (nodeSubType === 'mqtt') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerMQTT)
|
||||
} else if (nodeSubType === 'numeric_state') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerNumericState)
|
||||
} else if (nodeSubType === 'state') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerState)
|
||||
} else if (nodeSubType === 'tag') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerTag)
|
||||
} else if (nodeSubType === 'template') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerTemplate)
|
||||
} else if (nodeSubType === 'time') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerTime)
|
||||
} else if (nodeSubType === 'time_pattern') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerTimePattern)
|
||||
} else if (nodeSubType === 'webhook') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerWebhook)
|
||||
} else if (nodeSubType === 'zone') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerZone)
|
||||
} else if (nodeSubType === 'device') {
|
||||
return getFailures(node, v.triggers.AutomationTriggerDevice)
|
||||
}
|
||||
} else if (nodeType === 'condition') {
|
||||
if (['and', 'or', 'not'].includes(nodeSubType)) {
|
||||
return getFailures(node, v.conditions.LogicCondition)
|
||||
} else if (nodeSubType === 'numeric_state') {
|
||||
return getFailures(node, v.conditions.NumericCondition)
|
||||
} else if (nodeSubType === 'state') {
|
||||
return getFailures(node, v.conditions.StateCondition)
|
||||
} else if (nodeSubType === 'template') {
|
||||
return getFailures(node, v.conditions.TemplateCondition)
|
||||
} else if (nodeSubType === 'trigger') {
|
||||
return getFailures(node, v.conditions.TriggerCondition)
|
||||
} else if (nodeSubType === 'time') {
|
||||
return getFailures(node, v.conditions.TimeCondition)
|
||||
} else if (nodeSubType === 'zone') {
|
||||
return getFailures(node, v.conditions.ZoneCondition)
|
||||
}
|
||||
nodeSubType = getNodeSubType(node);
|
||||
|
||||
} catch (err) {
|
||||
errors.push(
|
||||
{ "message": [`Failed to identifiy subtype`], path: "" }
|
||||
)
|
||||
}
|
||||
if (nodeSubType) {
|
||||
const failures = getFailures(node, AllValidators[nodeType][nodeSubType]);
|
||||
if (failures) {
|
||||
errors = errors.concat(failures)
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(err)
|
||||
}
|
||||
if (errors.length > 0) {
|
||||
return errors
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
return [
|
||||
{ "message": ["Invalid or unknown " + nodeType], "path": "" },
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user