Compare commits

...
51 Commits
Author SHA1 Message Date
ari 6b21734041 added scene support 2022-08-06 22:43:56 -04:00
ari 754cc2ef98 added more support for trigger types 2022-08-06 22:37:26 -04:00
ari 1cb40288b1 remove state for zone 2022-08-06 20:41:02 -04:00
ari 129ba28ff5 v0.5.3 2022-08-06 20:28:09 -04:00
Ari Sosnovsky 44e246f79b Update README.md 2022-08-06 20:22:34 -04:00
ari 8bcbcaa801 added a redirect 2022-08-06 20:03:10 -04:00
ari b479476833 fixed up invalid node issue 2022-08-06 15:29:41 -04:00
Przemysław Adam Sowa baa31ab649 Don't use network host mode in the example docker-compose.yaml (#128) 2022-08-06 14:20:27 -04:00
Ari Sosnovsky dc7c6273e4 Update README.md 2022-08-06 13:16:34 -04:00
Ari Sosnovsky 2942b6173b Update README.md 2022-08-05 23:41:46 -04:00
ari bcfc648011 controls 2022-08-05 23:35:47 -04:00
ari 084d86ad7a fixed up build 2022-08-05 23:12:48 -04:00
ari ea6be4a8f3 infinte undo 2022-08-05 23:08:00 -04:00
ari 14649ac1fd added dial 2022-08-05 22:54:17 -04:00
ari f1b99cad1c trigger automation in metadata 2022-08-05 22:22:28 -04:00
ari ab7f50d4aa fixed trigger device validation 2022-08-05 22:04:31 -04:00
ari d22bba8c4d moving things around 2022-08-05 22:04:31 -04:00
ari 549f52655b refactor inputs 2022-08-05 22:04:31 -04:00
renovate[bot] 2c5d64ab86 Update dependency jss to v10.9.2 (#119)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-02 15:09:24 -04:00
renovate[bot] 7c50c345ec Update dependency react-jss to v10.9.2 (#120)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-02 15:09:13 -04:00
ari f4261f9701 better tag edit viz 2022-08-02 12:51:22 -04:00
ari 34826acb97 v0.5.1 2022-07-31 23:34:11 -04:00
ari cd1b4e8e2b ensuring scroll 2022-07-31 22:22:21 -04:00
ari 2b4c64c94b added ignore 2022-07-29 21:43:27 -04:00
ari 067f5fa642 added delay to save 2022-07-29 21:42:50 -04:00
ari 957b6a66fe fixed up deletes 2022-07-29 15:38:37 -04:00
ari e4af85cdfa consolidated ismobile 2022-07-29 15:16:47 -04:00
ari f99cb84658 cleaned up styles 2022-07-29 14:58:59 -04:00
ari 644edb2ef6 added saving for new 2022-07-29 14:56:26 -04:00
ari b4a9763ead added better tooling for local dev 2022-07-29 14:37:08 -04:00
ari 4551daedd3 fixed enqueue issue 2022-07-29 11:35:26 -04:00
ari fa4048e28c added state to effect 2022-07-29 10:47:59 -04:00
ari ea86f7f763 fixed minor socket connection issues 2022-07-29 10:45:42 -04:00
ari 9a26fc46d5 cleaned up unused 2022-07-29 10:00:56 -04:00
ari 35244bb107 mobile mode fixed 2022-07-28 23:00:35 -04:00
ari 883955e523 refactored entity listener so that live events actually come in 2022-07-28 22:27:57 -04:00
ari 57c86093a4 clean up 2022-07-28 21:50:23 -04:00
ari 2a827c24f6 automation updates 2022-07-28 21:05:36 -04:00
ari 473684efa6 delete auto 2022-07-28 17:59:00 -04:00
ari 3f0430ab37 new automation support 2022-07-28 17:54:15 -04:00
ari 96617e7b0c v1 of loaded manager 2022-07-28 15:43:00 -04:00
ari a9c3e9c890 templatized storymaking 2022-07-28 14:48:05 -04:00
ari 02ec81c16a moved control for tag update to tag db
renamed list to manager
2022-07-28 13:24:13 -04:00
ari 05d09830bb minor clean up 2022-07-27 21:32:31 -04:00
ari f16d25d41e moved sidebar 2022-07-27 21:11:36 -04:00
ari 104882cb25 tag editor 2022-07-27 21:09:30 -04:00
ari 5d9c04072b moved cleanupundefined
moved tags
2022-07-27 19:34:45 -04:00
ari 27314be9a8 added delete to story 2022-07-27 19:29:28 -04:00
ari f20eb271d9 initial v2 list 2022-07-27 19:27:30 -04:00
ari dfcbe9e76a v0.4.0 2022-07-26 20:35:07 -04:00
Ari Sosnovsky fca97b84ac Update README.md 2022-07-26 16:55:04 -04:00
191 changed files with 4605 additions and 3472 deletions

No files matched your search

+30
View File
@@ -1,5 +1,35 @@
# Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge)
## [0.5.3] - Bug Fixes
- Redirecting `/` to `/web` to resolve container install strangeness reported in https://github.com/asosnovsky/Shortumation/issues/125
- Fixed missing flag that caused the automation to explode in https://github.com/asosnovsky/Shortumation/issues/124
## [0.5.2] - Better Controls
- Add automation trigger
- Speed dial on the bottom
<img src="https://user-images.githubusercontent.com/7451445/183231968-9891bbb4-5c7c-4e05-b804-36978c809a5c.png" width="200px"/>
- Infinite undos <img src="https://user-images.githubusercontent.com/7451445/183231977-ed000017-2886-4a57-b5fb-c7e527bf3894.png" width="200px"/>
## [0.5.1] - Sidebar!
- completely redesigned the sidebar!
- Disable/enable automatons
- See 'bad state' automatons
- Delete automatons from registry (in cases where references are stale)
- Refactored sidebar UX to match MUI standards
- Cleaned up editing tags in sidebar
<img src="https://user-images.githubusercontent.com/7451445/182066721-07a93651-2f83-44d5-8420-15093caa52df.png" width="400px"/>
- Websockets now live-refresh when updates occur
## [0.4.0] - Depedency update
- Core dependency updates
- Python port is now dynamically set
## [0.3.4] - Condition/Trigger Editor Upgrades!
- Many condition editor fixes
-46
View File
@@ -1,46 +0,0 @@
BUILD_TAG=$(shell git describe --tags | sed 's/\([^-]*-g\)/r\1/;s/-/./g')
DC=BUILD_TAG=${BUILD_TAG} docker-compose -f docker-compose.build.yaml -f docker-compose.test.yaml
build-with-builder:
docker run \
--rm \
--privileged \
-v ~/.docker:/root/.docker \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
-v ${PWD}:/data \
homeassistant/amd64-builder \
--amd64 \
--test \
--version ${BUILD_TAG} \
-t /data
build:
cd webapp && yarn build
$(DC) build
build-no-cache:
cd webapp && yarn buil
$(DC) build --no-cache
push:
$(DC) push
start:
$(DC) up -d
sleep 1
$(DC) ps
logs:
$(DC) logs -f
ps:
$(DC) ps
stop:
$(DC) stop
bash:
$(DC) exec addon bash
config:
$(DC) config
+10 -6
View File
@@ -1,4 +1,4 @@
# Shortumation ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=platsic)
# <img src="logo.png" height="40x"/> Shortumation ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=platsic)
[![Test](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml) [![Build](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml)
@@ -6,7 +6,9 @@
| ------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| Version | ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge) | ![Docker Image Version (latest semver)](https://img.shields.io/docker/v/asosnovsky/shortumation-amd64?&sort=date&label=&style=for-the-badge) |
A [home-assistant addon](https://www.home-assistant.io/addons/) for a better UI for managing and writing your automations. We provide a way to visualize your automation using a visual-programming language that draws inspirations from [Node-Red](https://nodered.org/).
A [home-assistant addon](https://www.home-assistant.io/addons/) for a better UI for managing and writing your automations. We provide a way to visualize your automation using a visual-programming language that draws inspirations from [Node-Red](https://nodered.org/).
<img src="./assets/comparisons.png">
## Features
@@ -34,7 +36,7 @@ A [home-assistant addon](https://www.home-assistant.io/addons/) for a better UI
<img src="https://user-images.githubusercontent.com/7451445/179135790-a5e77e2b-6d42-4810-a27b-ff4d165e99ec.png" width="500px"/>
See roadmap in [Version 1 Github Project](https://github.com/asosnovsky/Shortumation/projects/1).
See roadmap in [Version 1 Github Project](https://github.com/users/asosnovsky/projects/3/views/4).
## Installation
@@ -46,12 +48,14 @@ Add the repository URL under **Supervisor → Add-on store → ⋮ → Manage ad
It should now appear in your `Add-on Store` and you should be able to install it!
**Please note that you may need to enable advance mode in your settings first!**
### Containerized or HA Core
Please note that this way of using Shortumation is **not future proof**.
If this warning does not scare you or you still want to try things out, then take a look at the example [docker-compose.yaml](example/containerized/docker-compose.yaml), or read the [extended guide here](https://github.com/asosnovsky/Shortumation/wiki/Installation#containerized--ha-core).
In general, if you want to help provide this to more home-assistant fans please join on the conversation here https://github.com/asosnovsky/Shortumation/issues/102 or help contribute :)
## FAQ
**How is this different from Node-Red?**
@@ -68,7 +72,7 @@ If this warning does not scare you or you still want to try things out, then tak
**This is awesome and all, how can I help?**
> Take a look at our Roadmap in [Version 1 Github Project](https://github.com/asosnovsky/Shortumation/projects/1), the [Development Guide](https://github.com/asosnovsky/Shortumation/wiki/Development) and send me some PRs to review!
> Take a look at our Roadmap in [Version 1 Github Project](https://github.com/users/asosnovsky/projects/3/views/4), the [Development Guide](https://github.com/asosnovsky/Shortumation/wiki/Development) and send me some PRs to review!
> Please also note that I did went ahead and marked some [good first issues](https://github.com/asosnovsky/Shortumation/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) if you want to pick them up just leave a comment and I will give you more context (I haven't had time to add more details).
+3
View File
@@ -0,0 +1,3 @@
LOG_LEVEL=DEBUG
SUPERVISOR_TOKEN=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI2ZjJiYzM2MjkyOWM0OGM1Yjg1NzgxNDEzNTRkNDk0NSIsImlhdCI6MTY1OTExMTExMCwiZXhwIjoxOTc0NDcxMTEwfQ.Q5Ei1a9BXyB4-whrPGoko6CKavOOloFC1fbP-jAYBpU
HASSIO_WS=ws://homeassistant:8123/api/websocket
+1
View File
@@ -143,3 +143,4 @@ dmypy.json
cython_debug/
# End of https://www.toptal.com/developers/gitignore/api/python
development_config
+14
View File
@@ -0,0 +1,14 @@
{
"recommendations": [
"njpwerner.autodocstring",
"bungcip.better-toml",
"ms-azuretools.vscode-docker",
"editorconfig.editorconfig",
"eamodio.gitlens",
"esbenp.prettier-vscode",
"ms-python.vscode-pylance",
"ms-python.python",
"redhat.vscode-yaml",
"ninoseki.vscode-pylens"
]
}
+12
View File
@@ -0,0 +1,12 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "Docker: Server",
"group": "none",
"command": ["make start-docker"],
"problemMatcher": []
}
]
}
+6 -4
View File
@@ -40,7 +40,9 @@ clean:
find . -type d -name "__pycache__" -exec rm -r {} +
find . -type d -name "*tmp" -exec rm -r {} +
run-local:
rm -f web
ln -s ../webapp/build web
USE_EXAMPLE_REPO=1 $(VENV_BIN)/hypercorn src.app:app --reload
start-docker:
rm -rf ./development_config
tar -xvf ../development_config.tar.gz -C ./
cp ./development_config/.env .env.api
docker-compose down
docker-compose up
+1 -1
View File
@@ -8,4 +8,4 @@
`make lint`: run all linter and code formatting
`make run-local`: starts the api locally
`make start-docker`: starts the api locally
+34
View File
@@ -0,0 +1,34 @@
version: '3'
services:
homeassistant:
image: "ghcr.io/home-assistant/home-assistant:stable"
volumes:
- ./development_config/config:/config
restart: unless-stopped
networks:
- main
ports:
- 8124:8123
addon:
image: "asosnovsky/shortumation-${ARCH:-amd64}:${BUILD_TAG:-edge}"
build:
context: "../"
dockerfile: "../Dockerfile"
args:
BUILD_ARCH: ${ARCH:-amd64}
BUILD_VERSION: ${BUILD_TAG:-edge}
volumes:
- "./development_config/config:/config"
- "./:/app"
- "../docker/bin:/app/bin"
- "../webapp/build:/app/web"
networks:
- main
ports:
- "8001:8000"
env_file:
- ./development_config/.env
entrypoint: hypercorn src.app:app --reload -b 0.0.0.0:8000
networks:
main:
+11 -1
View File
@@ -1,6 +1,7 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
from src.automations.manager import AutomationManager
from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER
@@ -10,7 +11,8 @@ from .routes import automations, details, ping, socket
def make_app(automation_mgr: AutomationManager) -> FastAPI:
app = FastAPI()
if (ROOT_FOLDER / "web").exists():
has_web_folder = (ROOT_FOLDER / "web").exists()
if has_web_folder:
app.mount(
f"{API_PREFIX}/web",
StaticFiles(
@@ -19,6 +21,7 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
),
name="web",
)
else:
print("WARN: could not find web folder")
app.add_middleware(
@@ -36,4 +39,11 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
details.make_details_router(automation_mgr.hass_config), prefix=f"{API_PREFIX}/details"
)
app.include_router(socket.router, prefix=f"{API_PREFIX}/socket")
@app.get("/")
def get_index():
if has_web_folder:
return RedirectResponse("/web")
return RedirectResponse("/details")
return app
+2 -2
View File
@@ -11,11 +11,11 @@ def find_hass_config() -> HassConfig:
if config("USE_EXAMPLE_REPO", False, cast=bool):
print("using USE_EXAMPLE_REPO")
from tests.utils import (
HA_CONFIG3_EXAMPLE,
HA_CONFIG2_EXAMPLE,
create_copy_of_example_config,
)
path = create_copy_of_example_config(HA_CONFIG3_EXAMPLE)
path = create_copy_of_example_config(HA_CONFIG2_EXAMPLE)
print("|-> ", path)
return HassConfig(path)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

+1 -1
View File
@@ -1,5 +1,5 @@
name: Shortumation
version: v0.3.4
version: v0.5.3
slug: shortumation
image: asosnovsky/shortumation-{arch}
url: "https://github.com/asosnovsky/Shortumation"
Binary file not shown.
-10
View File
@@ -1,10 +0,0 @@
version: '3'
services:
addon:
image: "asosnovsky/shortumation-${ARCH:-amd64}:${BUILD_TAG:-edge}"
build:
context: "./"
dockerfile: "./Dockerfile"
args:
BUILD_ARCH: ${ARCH:-amd64}
BUILD_VERSION: ${BUILD_TAG:-edge}
-10
View File
@@ -1,10 +0,0 @@
version: '3'
services:
addon:
volumes:
- "./sample_config:/config"
- "./api/tests:/app/tests"
ports:
- "8000:8000"
env_file:
- api/.env
+1
View File
@@ -9,6 +9,7 @@ pushd $api_location
echo "--------------------"
echo "BUILD_VERSION = "$BUILD_VERSION
echo "HOST = $host_port"
echo "HASSIO_WS = $HASSIO_WS"
echo $(python --version)
echo "--------------------"
python -m hypercorn src.app:app -b $host_port
+5 -2
View File
@@ -12,9 +12,12 @@ services:
shortumation:
# make sure to replace the ARCH with whatever system you are running!
image: "asosnovsky/shortumation-${ARCH:-amd64}:${SHORTUMATION_VERSION:-latest}"
network_mode: host
ports:
- 8000:8000
extra_hosts:
- "host.docker.internal:host-gateway"
volumes:
- ./config:/config
environment:
- SUPERVISOR_TOKEN=${SUPERVISOR_TOKEN}
- HASSIO_WS=ws://0.0.0.0:8123/api/websocket
- HASSIO_WS=ws://host.docker.internal:8123/api/websocket
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
-1
View File
@@ -1 +0,0 @@
<mxfile host="Electron" modified="2021-12-22T03:59:52.849Z" agent="5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/13.7.3 Chrome/85.0.4183.98 Electron/10.1.2 Safari/537.36" etag="tLc5i3WharxOLc8-v9Jg" version="13.7.3" type="device" pages="2"><diagram id="jPQkoFvJ-TX3pFbO5KUV" name="autos">7V1bk5s4Fv41rtp5aBfizmM6l9mZ7exkJpNN5qkLg2yzwcgFuNvOrx9oI2wktQ22JATj9EOMwBi+c3TuOpoYb1fbn1N/vfyIQhhPdC3cTox3E10HuuMW/5Uju/2IrVUDizQKq4sOA5+jH7Aa1KrRTRTCrHFhjlCcR+vmYICSBAZ5Y8xPU/TcvGyO4uavrv0FpAY+B35Mj36Nwny5H3Ut7TD+bxgtlviXgVadWfn44mogW/ohej4aMt5PjLcpQvn+02r7FsYleBiX/fc+vHK2frAUJnmbL3x9cr+iHx/m/m/hl49go2lf7t7c2fr+Nk9+vKneuHrafIchSNEmCWF5FzAx7p+XUQ4/r/2gPPtcEL0YW+aruDpNP1X1oE8wzeH2aKh6yp8hWsE83RWXVGdtp0KsYhlgVsfPBwKYXjW2PAK/YK6K8BXRF/W9D7gUHypoOsAEXI2CBYYFo1SHKM2XaIESP35/GL0PNulTjdsBRa04OnzhAaF1dcn/YZ7vqingb3LURLYANN19q77/cvBXeTC18OG77fHJd7vq6FWK5H66gPmpt3as/ZXlq56kXApjP4+emnOGRYXqq59QVDxMTXEPWFPt6J/VoL/lmM0bZmiTBrC6B0HZ+qEuJ7ah3pQwdGJKGBY1JQzAmhKGqCnhKogSITh0jUaplhHHKAFxgoNCyU/C64CaR3H8FsUoffmuEfrQnQfFeJan6Ds8OmMHLpzNizN+HC2SYiwooIWpPI60GFAL40eTQjqHq3UhliBfuC3ohiYLblefGbYthpNrSdwXuhaFbpYX0Gb/issfn36P8mAJk58muu2vSgCTWbZ+gUKbTqe9CwaTZFYGnMCQiadN4ZmgXLZckCRypTIqoOXARL/niux8PtcDJrKhPbMtXiLAbVpBOsMK1lkaXxiyDoXsli+ubgDZuM5cy7RO2rIdcLUIWeAyjASWjSDOtxglrjroGVdskA4cVxMQuJo942oACsXzrnBv3i+MZy9BlxLwKPBj0i1/lUJ7J/MUf1Xy8KwbrXsTzl70dfOCluN5tLrSSvbToCKdyctmI8S0Tqs/wOJ7Ya4cNln+8XzvDpPvbeMC+nEO4W2j/NvR5yNSFkcHSpYHu2Oy8gz7nSew15LAhlL0xY99KiJV3CZaZ7CFPMvW+2zCPNqWFO/Hu6KEYN8+gEH7rd8okIuXywk0yQAUlkpvqhOrKAz38hJm0Q9/9nKrkovXZZD35S2s+4n1rrxXMauy/QQDFP4JSiBBrGqIh0ZyCGLoPRODVuQULbLvMA+Wx2DC9P0T3GP6gh/OSpUXhH62rOXbEf3Ogjwpzf/yrxiP/RmMPxU0yiPEJPoDccEM5TlaMbgiL8XqPdrkcZQUv44TfBqLo4r3WJfvvNouykTkFM3nUQCnAUoCuM6z6XNa/FyyeFzDJIhiPgxRh4xOcAT2ghqmuSWII7B4OMURi0KLrdu/fJ1ZrSbl5Dh52cJu07W+7Tad9q9D+FQwBwUNX4v3NIXOM1l/hm6L1M5NrrSXK9cyAk6SEhOLEcKWKWsM2twarCnAiUJN+4DhsEo1D6wWeWzRysAjmNbo3Yu36PxA9lxmr6b5Jk0eJ7odlxw7S4tPi/ITSq7OYF2mKmr6KawqLDoveFMVvFVFB0ZQU1VYI/IaOVFIMVXRwpMUrSqApjW5ti7K6U+60YbwCoaR/7iO/R1Mp7SyKE889qQunFcooZK6aBGiu6mLa9VFe0ZQU11g9huvuuhMIbXUhU1XNQ4xs26QCse0W+EqLLNu09Z0NOcLrJTSJYcE1jEoYE0GsOKq7VwKxcFX759N49kVN59N42EzR5E8nk17CxlMMpTiKtPH5WalQFGp45Fcrk97LyulDflks4JpFNC26ksBL1fpIqc22iGTogzpIrXk1KatWhiPQnDrmsdgaami29EpcClgZUcxddNkzXSprpRDR3cVjWPWFFTYMXVYVeM3x5SvY9qBEdR0TB3aPh+XY9qdQmo5pmNcpXvWznfa1iHj1Jcidr5D26owzvhapP2YTQZrwbpMo8llGU1DXATlXLj4QZyEoc2uIYa+bJfwofpeBOXSTv8gcXW8Jr/ixV294arA4rKD28ANZnINn9XO8BAHMx0CCJYIcdZmPS31t+0mU7Oq0B0gUb15ClQ2mUTtr87of1DXvjZ4UFwHBJtCYbjW70nCn7WJq+vOmsS4/ZHoBjc6sUz+zqtjxfgm+2cV1tSmReb9ygD66anaKfgjeeLQjkgPTVqEAirV+8BadkBJiGuhxpqS8ANpPSm3Fwadp29m0vhn0TgBCcBZJFkN4MQhSTvUo+ZcRumdXM59NbtRc+5QWJcBpVTW1VnGsgKxIF5wE4Ki5/iQTieSFIhjcMKaSLy3XIwsrsELnY4ZLdZO31jT8bkxSRGn2WvLa4e2MCnitUhHiw5wkGU27FoQyZ6aZ1E4jC3EwT1Jp2xEgiVSZJh0eHKpHJLwBhWTuAhRqTEJj86DDDMm0R5qNWMSHh2I7Ccm0RlI5WISWCINJShxLev2HpTQGPG0fqISVzNv31EJoNERNYUdiu54qxWWAJqSdSucwFYsLgG0AQWBrgW778AE0FgtKMYjSBSLTABtTEUGbUtsvbZL6Ry1WmICjdXYQYHJ0b3VHtVrz+19JrDapI0CW5Z1KBlbVrnKKLBl1YbLxRbv4/BP72MNQNtG1vVaNFXEOmPLCBVbuBNVumbvDX0A8G68v+doc6i8byjQxl26AVpT4Ty9DMXohZ98TG3ZScHWuy2q05HJwa5M7a5mHIIaet/UYMU2CWLcVpOLbMxORgQZLCF15ThgVuERLCG6ooOQWhbDE5FsjjGq5fprzX6gkcKNKgCj6O0mW3h3qujCCmq2qgCMgr3BWgS8aKRWswrQZsMi0TqB3MbZtFhVfpJlnEG7DFcXP12qE7xXkFZJJxi09X/TCfx1QntWUFQnGLRfMjad0JlGiukE45IA5eCjW1jgt4huVZNDlejWgDvLXrIZ5TU0ttrSGLeXFl0Cb5NRAtz+DN9i/1LCCuCBPdzJLox5rPmd8eT9iX6/M+/e/Io+peHu4Q60Zh3u4uEV1iFKUy2H0AivrJ04z4OebB5sEZ4XvvUH8BT0Qhhd7tXd/eNAR5UdFdxu5eaoiHRUOrCCoo6KTUfLR+aodKeRYo6KrcISVatZHGuZdCd42RKODs8r2pb7QEGlNUaLRaI3jXG1xuhclq6cxqALncemMbovHVBLYzisKPUga3oNLITqwAG7NYJUdFmm9RDRdd0muBbeNLA/aBXtoNS9mzZhL9mgd5mggBUJNECakSatzeSaPYydJhSOPThDsCSdmyUpwZLswAqKWpKMbSlGZkl2p5FqluR4Vt6ZhOqx5Rk7+h/G/d0vyS+/z379r2s/fPnffx7+umPZ6JL1sUXspqJEMsCgFTKPBv9nFe5JIqmsbo2buuWqbq9khFeULXPHUrk1SSNSt3xo1FS2wJEYWjiVfB/R+i1y9yMLryA6ghjXVDa6IXEoI2JCPNwljZfUgcAkfJOmL3K9mkrFyIeohExEkdEpphZdJ+KQa26wfde5ToSs03Y9sl0nv0oRJmKX9H3hwJY1qwSxn2VR0OAW4eWKTCRaL53m3w2mHZfZpC7g18n1FCDnNnIcmpYg9nKzNVoRi9rcnQnzcHsfD1VLSOrFfLlw5yYKCqj93dFllZUsQFiwOlLd/EJ5a6NtvCVkbZLY4pzA4jBFKD/moPJFP6IQllf8DQ==</diagram><diagram id="7X2k5OJ-jCNTzSic57L4" name="Page-2">5Zlbc9o8EIZ/DZdhZMnGcJlAekyaTunXdnrTUWxhayJbrixO/fXfCsuAEU1IG4cwhQvs1cl63vVqJTpkmC1eK1qk1zJmooNRvOiQUQdjD5E+/BjLsrL0kDUkise20sYw5r9Y3dJapzxmZaOillJoXjSNkcxzFumGjSol581qEymaoxY0YY5hHFHhWr/yWKeVtY/Djf0N40laj+z1BlVJRuvKdiZlSmM53zKRyw4ZKil1dZUthkwYeDWXvr794NPPfoh+RFdfxvLbMsJnVWevHtNkPQXFcv3HXY9wcF32hmefv7+ek7dSq7dfRmeexTCjYmqB2cnqZU1QyWkeM9ML6pCLeco1Gxc0MqVz8BmwpToTcOfB5YQLMZRCqlVbMgnMF+ylVvKObZX0Vh/TQuZ6y159wG4fjCnNFjtSPsDBW4sDXs1kxrRaQjvbi2/ltP5MQns/33gHRtaWbnnG2kitRybrrjfU4cKCf4QI/r+uweBQCfpPIMHexyWOBFd8xvMEbJ+kzODnYqq1zO8RxntYmLZw9ps4vT08PbyHp98WTtejbyYTDlQwupaaG47o5oXCDJswfXxsmMEhMCeT06C5J9o+L83eATSvmaYngTN4Tufcu3a5gdMBlwC54rdAbN5Hb+vqqJWQ6B/b77AD6j3XUcry51xbfi+hC/JoLuWSasGlHkPC+lDYDVwf8gKXDH4CMuLupxz9t/hYTNOrAH8IZrPRO5vg30umvGPgVTZPLCTPNVOXM5h2af1kvYsxFWJapuuscsuZmpliLnPmppUBMl+wC3rLxEdZ8lX0JKOImUGhwEjDYSd2tVPhVoK7Z1sVzgVPTIGWxqnlVAuew+j1htAMQm2Vdecwj8LMOVskZuPalaso3gXLine truncated
-13
View File
@@ -1,13 +0,0 @@
0:
Type: Generic2
1:
Type: Generic
2:
Type: Climate
Room: House
4: {}
3:
Type: Vent
Room: Bathroom
Floor: First
5: {}
-66
View File
@@ -1,66 +0,0 @@
- id: '1616887975473'
alias: Home Assistant Off
description: ''
trigger_variables:
mode: single
trigger:
- platform: homeassistant
event: shutdown
- $smType: trigger
platform: device
device_id: ''
domain: ''
type: ''
subtype: ''
condition: []
action:
- device_id: 2a98db84af7526c7ec3cc7aebd1a9e1c
domain: mobile_app
type: notify
title: Hassio Status
message: Hassio Is turning off...
- choose: []
default: []
alias: choose better days
- id: '1616888026264'
alias: Home Assistant On
description: ''
trigger_variables:
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- device_id: 2a98db84af7526c7ec3cc7aebd1a9e1c
domain: mobile_app
type: notify
title: Hassio Status
message: Home assistant is up!
- id: shortu-2
alias: Neat trick
description: ''
mode: queued
trigger: []
condition: []
action:
- alias: Choose
default:
- condition: and
alias: ''
conditions:
- condition: or
conditions: []
choose: []
- service: lights.turn_on
target:
entity: bear
data: {}
- id: shortu-3
alias: Bathroom Vent
description: Turn the vent on when the humidity is high or it's smelly
trigger_variables:
mode: single
trigger: []
condition: []
action: []
-2
View File
@@ -1,2 +0,0 @@
# empty configuration file
cloud:
+1 -1
View File
@@ -21,4 +21,4 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*
development_config
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
set -e
BIN_DIR="$( realpath $( dirname -- "${BASH_SOURCE[0]}" ) )"
VSCODE_DIR="$( dirname ${BIN_DIR} )"
WEBAPP_DIR="$( dirname ${VSCODE_DIR} )"
ROOT_DIR="$( dirname ${WEBAPP_DIR} )"
pushd $WEBAPP_DIR
rm -rf $WEBAPP_DIR/development_config
tar -xvf ../development_config.tar.gz -C $WEBAPP_DIR/
docker-compose down
docker-compose up
+13
View File
@@ -0,0 +1,13 @@
{
"recommendations": [
"njpwerner.autodocstring",
"aeschli.vscode-css-formatter",
"paulmolluzzo.convert-css-in-js",
"ms-azuretools.vscode-docker",
"editorconfig.editorconfig",
"eamodio.gitlens",
"orta.vscode-jest",
"esbenp.prettier-vscode",
"pmneo.tsimporter"
]
}
+77 -58
View File
@@ -1,59 +1,78 @@
{
"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
},
]
}
"version": "2.0.0",
"tasks": [
{
"icon": {
"id": "server-environment"
},
"type": "shell",
"label": "Docker: Start Server",
"group": "none",
"command": [".vscode/bin/start-docker-server.sh"],
"runOptions": {
"runOn": "folderOpen"
},
"problemMatcher": []
},
{
"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,
"runOptions": {
"runOn": "folderOpen"
}
},
{
"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,
"runOptions": {
"runOn": "folderOpen"
}
}
]
}
+13 -44
View File
@@ -1,50 +1,19 @@
## Available Scripts
# Development Guide
In the project directory, you can run:
## Prerequisites
### `yarn storybook`
- https://code.visualstudio.com/
- https://nodejs.org/en/
- https://www.docker.com/
Spins up the prototyping tool storybook.\
Open [http://localhost:6006](http://localhost:6006) to view it in the browser.
## Setup
The page will reload if you make edits.\
You will also see any lint errors in the console.
Open this folder directly with vscode. As soon as it happens you will be prompted to install certain extensions and you should see a few tasks automatically spin up. Primarily:
### `yarn start`
- `npm: tsc`: scans code and validate the syntax is correct
- `npm: test`: automatically run test cases
- `npm: start`: automatically starts the webap on port `3000`
- `npm: storybook`: automatically starts storybook on port `6006` (I recommend you develop containers using this first!)
- `Docker: Server`: this will start the Shortumation server as well as a development Homeassistant container (you can access these over locahost:8123 and localhost:8000).
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
If you don't need some of these, you can turn them off by selecting the 'trash can' icon to their right.
+34
View File
@@ -0,0 +1,34 @@
version: '3'
services:
homeassistant:
image: "ghcr.io/home-assistant/home-assistant:stable"
volumes:
- ./development_config/config:/config
restart: unless-stopped
networks:
- main
ports:
- 8123:8123
addon:
image: "asosnovsky/shortumation-${ARCH:-amd64}:${BUILD_TAG:-edge}"
build:
context: "../"
dockerfile: "../Dockerfile"
args:
BUILD_ARCH: ${ARCH:-amd64}
BUILD_VERSION: ${BUILD_TAG:-edge}
volumes:
- "./development_config/config:/config"
- "../api:/app"
- "../docker/bin:/app/bin"
- "./build:/app/web"
networks:
- main
ports:
- "8000:8000"
env_file:
- ./development_config/.env
entrypoint: hypercorn src.app:app --reload -b 0.0.0.0:8000
networks:
main:
+2 -2
View File
@@ -17,7 +17,7 @@
"@uiw/react-codemirror": "4.10.4",
"autosuggest-highlight": "3.3.4",
"home-assistant-js-websocket": "7.1.0",
"jss": "10.9.1",
"jss": "10.9.2",
"material-ui-confirm": "3.0.4",
"notistack": "2.0.5",
"react": "18.2.0",
@@ -25,7 +25,7 @@
"react-dom": "18.2.0",
"react-flow-renderer": "10.3.12",
"react-imask": "6.4.2",
"react-jss": "10.9.1",
"react-jss": "10.9.2",
"react-router-dom": "6.3.0",
"react-scripts": "5.0.1",
"superstruct": "0.16.0",
+10 -8
View File
@@ -1,12 +1,14 @@
import App from "./App";
import { withQuery } from "@storybook/addon-queryparams";
import { makeStory } from "devUtils";
const book = {
title: "App/App",
decorators: [withQuery],
component: App
};
const { make, componentMeta } = makeStory({
Component: App,
meta: {
title: "App",
decorators: [withQuery],
},
});
export default componentMeta;
export const Basic = () => <App />
export default book;
export const RootApp = make({});
+18 -16
View File
@@ -1,22 +1,24 @@
import { AutomationData } from 'types/automations';
import { makeAutomationAPI } from './automations';
import { AutomationData } from "types/automations";
import { makeAutomationAPI } from "./automations";
import { makeRemoteAPI } from "./base";
import { useAPIService } from './core';
import { useAPIService } from "./core";
import { useMockAPI } from "./mock";
import { useRef } from "react";
const locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i);
const baseURL = new URL(
process.env.NODE_ENV === 'development' ?
`http://${window.location.hostname}:8000` :
window.location.origin + (!locationPrefixWeb ? '' : locationPrefixWeb[1])
);
export const wsURL = baseURL + "socket"
export const remoteAutoAPI = makeRemoteAPI(
baseURL + "automations"
);
export const useConnectedApiService = () => useAPIService(
makeAutomationAPI(remoteAutoAPI)
);
export const useMockApiService = (initialAutos: AutomationData[]) => useAPIService(
makeAutomationAPI(useMockAPI(initialAutos))
process.env.NODE_ENV === "development"
? `http://${window.location.hostname}:8000`
: window.location.origin + (!locationPrefixWeb ? "" : locationPrefixWeb[1])
);
export const wsURL = baseURL + "socket";
export const remoteAutoAPI = makeRemoteAPI(baseURL + "automations");
export const useConnectedApiService = () =>
useAPIService(makeAutomationAPI(remoteAutoAPI));
export const useMockApiService = (
initialAutos: AutomationData[],
returnErrors: boolean = false
) =>
useAPIService(
makeAutomationAPI(useMockAPI(initialAutos, useRef, returnErrors))
);
+8 -1
View File
@@ -9,11 +9,18 @@ import {
export const useMockAPI = (
initialAutos: AutomationData[] = [],
makeRef = useRef
makeRef = useRef,
returnErrors: boolean = false
): API => {
const automationsRef = makeRef(initialAutos);
return {
async makeCall({ path, method = "POST", data = {} }) {
if (returnErrors) {
return {
ok: false,
error: "Test Error",
};
}
// console.debug("[[mockCall]]", method, path, data);
if (path === AUTOMTAION_LIST) {
return {
@@ -1,25 +1,27 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { makeTagDB } from "components/AutomationList/TagDB";
import { Page } from "components/Page";
import { useTagDB } from "components/AutomationManager/TagDB";
import { useState } from "react";
import { AutoInfoBox } from "./AutoInfoBox";
import { defaultAutomation } from "utils/defaults";
import { AutoInfoBox, AutoInfoBoxProps } from "./AutoInfoBox";
import { makeStory } from "devUtils";
export default {
title: "App/AutomationList/Editor/InfoBox",
component: AutoInfoBox,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
tagDB: makeTagDB([defaultAutomation("test")]),
const { componentMeta, make } = makeStory({
meta: {
title: "App/AutomationEditor/InfoBox",
},
} as ComponentMeta<typeof AutoInfoBox>;
Component: (args: {
metadata: AutoInfoBoxProps["metadata"];
tags: AutoInfoBoxProps["tags"];
onUpdate: AutoInfoBoxProps["onUpdate"];
}) => {
const [[metadata, tags], setState] = useState([args.metadata, args.tags]);
const tagDB = useTagDB(
[{ id: metadata.id, tags: Object.fromEntries(tags) }],
(_, t) => setState([metadata, Object.entries(t)])
);
export const NoTags: ComponentStory<typeof AutoInfoBox> = (args) => {
const [[metadata, tags], setState] = useState([args.metadata, args.tags]);
return (
<Page>
return (
<AutoInfoBox
{...args}
tagDB={tagDB}
metadata={metadata}
tags={tags}
onUpdate={(m, t) => {
@@ -27,11 +29,12 @@ export const NoTags: ComponentStory<typeof AutoInfoBox> = (args) => {
setState([m, t]);
}}
/>
</Page>
);
};
NoTags.args = {
...NoTags.args,
);
},
});
export default componentMeta;
export const NoTags = make({
tags: [],
metadata: {
id: "random",
@@ -42,11 +45,9 @@ NoTags.args = {
},
mode: "single",
},
};
});
export const SomeTags: ComponentStory<typeof AutoInfoBox> = NoTags.bind({});
SomeTags.args = {
...SomeTags.args,
export const SomeTags = make({
tags: [
["Room", "Bathroom"],
["Type", "Climate"],
@@ -60,4 +61,4 @@ SomeTags.args = {
},
mode: "single",
},
};
});
@@ -1,21 +1,21 @@
import "./AutoInfoBox.css";
import { AutomationMetadata } from "types/automations";
import { InputList } from "components/Inputs/InputList";
import InputText from "components/Inputs/InputText";
import InputText from "components/Inputs/Base/InputText";
import { FC, ReactNode, useRef, useState } from "react";
import { AddIcon, TrashIcon } from "components/Icons";
import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "components/AutomationList/TagDB";
import { TagDB } from "components/AutomationManager/TagDB";
import { ButtonIcon } from "components/Icons/ButtonIcons";
interface Props {
export interface AutoInfoBoxProps {
metadata: AutomationMetadata;
tags: Array<[string, string]>;
onUpdate: (m: AutomationMetadata, tags: Array<[string, string]>) => void;
tagDB: TagDB;
children?: ReactNode;
}
export const AutoInfoBox: FC<Props> = ({
export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
metadata,
tags,
onUpdate,
@@ -0,0 +1,23 @@
.mobile .automation-editor--flow-wrapper--toolbar {
align-items: center;
}
.mobile .automation-editor--flow-wrapper--toolbar--title {
padding-left: 2.5em;
justify-content: center;
flex-direction: column;
}
.mobile .automation-editor--flow-wrapper--toolbar--title--text .input-text-view.view span {
max-height: 1.25em;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
word-wrap: break-word;
}
.mobile .automation-editor--flow-wrapper--toolbar--title--text .id,
.mobile .automation-editor--flow-wrapper--toolbar--title .input-text-view.description,
.mobile .automation-editor--flow-wrapper--toolbar--edit-btn {
display: none;
}
@@ -1,13 +1,12 @@
import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { AutomationEditor } from "./index";
import { useState } from "react";
import { Page } from "components/Page";
import { makeTagDB } from "components/AutomationList/TagDB";
import { useTagDB } from "components/AutomationManager/TagDB";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
export default {
title: "App/AutomationList/Editor",
title: "App/AutomationEditor",
component: AutomationEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
@@ -21,7 +20,10 @@ const Template: ComponentStory<typeof AutomationEditor> = (args) => {
<Page>
<AutomationEditor
{...args}
tagDB={makeTagDB(state ? [state] : [])}
tagDB={useTagDB(
state ? [{ id: state.metadata.id, tags: state.tags }] : [],
() => {}
)}
automation={state}
onUpdate={(s) => {
window.setTimeout(() => setState(s), 3000);
@@ -1,36 +1,54 @@
import "./index.css";
import Icon from "@mui/material/Icon";
import { CheckMarkIcon } from "components/Icons";
import "./index.mobile.css";
import { FC, useState } from "react";
import { AutomationData } from "types/automations";
import { Modal } from "components/Modal";
import { AutoInfoBox } from "./AutoInfoBox";
import ModeEditOutlineTwoToneIcon from "@mui/icons-material/ModeEditOutlineTwoTone";
import { Button } from "components/Inputs/Button";
import { useAutomatioEditorState, EditorData } from "./state";
import { MiniFailure } from "types/validators/helper";
import InputYaml from "components/Inputs/InputYaml";
import { TagDB } from "components/AutomationList/TagDB";
import { useCookies } from "react-cookie";
import Skeleton from "@mui/material/Skeleton";
import LinearProgress from "@mui/material/LinearProgress";
import { useCookies } from "react-cookie";
import SpeedDial from "@mui/material/SpeedDial";
import SpeedDialAction from "@mui/material/SpeedDialAction";
import SpeedDialIcon from "@mui/icons-material/SettingsRounded";
import UndoIcon from "@mui/icons-material/UndoSharp";
import Icon from "@mui/material/Icon";
import EditIcon from "@mui/icons-material/ModeEditOutlineTwoTone";
import DeleteIcon from "@mui/icons-material/DeleteForever";
import { CheckMarkIcon } from "components/Icons";
import RunIcon from "@mui/icons-material/RunCircleOutlined";
import { Modal } from "components/Modal";
import { Button } from "components/Inputs/Buttons/Button";
import InputYaml from "components/Inputs/Base/InputYaml";
import { TagDB } from "components/AutomationManager/TagDB";
import { DAGDims } from "components/DAGGraph/elements/types";
import { DAGAutomationGraph } from "components/DAGGraph";
import { InputList } from "components/Inputs/InputList";
import { InputTextView } from "components/Inputs/InputTextView";
import { ControlButton } from "react-flow-renderer";
import { AutomationData } from "types/automations";
import { MiniFailure } from "types/validators/helper";
import { AutoInfoBox } from "./AutoInfoBox";
import { useAutomatioEditorState, EditorData } from "./state";
interface Props {
automation?: AutomationData;
dims: DAGDims;
onUpdate: (auto: AutomationData) => void;
onTrigger: () => void;
onDelete: () => void;
tagDB: TagDB;
isNew?: boolean;
}
export const AutomationEditor: FC<Props> = ({
dims,
automation: propsAutos,
onUpdate: propsOnUpdate,
onDelete,
onTrigger,
tagDB,
isNew,
}) => {
// state
const {
@@ -42,6 +60,7 @@ export const AutomationEditor: FC<Props> = ({
validate,
save,
saveAndUpdate,
undo,
} = useAutomatioEditorState(propsAutos, propsOnUpdate);
const [infoBoxOpen, setInfoBox] = useState(false);
const [
@@ -188,10 +207,15 @@ export const AutomationEditor: FC<Props> = ({
Flip
</Button>
)}
{state.status === "changed" && (
<Button onClick={undo}>
<UndoIcon />
</Button>
)}
<Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save}
disabled={state.status !== "changed"}
disabled={state.status !== "changed" && !isNew}
>
Save <CheckMarkIcon color="#bf4" />
</Button>
@@ -204,12 +228,39 @@ export const AutomationEditor: FC<Props> = ({
onTriggerUpdate={updateTrigger}
onConditionUpdate={updateCondition}
isFlipped={flipped}
additionalControls={
<ControlButton onClick={() => setInfoBox(!infoBoxOpen)}>
<ModeEditOutlineTwoToneIcon />
</ControlButton>
}
/>
<SpeedDial
ariaLabel="options label"
sx={{ position: "absolute", bottom: 16, right: 16 }}
icon={<SpeedDialIcon />}
>
<SpeedDialAction
tooltipOpen
icon={<RunIcon />}
tooltipTitle={"Trigger"}
onClick={onTrigger}
/>
<SpeedDialAction
tooltipOpen
icon={<DeleteIcon />}
tooltipTitle={"Delete"}
onClick={onDelete}
/>
<SpeedDialAction
tooltipOpen
icon={<EditIcon />}
tooltipTitle={"Metadata"}
onClick={() => setInfoBox(!infoBoxOpen)}
/>
{state.status === "changed" && (
<SpeedDialAction
tooltipOpen
icon={<UndoIcon />}
tooltipTitle={"Undo"}
onClick={undo}
/>
)}
</SpeedDial>
</div>
</div>
);
+138 -99
View File
@@ -1,117 +1,156 @@
import { useState, useEffect } from 'react';
import { useState, useEffect } from "react";
import { AutomationData, AutomationMetadata } from "types/automations";
import * as v from "types/validators/autmation";
import { getFailures } from "types/validators/helper";
import { MiniFailure } from '../../types/validators/helper';
import { MiniFailure } from "../../types/validators/helper";
export type EditorData = ReturnType<typeof genEditorData>;
export type EditorState = {
status: 'unchanged' | 'changed' | 'saving',
data: EditorData
} | {
status: 'loading'
} | {
status: 'invalid',
failures: MiniFailure[],
data: EditorData,
}
export type EditorStatus = EditorState['status'];
export type EditorState =
| {
status: "unchanged";
data: EditorData;
}
| {
status: "changed" | "saving";
previous: EditorData[];
data: EditorData;
}
| {
status: "loading";
}
| {
status: "invalid";
failures: MiniFailure[];
data: EditorData;
};
export type EditorStatus = EditorState["status"];
export const useAutomatioEditorState = (
automation: AutomationData | undefined,
onSave: (a: AutomationData) => void,
automation: AutomationData | undefined,
onSave: (a: AutomationData) => void
) => {
const [state, update] = useState<EditorState>({
status: "loading",
});
const makeUpdate = <K extends keyof EditorData, D extends EditorData[K]>(name: K) => (
data: D
) => ((state.status === 'changed') || (state.status === 'unchanged')) && update({
status: 'changed',
const [state, update] = useState<EditorState>({
status: "loading",
});
const makeUpdate =
<K extends keyof EditorData, D extends EditorData[K]>(name: K) =>
(data: D) =>
(state.status === "changed" || state.status === "unchanged") &&
update({
status: "changed",
previous:
state.status === "unchanged"
? [state.data]
: state.previous.concat([state.data]),
data: {
...state.data,
[name]: data,
}
})
...state.data,
[name]: data,
},
});
const saveAndUpdate = (data: EditorData) => {
const cleanData = {
...data,
tags: data.tags.reduce((all, [tagName, tagValue]) => ({
...all,
[tagName.trim()]: tagValue.trim(),
}), {})
};
const saveAndUpdate = (data: EditorData) => {
if (state.status === "changed") {
const cleanData = {
...data,
tags: data.tags.reduce(
(all, [tagName, tagValue]) => ({
...all,
[tagName.trim()]: tagValue.trim(),
}),
{}
),
};
update({
status: "saving",
previous: state.previous,
data,
});
onSave(cleanData);
}
};
useEffect(() => {
if (automation) {
const failures = getFailures(automation, v.AutomationData);
if (failures) {
update({
status: "saving",
data,
})
onSave(cleanData);
status: "invalid",
failures,
data: genEditorData(automation),
});
} else {
update({
status: "unchanged",
data: genEditorData(automation),
});
}
}
}, [automation]);
useEffect(() => {
if (automation) {
const failures = getFailures(automation, v.AutomationData);
if (failures) {
update({
status: 'invalid',
failures,
data: genEditorData(automation),
})
} else {
update({
status: 'unchanged',
data: genEditorData(automation),
})
}
return {
validate: (data: any) => getFailures(data, v.AutomationData),
updateTrigger: makeUpdate("trigger"),
updateSequence: makeUpdate("sequence"),
updateCondition: makeUpdate("condition"),
saveAndUpdate,
updateMetadata: (
metadata: AutomationMetadata,
tags: Array<[string, string]>
) => {
if (state.status === "changed" || state.status === "unchanged") {
update({
status: "changed",
previous:
state.status === "changed"
? state.previous.concat([state.data])
: [state.data],
data: {
...state.data,
tags,
metadata,
},
});
}
},
save: () => {
if (state.status !== "loading") {
saveAndUpdate(state.data);
}
},
undo: () => {
if (state.status === "changed") {
if (state.previous.length === 1) {
update({
status: "unchanged",
data: state.previous[0],
});
} else {
update({
status: "changed",
data: state.previous[state.previous.length - 1],
previous: state.previous.slice(0, state.previous.length - 1),
});
}
}, [automation]);
return {
validate: (data: any) => getFailures(data, v.AutomationData),
updateTrigger: makeUpdate('trigger'),
updateSequence: makeUpdate('sequence'),
updateCondition: makeUpdate('condition'),
saveAndUpdate,
updateMetadata: (metadata: AutomationMetadata, tags: Array<[string, string]>) => {
if ((state.status === 'changed') || (state.status === 'unchanged')) {
update({
status: 'changed',
data: {
...state.data,
tags,
metadata,
}
})
}
},
save: () => {
if (state.status !== 'loading') {
saveAndUpdate(state.data)
}
},
get state() {
return state;
}
}
}
}
},
get state() {
return state;
},
};
};
const genEditorData = (automation: AutomationData) => {
const {
metadata,
trigger,
sequence,
condition,
} = automation;
const { metadata, trigger, sequence, condition } = automation;
const tags: [string, string][] = Object.keys(automation.tags).map(tagName => [tagName, automation.tags[tagName]]);
const tags: [string, string][] = Object.keys(automation.tags).map(
(tagName) => [tagName, automation.tags[tagName]]
);
return {
metadata,
trigger,
sequence,
condition,
tags,
}
}
return {
metadata,
trigger,
sequence,
condition,
tags,
};
};
@@ -1,187 +0,0 @@
import "styles/root.css";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { useState } from "react";
import { AutomationList } from ".";
import { bigMockAutoList } from "utils/mocks";
import { Page } from "components/Page";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { AutomationData } from "types/automations";
export default {
title: "App/AutomationList",
component: AutomationList,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
dims: DEFAULT_DIMS,
},
} as ComponentMeta<typeof AutomationList>;
const Template: ComponentStory<typeof AutomationList> = (args) => {
const [autos, setAutos] = useState(args.automations.data);
return (
<Page>
<AutomationList
{...args}
automations={{
...args.automations,
data: autos,
}}
onAdd={(a) => {
args.onAdd(a);
setAutos([...autos, a]);
}}
onRemove={(i) => {
args.onRemove(i);
setAutos([...autos.slice(0, i), ...autos.slice(i + 1)]);
}}
onUpdate={(i, a) => {
args.onUpdate(i, a);
setAutos([...autos.slice(0, i), a, ...autos.slice(i + 1)]);
}}
/>
</Page>
);
};
const make = (autos: AutomationData[]) => {
const NewTemp = Template.bind({});
NewTemp.args = {
...NewTemp.args,
automations: {
data: autos,
params: {
offset: 0,
limit: 100,
},
totalItems: autos.length,
},
};
return NewTemp;
};
export const EmptyStart = make([]);
export const FewAutos = make(bigMockAutoList);
export const BadAutmations = make([
{
metadata: {
alias: "Set Thermostat to 76 at 8am",
description: "",
mode: "single",
} as any,
trigger: [
{
at: "08:00:00",
platform: "time",
},
],
condition: [
{
condition: "state",
entity_id: "climate.thermostat",
state: "cool",
},
],
sequence: [
{
data: {
temperature: 76,
},
service: "climate.set_temperature",
target: {
entity_id: "climate.thermostat",
},
},
],
tags: {},
},
{
condition: [],
tags: {},
metadata: {
id: "Bad Choose Example",
alias: "Bad Choose",
description: "Example Metadata",
trigger_variables: {
wowo: "!",
},
mode: "single",
},
trigger: [],
sequence: [
{
choose: [],
},
] as any,
},
{
condition: [],
tags: {},
metadata: {
id: "random",
alias: "Bad Trigger",
description: "Example Metadata",
trigger_variables: {
wowo: "!",
},
mode: "single",
},
trigger: ["haha I am a string"] as any,
sequence: [],
},
{
condition: [],
tags: {},
metadata: {} as any,
trigger: [],
sequence: [],
},
]);
export const FewAutosWithSlowLoader: ComponentStory<typeof AutomationList> = (
args
) => {
const [autos, setAutos] = useState(args.automations.data);
return (
<Page>
<AutomationList
{...args}
automations={{
...args.automations,
data: autos,
}}
onAdd={(a) => {
window.setTimeout(() => {
args.onAdd(a);
setAutos([...autos, a]);
}, 10000);
}}
onRemove={(i) => {
window.setTimeout(() => {
args.onRemove(i);
setAutos([...autos.slice(0, i), ...autos.slice(i + 1)]);
}, 10000);
}}
onUpdate={(i, a) => {
window.setTimeout(() => {
args.onUpdate(i, a);
setAutos([...autos.slice(0, i), a, ...autos.slice(i + 1)]);
}, 10000);
}}
/>
</Page>
);
};
FewAutosWithSlowLoader.args = {
...FewAutosWithSlowLoader.args,
automations: {
data: bigMockAutoList,
params: {
limit: 100,
offset: 0,
},
totalItems: 100,
},
};
@@ -1,84 +0,0 @@
.automation-list-box {
display: flex;
flex-direction: column;
height: 100%;
}
.automation-list-box--body {
overflow-y: auto;
overflow-x: hidden;
height: 100%;
flex: 1;
user-select: none;
}
.automation-list-box--body>* {
padding-top: 0.5em;
padding-bottom: 0.5em;
}
.automation-list-box--body--group {
display: flex;
flex-direction: column;
padding-left: 1em;
border-radius: 10px;
padding-bottom: 0.5em;
border-width: 1px;
border-bottom-style: solid;
border-color: var(--mui-grey-400);
}
.automation-list-box--body--group.other {
border-color: var(--mui-success-main);
}
.automation-list-box--body--group.other>b {
color: var(--mui-success-light);
}
.automation-list-box--body--group>.automation-list-box--body--group {
border-left-style: solid;
border-top-left-radius: 0;
margin-left: 0.75em;
padding-left: 0.5em;
}
.automation-list-box--body--group>b {
width: 100%;
cursor: pointer;
padding: 0.1em;
}
.automation-list-box--body--group>b:hover,
.automation-list-box--body--group.selected>b {
background-color: var(--mui-grey-700);
color: var(--mui-secondary-contrastText);
}
.automation-list-box--bottom {
margin-top: 0.5em;
margin-bottom: 0.5em;
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
}
.automation-list-box--bottom>.automation-list-box--bottom--add {
background-color: var(--mui-primary-main);
color: var(--mui-primary-contrastText);
padding: 0.5em 2em;
}
.automation-list-box--bottom>.automation-list-box--bottom--add:hover {
color: var(--mui-primary-light);
}
.automation-list-box--bottom--load svg {
color: var(--mui-primary-main);
}
.automation-list-box--bottom--load.less svg {
transform: rotate(180deg);
}
@@ -1,79 +0,0 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { useState } from "react";
import { AutomationListBox } from "./AutomationListBox";
import { createMockAuto } from "utils/mocks";
import { Page } from "components/Page";
import { CookiesProvider } from "react-cookie";
import { makeTagDB } from "./TagDB";
import { AutomationData } from "types/automations";
export default {
title: "App/AutomationList/Box",
component: AutomationListBox,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof AutomationListBox>;
const Template: ComponentStory<typeof AutomationListBox> = (args) => {
const [selected, setSelected] = useState(args.selected);
return (
<Page>
<CookiesProvider>
<AutomationListBox
{...args}
tagsDB={makeTagDB(args.automations.data)}
automations={args.automations}
selected={selected}
onSelectAutomation={(i) => {
setSelected(i);
args.onSelectAutomation(i);
}}
/>
</CookiesProvider>
</Page>
);
};
const make = (autos: AutomationData[]) => {
const NewTemp = Template.bind({});
NewTemp.args = {
...NewTemp.args,
automations: {
data: autos,
params: {
offset: 0,
limit: 100,
},
totalItems: autos.length,
},
};
return NewTemp;
};
export const EmptyStart = make([]);
export const FewAutos = make([
createMockAuto({
Room: "Bathroom",
Type: "Lights",
NewDevice: "Yes",
Remote: "No",
Floor: "1",
}),
createMockAuto({ Room: "Bathroom", Type: "Climate" }),
createMockAuto({ Room: "Living Room", Type: "Climate" }),
createMockAuto({ Type: "Climate" }),
createMockAuto({ Type: "Lights", Routine: "Myself" }),
createMockAuto({ Routine: "DNS", Type: "SSL" }),
createMockAuto({ Room: "Bedroom", Type: "Lights", Routine: "Baby" }),
createMockAuto({ Room: "Office", Type: "Lights" }),
createMockAuto({ Room: "Office" }),
createMockAuto(),
]);
export const OneAuto = make([
createMockAuto({
Type: "Climate",
}),
]);
@@ -1,22 +0,0 @@
import { getTagList } from "./AutomationListBox";
import { createMockAuto } from "utils/mocks";
test("getTagList", () => {
expect(
getTagList([
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
])
).toStrictEqual([]);
expect(
getTagList([
createMockAuto({ Room: "Kitchen", Area: "Oven" }),
createMockAuto({ Room: "Attic" }),
createMockAuto({ Room: "Office" }),
createMockAuto({ Area: "Balcony" }),
])
).toStrictEqual(["Room", "Area"]);
});
@@ -1,195 +0,0 @@
import "./AutomationListBox.css";
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";
import { TagDB } from "components/AutomationList/TagDB";
// import { ButtonIcon } from "components/Icons/ButtonIcons";
// import ReadMoreOutlinedIcon from "@mui/icons-material/ReadMoreOutlined";
import { ListData, ListParams } from "apiService/types";
import Chip from "@mui/material/Chip";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
export type AutomationListBoxProps = {
automations: ListData<AutomationData>;
selected: number;
onSelectAutomation: (i: number) => void;
onRemove: (i: number) => void;
onAdd: () => void;
onUpdateTags: (id: string, tags: Record<string, string>) => void;
onUpdate: (a: AutomationData, i: number) => void;
onLoadMore: (p: ListParams) => void;
tagsDB: TagDB;
};
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<AutomationListBoxProps> = ({
automations: {
data: automations,
// params: autoParams,
totalItems: totalAutomations,
},
selected,
onSelectAutomation,
onAdd,
onRemove,
// onLoadMore,
onUpdateTags,
tagsDB,
onUpdate,
}) => {
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
);
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}
tagsDB={tagsDB}
onSave={onUpdate}
/>
</div>
<div className="automation-list-box--bottom">
<Button className="automation-list-box--bottom--add" onClick={onAdd}>
Add
</Button>
{automations.length < totalAutomations ? (
<>
<Chip
label={`Only loaded ${automations.length} out of ${totalAutomations}`}
variant="outlined"
color="warning"
icon={<InfoOutlinedIcon />}
onClick={() =>
window.open(
"https://github.com/asosnovsky/Shortumation/issues/78",
"_blank"
)
}
/>
<small>support for more is not yet implemented</small>
</>
) : (
""
)}
{/* {autoParams.offset > 0 && (
<ButtonIcon
borderless
className="automation-list-box--bottom--load less"
icon={<ReadMoreOutlinedIcon />}
onClick={() => onLoadMore()}
/>
)} */}
{/* {filteredAutomations.length} out of {totalAutomations} */}
{/* {autoParams.offset + automations.length < totalAutomations && (
<ButtonIcon
borderless
className="automation-list-box--bottom--load more"
icon={<ReadMoreOutlinedIcon />}
/>
)} */}
</div>
</div>
);
};
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;
}
return all;
}, {})
);
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)
)
) {
return false;
}
}
return true;
});
@@ -1,50 +0,0 @@
.automation-list-box--body--item:hover, .automation-list-box--body--item.selected {
outline-color: var(--mui-grey-400);
outline-style: solid;
outline-width: 1px;
background-color: var(--mui-secondary-contrastText);
}
.automation-list-box--body--item:hover>.automation-list-box--body--item--tags>span {
border-color: var(--mui-common-black);
}
.automation-list-box--body--item--tags--add:hover {
border-color: var(--mui-common-black);
color: var(--mui-grey-400);
background-color: var(--mui-secondary-contrastText);
}
.automation-list-box--body--item {
padding-left: 1em;
cursor: pointer;
display: flex;
gap: 1em;
}
.automation-list-box--body--item::before {
content: "⊚ ";
}
.automation-list-box--body--item--buttons {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
height: 100%;
gap: 0.25em;
margin: 0.5em
}
.automation-list-box--body--item--buttons>button {
padding: 0.25em;
margin: 0;
}
.automation-list-box--body--item--buttons .save {
color: var(--mui-success-light)
}
.automation-list-box--body--item--buttons .save:hover {
color: var(--mui-success-main)
}
@@ -1,257 +0,0 @@
import "./AutomationListBoxGroup.css";
import { TrashIcon } from "components/Icons";
import { MetadataBox } from "./AutomationMetadataBox";
import { AutomationData } from "types/automations";
import { AutomationGrouping } from "./automationGrouper";
import { FC, useEffect, useState } from "react";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { TagDB } from "./TagDB";
import Save from "@mui/icons-material/Save";
export type AutomationListBoxEvents = {
onSelectAutomation: (i: number) => void;
onRemove: (i: number) => void;
};
export type AutomationListBoxGroups = {
grouping: AutomationGrouping;
currentNode: number;
};
export type AutomationListBoxProps = {
events: AutomationListBoxEvents;
groups: AutomationListBoxGroups;
autos: Array<[AutomationData, number]>;
selectedAutomationIdx: number;
};
export type AutomationListBoxGroupProps = {
events: AutomationListBoxEvents;
grouping: AutomationGrouping;
autos: Array<[AutomationData, number]>;
selectedAutomationIdx: number;
tagsDB: TagDB;
onSave: (a: AutomationData, i: number) => void;
};
export const AutomationListBoxGroup: FC<AutomationListBoxGroupProps> = ({
events,
grouping,
autos,
selectedAutomationIdx,
tagsDB,
onSave,
}) => {
if (grouping.top.length === 1) {
return (
<>
{convertGroupsToItems(
autos,
{
grouping,
currentNode: grouping.top[0],
},
events,
selectedAutomationIdx,
tagsDB,
onSave
)}
</>
);
} else {
return (
<>
{grouping.top.map((groupIdx) => (
<AutomationListBoxGroupItem
key={groupIdx}
autos={autos}
groups={{
grouping,
currentNode: groupIdx,
}}
events={events}
selectedAutomationIdx={selectedAutomationIdx}
tagsDB={tagsDB}
onSave={onSave}
/>
))}
</>
);
}
};
export const convertGroupsToItems = (
autos: Array<[AutomationData, number]>,
{ grouping, currentNode }: AutomationListBoxGroups,
events: AutomationListBoxEvents,
selectedAutomationIdx: number,
tagsDB: TagDB,
onSave: (a: AutomationData, i: number) => void
) => {
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]}
tagsDB={tagsDB}
onSave={(a) => onSave(a, autoIndex)}
/>
));
}
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}
tagsDB={tagsDB}
onSave={onSave}
/>
));
}
return <></>;
};
export const AutomationListBoxGroupItem: FC<{
events: AutomationListBoxEvents;
groups: AutomationListBoxGroups;
autos: Array<[AutomationData, number]>;
selectedAutomationIdx: number;
tagsDB: TagDB;
onSave: (a: AutomationData, i: number) => void;
}> = ({ autos, groups, events, selectedAutomationIdx, tagsDB, onSave }) => {
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,
tagsDB,
onSave
)}
</div>
);
};
export const AutomationListBoxItem: FC<{
auto: [AutomationData, number];
isSelected: boolean;
events: AutomationListBoxEvents;
tagsDB: TagDB;
onSave: (a: AutomationData) => void;
}> = ({
events: { onRemove, onSelectAutomation },
auto: [auto, autoIndex],
isSelected,
tagsDB,
onSave,
}) => {
// state
const [{ tags, isModified, alias }, setState] = useState({
isModified: false,
tags: Object.entries(auto.tags),
alias: auto.metadata.alias ?? "",
});
// effects
useEffect(() => {
setState({
isModified: false,
tags: Object.entries(auto.tags),
alias: auto.metadata.alias ?? "",
});
}, [auto]);
// alias
const setAlias = (a: string) =>
setState({
isModified: true,
tags,
alias: a,
});
const setTags = (t: [string, string][]) =>
setState({
isModified: true,
tags: t,
alias,
});
// sub elements
let title = "BadAuto<<Missing Metadata>>";
if (auto.metadata) {
title = `Name = ${auto.metadata.alias}\nID = ${auto.metadata.id}\nDescription = ${auto.metadata.description}`;
}
// render
return (
<div
key={autoIndex}
className={[
"automation-list-box--body--item",
isSelected ? "selected" : "",
isModified ? "modded" : "",
].join(" ")}
title={title}
onClick={() => onSelectAutomation(autoIndex)}
>
<MetadataBox
metadata={{
...auto.metadata,
alias,
}}
tags={tags}
tagsDB={tagsDB}
onTagUpdate={setTags}
onAliasUpdate={setAlias}
/>
<div className="automation-list-box--body--item--buttons">
{isModified && (
<ButtonIcon
className="save"
icon={<Save />}
onClick={() =>
onSave({
...auto,
tags: Object.fromEntries(tags),
metadata: {
...auto.metadata,
alias,
},
})
}
/>
)}
<ButtonIcon onClick={() => onRemove(autoIndex)} icon={<TrashIcon />} />
</div>
</div>
);
};
@@ -1,101 +0,0 @@
.automation-list-box--body--item--title {
display: flex;
flex-direction: column;
padding-left: 0.25em;
flex: 1;
}
.automation-list-box--body--item--title>b {
font-size: 1em;
display: flex;
align-items: center;
gap: 0.25em;
}
.automation-list-box--body--item--title .input-text-view span {
max-height: 1.5em;
}
.automation-list-box--body--item--title>span, .automation-list-box--body--item--title>b>span {
font-size: 0.75em;
}
.automation-list-box--body--item--tags {
flex: 1;
display: flex;
flex-wrap: wrap;
font-size: 0.75em;
justify-content: left;
align-items: flex-start;
overflow: auto;
max-height: 100%;
gap: 0.25em;
}
.automation-list-box--body--item--tags>span {
border-color: var(--mui-grey-400);
border-style: solid;
border-width: 1px;
border-radius: 0.5em;
padding: 0.1em 0.5em;
}
.automation-list-box--body--item--tags--item {
color: white;
border-color: white;
border-style: solid;
border-width: 1px;
border-radius: 0.5em;
padding: 0.1em 0.5em;
display: flex;
flex-direction: row;
gap: 0.25em;
max-width: min-content;
align-items: center;
}
.automation-list-box--body--item--tags--item>.text:hover {
text-decoration: underline;
cursor: pointer;
}
.automation-list-box--body--item--tags--item>.text {
position: relative;
}
.automation-list-box--body--item--tags--item>.text .MuiFilledInput-root {
padding: 0;
min-width: 6em;
max-width: 10em;
background-color: var(--mui-common-black);
}
.automation-list-box--body--item--tags--item>.text .icon {
position: absolute;
right: 0.5em;
top: 0.5em;
cursor: pointer;
}
.automation-list-box--body--item--tags--item>.text .icon:hover {
background-color: var(--mui-grey-400);
border-radius: 20px;
}
.automation-list-box--body--item--tags--item>.text .icon:hover svg {
fill: var(--mui-common-black);
}
.automation-list-box--body--item--tags--item .delete {
font-size: 1em;
color: var(--mui-error-light);
}
.automation-list-box--body--item--tags--item .delete:hover {
color: var(--mui-error-dark);
outline: 1px solid var(--mui-error-dark);
border-radius: 20px;
}
@@ -1,181 +0,0 @@
import "./AutomationMetadataBox.css";
import { CheckMarkIcon } from "components/Icons";
import { FC, useState } from "react";
import { AutomationMetadata } from "types/automations";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { TagDB } from "./TagDB";
import DeleteIcon from "@mui/icons-material/ClearTwoTone";
import { InputTextView } from "components/Inputs/InputTextView";
export const MetadataBox: FC<{
metadata: AutomationMetadata;
onAliasUpdate: (t: string) => void;
onTagUpdate: (t: [string, string][]) => void;
tags: [string, string][];
tagsDB: TagDB;
}> = ({ tags, onTagUpdate, onAliasUpdate, tagsDB, metadata }) => {
// state
const [newTag, setNewTag] = useState<
| {
on: false;
}
| {
on: true;
name: string;
value: string;
}
>({ on: false });
// alias
const tagOptions = tagsDB.getTagNames(tags.map((t) => t[0]));
// render
let title = <span>{"BadAuto<<Missing Metadata>>"}</span>;
if (metadata) {
title = (
<>
<b className="text">
<InputTextView
value={metadata.alias ?? ""}
onChange={onAliasUpdate}
/>
<span>({String(metadata.id).slice(0, 10)})</span>
</b>
<span>{String(metadata.description ?? "").slice(0, 25)}</span>
</>
);
}
return (
<div className="automation-list-box--body--item--title">
{title}
<div className="automation-list-box--body--item--tags">
{tags.map(([tagName, tagValue], tagIndex) => (
<MetadataBoxTag
options={[tagOptions, tagsDB.getTagValues(tagName)]}
key={tagIndex}
value={[tagName, tagValue]}
onDelete={() =>
onTagUpdate([
...tags.slice(0, tagIndex),
...tags.slice(tagIndex + 1),
])
}
onChange={([newName, newValue]) =>
onTagUpdate([
...tags.slice(0, tagIndex),
[newName, newValue],
...tags.slice(tagIndex + 1),
])
}
/>
))}
{newTag.on ? (
<MetadataBoxTag
options={[tagOptions, tagsDB.getTagValues(newTag.name)]}
key="new"
value={[newTag.name, newTag.value]}
initialState={true}
onChange={([name, value]) => {
setNewTag({
on: true,
name,
value,
});
}}
onToggle={(em) => {
if (!em) {
if (newTag.name.trim() !== "" && newTag.value.trim() !== "") {
onTagUpdate(tags.concat([[newTag.name, newTag.value]]));
setNewTag({
on: false,
});
}
}
setNewTag({
on: false,
});
}}
/>
) : (
<span
className="automation-list-box--body--item--tags--add"
onClick={() =>
setNewTag({
on: true,
name: "",
value: "",
})
}
>
+
</span>
)}
</div>
</div>
);
};
export const MetadataBoxTag: FC<{
value: [string, string];
onChange: (t: [string, string]) => void;
options: [string[], string[]];
initialState?: boolean;
onToggle?: (em: boolean) => void;
onDelete?: () => void;
}> = (props) => {
const [editMode, setEditMode] = useState(
props.initialState ? props.initialState : false
);
const toggle = () => {
if (editMode) {
if (props.value[0].trim() === "" || props.value[1].trim() === "") {
props.onToggle && props.onToggle(true);
return setEditMode(true);
}
}
props.onToggle && props.onToggle(!editMode);
setEditMode(!editMode);
};
return (
<span className="automation-list-box--body--item--tags--item">
{props.onDelete && (
<DeleteIcon onClick={props.onDelete} className="delete" />
)}
{editMode ? (
<InputAutoComplete
multiple={false}
className="text"
disableChips
options={props.options[0]}
label=""
value={props.value[0]}
onEnter={toggle}
onChange={(v) => props.onChange([v ?? "", props.value[1]])}
onlyShowLabel
endAdornment={<CheckMarkIcon className="icon" onClick={toggle} />}
/>
) : (
<b className="text" onClick={toggle}>
{props.value[0]}:
</b>
)}
{editMode ? (
<InputAutoComplete
multiple={false}
className="text"
disableChips
options={props.options[1]}
label=""
value={props.value[1]}
onEnter={toggle}
onChange={(v) => props.onChange([props.value[0], v ?? ""])}
onlyShowLabel
endAdornment={<CheckMarkIcon className="icon" onClick={toggle} />}
/>
) : (
<span className="text" onClick={toggle}>
{props.value[1]}
</span>
)}
</span>
);
};
@@ -1,30 +0,0 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { MetadataBoxTag } from "./AutomationMetadataBox";
import { useState } from "react";
export default {
title: "App/AutomationList/Box",
component: MetadataBoxTag,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
value: ["Type", "Climate"],
options: [[], []],
},
} as ComponentMeta<typeof MetadataBoxTag>;
export const BoxTag: ComponentStory<typeof MetadataBoxTag> = (args) => {
const [state, setState] = useState(args.value);
return (
<Page>
<MetadataBoxTag
options={args.options}
value={state}
onChange={(v) => {
setState(v);
args.onChange(v);
}}
/>
</Page>
);
};
@@ -1,63 +0,0 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { ConnectedAutomationList } from ".";
import { createMockAuto } from "utils/mocks";
import { useMockApiService } from "apiService";
import { Page } from "components/Page";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
export default {
title: "App/AutomationList/MockConnected",
component: ConnectedAutomationList,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
dims: DEFAULT_DIMS,
initialAutomations: [],
},
} as ComponentMeta<typeof ConnectedAutomationList>;
const Template: ComponentStory<any> = (args) => {
const api = useMockApiService(args.initialAutomations);
return (
<Page>
<ConnectedAutomationList {...args} api={api} />
</Page>
);
};
export const EmptyStart = Template.bind({});
export const FewAutos = Template.bind({});
FewAutos.args = {
...FewAutos.args,
initialAutomations: [
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
],
};
export const Loading: ComponentStory<any> = (args) => {
const api = useMockApiService(args.initialAutomations);
return (
<Page>
<ConnectedAutomationList
{...args}
api={{
...api,
state: {
automations: {
ready: false,
},
},
}}
/>
</Page>
);
};
@@ -1,26 +0,0 @@
import { AutomationData } from "types/automations";
export type TagDB = ReturnType<typeof makeTagDB>;
export const makeTagDB = (automations: AutomationData[]) => {
const allTags: Record<string, Set<string>> = {};
automations.forEach(({ tags }) =>
Object.keys(tags).forEach((tagName) => {
const tagValue = tags[tagName];
if (!allTags[tagName]) {
allTags[tagName] = new Set();
}
allTags[tagName].add(tagValue);
})
);
const allTagNames = Object.keys(allTags);
return {
getTagNames(myTags: string[]): string[] {
return allTagNames.filter((n) => !myTags.includes(n)).sort();
},
getTagValues(tagName: string): string[] {
return allTags[tagName]
? Array.from(allTags[tagName].values()).sort()
: [];
},
};
};
@@ -1,72 +0,0 @@
import { makeGrouping } from "./automationGrouper";
import { AutomationData } from 'types/automations/index';
import { bigMockAutoList, createMockAuto } from 'utils/mocks';
const automations: AutomationData[] = [
createMockAuto({
"Room": 'Living Room',
"Type": 'Lights'
}),
createMockAuto({
"Room": 'Living Room',
"Type": 'Climate'
}),
createMockAuto({
"Room": 'Kitchen',
"Type": 'Climate'
}),
createMockAuto({
"Type": 'Climate'
}),
createMockAuto({
"Room": 'Living Room'
}),
createMockAuto({}),
];
test('no grouping', () => {
const grouped = makeGrouping(automations, [], 0);
expect(grouped.top).toStrictEqual([0])
expect(grouped.getAutomations(0)).toStrictEqual([0, 1, 2, 3, 4, 5])
});
test('1 grouping', () => {
const grouped = makeGrouping(automations, ["Room"], 0);
expect(grouped.top).toHaveLength(3);
expect(grouped.getAutomations(0)).toStrictEqual([0, 1, 4])
expect(grouped.getAutomations(1)).toStrictEqual([2])
expect(grouped.getAutomations(2)).toStrictEqual([3, 5])
});
test('2 groupings', () => {
const grouped = makeGrouping(automations, ["Room", "Type"], 0);
expect(grouped.top).toHaveLength(3);
expect(grouped.getAutomations(grouped.top[0])).toHaveLength(0)
expect(grouped.getSubGroups(grouped.top[0])).toHaveLength(3)
expect(grouped.getAutomations(grouped.top[1])).toHaveLength(0)
expect(grouped.getSubGroups(grouped.top[1])).toHaveLength(1)
expect(grouped.getAutomations(grouped.top[2])).toHaveLength(2)
expect(grouped.getSubGroups(grouped.top[2])).toHaveLength(0)
});
test('bigAutoList groupings has not duplicate ids', () => {
const grouped = makeGrouping(bigMockAutoList, ['Room', "Remote"], 0);
const flattenAndCount = (gid: number): Record<number, number[]> => {
const subgroups = grouped.getSubGroups(gid);
if (subgroups.length > 0) {
return flattenAndConsolidate(subgroups)
} else {
return grouped.getAutomations(gid).reduce((sum: Record<number, number[]>, b) => {
sum[b] = (sum[b] ?? []).concat(gid)
return sum
}, {})
}
}
const flattenAndConsolidate = (gids: number[]): Record<number, number[]> => gids.map(flattenAndCount).reduce((a, b) => {
for (const k of Object.keys(b).map(Number)) {
a[k] = (a[k] ?? []).concat(b[k])
}
return a
}, {})
const countedAutos = flattenAndConsolidate(grouped.top)
for (const key of Object.keys(countedAutos).map(Number)) {
expect(countedAutos[key]).toHaveLength(1)
}
})
@@ -1,130 +0,0 @@
import { AutomationData } from "types/automations";
const makeGrouper = () => {
const groupIdNames: string[] = []
const groupSubGroups: Array<Set<number>> = []
const groupAutomations: number[][] = []
const groupData: Array<{
name: string;
selected: boolean;
isOther: boolean;
isTop: boolean;
}> = [];
const topGroups: number[] = [];
return {
groupIdNames,
groupSubGroups,
groupAutomations,
groupData,
topGroups,
addNew(groupId: string, groupName: string, theChosenOne: boolean, isTopLevel: boolean, isOther: boolean = false): number {
groupIdNames.push(groupId);
groupSubGroups.push(new Set());
groupAutomations.push([]);
groupData.push({
name: groupName,
selected: theChosenOne,
isTop: isTopLevel,
isOther
})
const groupIdx = groupIdNames.length - 1;
if (isTopLevel) {
topGroups.push(groupIdx);
}
return groupIdx;
},
updateGroup(
groupIdx: number,
update: {
isChosen: boolean,
lastGroupIdx: number | null,
autoIdx: number | null,
}
) {
if (update.isChosen) {
groupData[groupIdx].selected = true;
}
if (update.lastGroupIdx !== null) {
groupSubGroups[update.lastGroupIdx].add(groupIdx);
}
if (update.autoIdx !== null) {
groupAutomations[groupIdx].push(update.autoIdx)
}
}
}
}
export type AutomationGrouping = ReturnType<typeof makeGrouping>;
export const makeGrouping = (
autos: AutomationData[],
selectedTags: string[],
selectedAutomationIdx: number,
) => {
const grouper = makeGrouper();
if (selectedTags.length === 0) {
grouper.addNew("$", "", selectedAutomationIdx >= 0, true, true)
grouper.groupAutomations = [autos.map((_, i) => i)];
} else {
autos.forEach((auto, autoIdx) => {
const theChosenOne = selectedAutomationIdx === autoIdx;
let lastGroupIdx: number | null = null;
let lastGroupId: string = "$";
for (let ti = 0; ti < selectedTags.length; ti++) {
const isTopLevel = ti === 0;
const selTag = selectedTags[ti];
if (selTag in auto.tags) {
const groupName = auto.tags[selTag];
const groupId = `${lastGroupId}>${selTag}:${groupName}`;
let groupIdx = grouper.groupIdNames.indexOf(groupId);
if (groupIdx < 0) {
groupIdx = grouper.addNew(groupId, groupName, theChosenOne, isTopLevel);
}
grouper.updateGroup(groupIdx, {
isChosen: theChosenOne,
lastGroupIdx,
autoIdx: ti === selectedTags.length - 1 ? autoIdx : null,
})
lastGroupIdx = groupIdx;
lastGroupId = groupId;
} else {
const groupId = `${lastGroupId}>${selTag}:$`;
let groupIdx = grouper.groupIdNames.indexOf(groupId);
if (groupIdx < 0) {
groupIdx = grouper.addNew(groupId, "", theChosenOne, isTopLevel, true);
}
grouper.updateGroup(groupIdx, {
isChosen: theChosenOne,
lastGroupIdx,
autoIdx,
})
break
}
}
});
}
const sortGroupIds = (groupIds: number[]) => groupIds.sort((a, b) => {
const adata = grouper.groupData[a];
const bdata = grouper.groupData[b];
if (adata.isOther) {
return 1
} else {
return adata.name > bdata.name ? -1 : 1
}
})
return {
top: sortGroupIds(grouper.topGroups),
getSubGroups(groupIdx: number) {
return sortGroupIds(Array.from(grouper.groupSubGroups[groupIdx].values()))
},
getAutomations(groupIdx: number) {
return grouper.groupAutomations[groupIdx]
},
getData(groupIdx: number) {
return grouper.groupData[groupIdx]
}
}
}
@@ -1,68 +0,0 @@
/* root elements */
.automation-list--root {
width: 100%;
height: 100%;
display: flex;
flex-direction: row;
overflow: hidden;
}
.automation-list--list {
flex: 1;
max-width: 400px;
position: relative;
}
.automation-list--viewer {
overflow: hidden;
flex: 1;
}
/* Loading state */
.automation-list--root.loading {
width: 100%;
height: 100%;
flex-direction: column;
}
.automation-list--root.loading>* {
width: 100%;
}
.automation-list--root.loading .automation-list--circle-loader {
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
display: flex;
}
/* list children: on hide */
.automation-list--list.hide>.automation-list-box {
width: 0;
opacity: 0;
}
.automation-list--list.hide {
min-width: 35px;
max-width: 35px;
}
.automation-list--list.hide>.automation-list--list-hide {
transform: rotate(180deg);
left: 0;
}
/* list children: normal */
.automation-list--list {
border-right: solid;
border-width: 1px;
}
.automation-list--list .automation-list--list-hide {
position: absolute;
bottom: 0em;
left: 0.5em;
max-width: 1.5em;
max-height: 1.5em;
}
@@ -1,38 +0,0 @@
/* none-hidden */
.automation-list--root.mobile {
flex-direction: column;
}
.automation-list--root.mobile>.automation-list--list {
max-width: 100vw;
min-height: 100vh;
}
.automation-list--root.mobile .automation-editor {
flex-direction: column;
}
.automation-list--root.mobile .automation-list--list-hide {
transform: rotate(90deg);
left: 0.25em;
}
/* list hide */
.automation-list--root.mobile .automation-list--list.hide {
width: 100vw;
min-height: 0;
max-height: 0;
}
.automation-list--root.mobile .automation-list--list.hide .automation-list--list-hide {
transform: rotate(270deg);
position: fixed;
top: 0.5em;
z-index: 5;
}
.automation-list--root.mobile .automation-editor--flow-wrapper>.automation-editor--flow-wrapper--toolbar .input-text-view,
.automation-list--root.mobile .automation-editor--flow-wrapper>.automation-editor--flow-wrapper--toolbar .id {
display: none;
}
@@ -1,213 +0,0 @@
import "./index.css";
import "./index.mobile.css";
import { AutomationEditor } from "components/AutomationEditor";
import { FC, ReactNode, useState, useRef, useEffect } from "react";
import { AutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { ApiService } from "apiService/core";
import { AutomationListBox } from "./AutomationListBox";
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";
import { useSnackbar } from "notistack";
import { DAGDims } from "components/DAGGraph/elements/types";
import { ListData, ListParams } from "apiService/types";
interface AutomationListParams {
automations: ListData<AutomationData>;
onUpdate: (i: number, auto: AutomationData) => void;
onUpdateTags: (id: string, tags: Record<string, string>) => void;
onAdd: (auto: AutomationData) => void;
onRemove: (i: number) => void;
onLoadMore: (p: ListParams) => void;
dims: DAGDims;
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,
onLoadMore,
onUpdate,
onUpdateTags,
onAdd,
onRemove,
dims,
children,
}) => {
// state
const snackbr = useSnackbar();
const { hideList, setHideList, current, setCurrent } =
useAutomationListState();
const { isMobile } = useWindowSize();
const firstRender = useRef(true);
// alias
const currentAuto =
automations.data.length > 0
? automations.data[current - automations.params.offset]
: null;
const tagDB = makeTagDB(automations.data);
// effect
useEffect(() => {
if (firstRender.current) {
snackbr.enqueueSnackbar("Saved.", { variant: "info" });
}
firstRender.current = true;
// eslint-disable-next-line
}, [automations]);
// render
return (
<div
className={["automation-list--root", isMobile ? "mobile" : ""].join(" ")}
>
<div
className={["automation-list--list", hideList ? "hide" : "show"].join(
" "
)}
>
<AutomationListBox
automations={automations}
onUpdate={(a, i) => onUpdate(i, a)}
onUpdateTags={onUpdateTags}
onAdd={() => {
onAdd(defaultAutomation(String(Date.now())));
setCurrent(automations.data.length);
if (isMobile) {
setHideList(true);
}
}}
onSelectAutomation={(i) => {
setCurrent(i);
if (isMobile) {
setHideList(true);
}
}}
onLoadMore={onLoadMore}
selected={current}
onRemove={onRemove}
tagsDB={tagDB}
/>
<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>
);
};
interface ConnectedAutomationListParams {
dims: DAGDims;
api: ApiService;
}
export const ConnectedAutomationList: FC<ConnectedAutomationListParams> = ({
api: {
state: { automations },
...methods
},
dims,
}) => {
const { reloadAutomations } = useHA();
const [saving, setSaving] = useState(false);
const updateTags = async (id: string, tags: Record<string, string>) => {
const resp = await methods.updateTags({
automation_id: id,
tags,
});
setSaving(true);
await reloadAutomations();
setSaving(false);
return resp;
};
const removeAutomation = async (args: any) => {
const resp = await methods.removeAutomation(args);
setSaving(true);
await reloadAutomations();
setSaving(false);
return resp;
};
const updateAutomation = async (args: any) => {
const resp = await methods.updateAutomation(args);
setSaving(true);
await reloadAutomations();
setSaving(false);
return resp;
};
if (!automations.ready) {
return (
<div className="automation-list--root loading">
<LinearProgress />
<div className="automation-list--circle-loader">
<CircularProgress />
</div>
</div>
);
}
if (!automations.ok) {
return <span>Error {automations.error}</span>;
}
return (
<>
{saving && <LinearProgress />}
<AutomationList
dims={dims}
automations={automations.data}
onUpdateTags={updateTags}
onLoadMore={() => {}}
onAdd={(auto) =>
updateAutomation({ auto, index: automations.data.totalItems + 1 })
}
onRemove={(index) => removeAutomation({ index })}
onUpdate={(index, auto) => updateAutomation({ index, auto })}
/>
</>
);
};
@@ -0,0 +1,39 @@
.automation-manager--list-box-group--title {
margin: 0.5em;
}
.automation-manager--list-box-group--title .icon {
font-size: 1.2em;
}
.automation-manager--list-box-group--title:hover,
.automation-manager--list-box-group.selected .automation-manager--list-box-group--title {
color: var(--mui-primary-main);
cursor: pointer;
user-select: none;
}
.automation-manager--list-box-group.modified {
border: 1px var(--mui-success-main) solid;
}
.automation-manager--list-box-group {
border-color: var(--mui-text-secondary);
border-width: 0.125px;
border-bottom-style: solid;
border-radius: 10px;
border-bottom-right-radius: 0;
}
.automation-manager--list-box-group--list.close {
height: 0;
opacity: 0;
display: none;
}
.automation-manager--list-box-group .automation-manager--list-box-group {
margin-left: 0.5em;
margin-bottom: 0.5em;
border-left: 1px solid var(--mui-text-secondary);
border-top-left-radius: 0;
}
@@ -0,0 +1,157 @@
import { ListBoxGroup } from ".";
import { makeStory } from "devUtils";
import { useTagDB } from "../TagDB";
const { make, componentMeta } = makeStory({
Component: ListBoxGroup,
BaseTemplate: (args) => {
const tagsDB = useTagDB([], () => {});
return <ListBoxGroup {...args} tagsDB={tagsDB} />;
},
meta: {
title: "App/AutomationManager/ListBoxGroup",
args: {
title: "Example",
type: "items",
flags: {
isSelected: false,
isModified: false,
},
data: [
{
id: "1",
title: "Example",
entityId: "automation.1",
description: "Amazing automation!",
tags: {},
state: "on",
flags: {
isSelected: false,
isModified: false,
},
},
{
id: "2",
title: "Example 2",
entityId: "automation.2",
description: "Cool!",
state: "on",
flags: {
isSelected: false,
isModified: false,
},
tags: {
room: "main bedroom",
routine: "night time",
},
},
],
},
},
});
export default componentMeta;
export const Basic = make({});
export const Nested = make({
title: "Top Group",
type: "group",
flags: {
isSelected: false,
isModified: false,
},
data: [
{
title: "Subgroup 1",
type: "group",
flags: {
isSelected: true,
isModified: false,
},
data: [
{
type: "items",
flags: {
isSelected: true,
isModified: false,
},
title: "Subsub group",
data: [
{
id: "1",
entityId: "automation.1",
description: "",
title: "Automation #1",
state: "on",
flags: {
isSelected: true,
isModified: false,
},
tags: {},
},
{
id: "2",
entityId: "automation.2",
description: "another one",
title: "Automation #2",
state: "off",
flags: {
isSelected: false,
isModified: false,
},
tags: {},
},
{
id: "3",
entityId: "automation.3",
description: "bad one",
title: "Automation #3",
state: "offing",
flags: {
isSelected: false,
isModified: false,
},
tags: {
type: "bad",
},
},
],
},
],
},
{
title: "Subgroup 2",
type: "group",
flags: {
isSelected: false,
isModified: false,
},
data: [],
},
{
title: "Other",
type: "items",
flags: {
isSelected: false,
isModified: false,
},
data: [
{
id: "4",
entityId: "automation.4",
description: "Cool thing",
title: "Automation #4",
flags: {
isSelected: false,
isModified: false,
},
state: "on",
tags: {
type: "good",
},
},
],
},
],
});
@@ -0,0 +1,121 @@
import "./index.css";
import { FC, useState } from "react";
import { MetadataBox } from "../MetadataBox";
import {
AutomationManagerAutoUpdatable,
AutomationManagerItem,
} from "../types";
import { TagDB } from "../TagDB";
export type ListBoxGroupProps = AutomationManagerItem & {
onAutomationUpdate: (
a: AutomationManagerAutoUpdatable,
aid: string,
eid: string
) => void;
onAutomationDelete: (aid: string, eid: string) => void;
onSelect: (aid: string) => void;
onRun: (eid: string) => void;
initialOpenState?: boolean;
tagsDB: TagDB;
};
export const ListBoxGroup: FC<ListBoxGroupProps> = ({
title,
type,
data,
flags,
initialOpenState,
tagsDB,
...events
}) => {
const [open, setOpen] = useState(initialOpenState ?? false);
const openIcon = !open ? "⊕" : "⊖";
const totalAutomations = countAutomations({
title,
type,
data,
} as any);
return (
<div
className={[
"automation-manager--list-box-group",
flags.isSelected ? "selected" : "",
flags.isModified ? "modified" : "",
].join(" ")}
>
<div
onClick={() => setOpen(!open)}
className="automation-manager--list-box-group--title"
>
<b>{title}</b> <span className="icon">{openIcon}</span> (
{totalAutomations} automation
{totalAutomations === 1 ? "" : "s"})
</div>
<div
className={[
"automation-manager--list-box-group--list",
open ? "open" : "close",
].join(" ")}
>
{type === "items"
? data.map((auto, i) => (
<MetadataBox
key={`${i}-${auto.id}`}
{...auto}
tagsDB={tagsDB}
onDelete={() =>
events.onAutomationDelete(auto.id, auto.entityId)
}
isSelected={auto.flags.isSelected}
onSelect={() => events.onSelect(auto.id)}
onRun={() => events.onRun(auto.entityId)}
onDescriptionUpdate={(description) =>
events.onAutomationUpdate(
{
...auto,
description,
},
auto.id,
auto.entityId
)
}
onTitleUpdate={(title) =>
events.onAutomationUpdate(
{
...auto,
title,
},
auto.id,
auto.entityId
)
}
onStateUpdate={(state) =>
events.onAutomationUpdate(
{
...auto,
state,
},
auto.id,
auto.entityId
)
}
/>
))
: data.map((group, i) => (
<ListBoxGroup {...events} {...group} tagsDB={tagsDB} key={i} />
))}
</div>
</div>
);
};
const countAutomations = (item: AutomationManagerItem): number => {
if (item.type === "items") {
return item.data.length;
} else {
return item.data.reduce((total = 0, n) => total + countAutomations(n), 0);
}
};
@@ -0,0 +1,132 @@
import { HassEntities } from "home-assistant-js-websocket";
import { useEffect, useState } from "react";
import { AutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults";
import { TagDB } from "../TagDB";
import { AutomationManagerAuto } from "../types";
export const useAutomationDB = (
haEntities: HassEntities,
configAutomations: AutomationData[],
tagsDB: TagDB
) => {
const autoMap = genMapping(haEntities, configAutomations, tagsDB);
const [newAuto, setNewAuto] =
useState<null | [AutomationManagerAuto, AutomationData]>(null);
useEffect(() => {
if (newAuto && autoMap[newAuto[0].id]) {
setNewAuto(null);
}
}, [autoMap, newAuto]);
return {
get managerAutoList() {
const out = Object.values(autoMap).map(([m, _]) => m);
if (newAuto) {
return out.concat([newAuto[0]]);
} else {
return out;
}
},
getAutomationData(
autoId: string
): null | [AutomationManagerAuto, AutomationData | null] {
if (newAuto && newAuto[0].id === autoId) {
return newAuto;
}
return autoMap[autoId] ?? null;
},
isAutoNew(autoId: string) {
return (newAuto && newAuto[0].id === autoId) ?? false;
},
removeNew() {
setNewAuto(null);
},
addNew() {
const auto = defaultAutomation(String(Date.now()));
setNewAuto([
{
id: auto.metadata.id,
entityId: "",
title: auto.metadata.alias ?? "",
description: auto.metadata.description ?? "",
state: "unregistered",
tags: {},
issue: "New Automation",
isNew: true,
},
auto,
]);
return auto;
},
};
};
const genMapping = (
haEntities: HassEntities,
configAutomations: AutomationData[],
tagsDB: TagDB
) => {
const configData: Record<string, AutomationData> = configAutomations.reduce(
(all, n) => ({
...all,
[n.metadata.id]: n,
}),
{}
);
const automatioinMap: Record<
string,
[AutomationManagerAuto, AutomationData | null]
> = {};
Object.entries(haEntities)
.filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation."))
.forEach(([entityId, entityData]) => {
const autoId = entityData.attributes.id;
let title = entityData.attributes.friendly_name ?? "";
let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state)
? undefined
: `recived invalid state "${entityData.state}, this could be because you have a lingering automation that was not cleared by homeassistant, try to reboot HA or manually clear this automation from HA Database."`;
let found: AutomationData | null = null;
if (configData[autoId]) {
found = configData[entityData.attributes.id];
title = found.metadata.alias ?? title;
description = found.metadata.description ?? description;
delete configData[autoId];
} else {
issue = "failed to find this automation in '/config' folder";
}
automatioinMap[autoId] = [
{
id: autoId,
entityId,
title,
description,
state: entityData.state,
tags: tagsDB.getTags(autoId),
issue,
},
found,
];
});
Object.values(configData).forEach((auto) => {
automatioinMap[auto.metadata.id] = [
{
id: auto.metadata.id,
entityId: "",
title: auto.metadata.alias ?? "",
description: auto.metadata.description ?? "",
state: "unregistered",
tags: tagsDB.getTags(auto.metadata.id),
issue:
"homeassistant did not load this automation, try to manually reload automations or restart homeassistant.",
},
auto,
];
});
return automatioinMap;
};
@@ -0,0 +1,4 @@
.automation-manager--editor {
height: 100%;
width: 100%;
}
@@ -0,0 +1,90 @@
import "./index.css";
import { AutomationEditor } from "components/AutomationEditor";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { FC, PropsWithChildren } from "react";
import { AutomationManagerSidebar } from "../Sidebar";
import {
useAutomationManagerState,
UseAutomationManagerStateArgs,
} from "./state";
import Alert from "@mui/material/Alert";
import { useConfirm } from "material-ui-confirm";
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
onAutomationDelete: (aid: string, eid: string) => void;
};
export const AutomationManagerLoaded: FC<
PropsWithChildren<AutomationManagerLoadedProps>
> = ({ children, ...args }) => {
const state = useAutomationManagerState(args);
const confirm = useConfirm();
const onAutomationDelete = async (aid: string, eid: string) =>
confirm({
title: "Are you sure you want to delete this automation?",
confirmationText: "Delete",
})
.then(() => {
args.onAutomationDelete(aid, eid);
state.setSelectedAutomationId(null);
})
.catch(() => {});
return (
<div className="automation-manager">
{children}
<AutomationManagerSidebar
automations={state.automations}
tagsDB={state.tagsDB}
selectedAutomationId={state.currentAutomationId}
onSelectedAutomationId={state.setSelectedAutomationId}
onAutomationAdd={() => state.addNew()}
onAutomationDelete={onAutomationDelete}
onAutomationUpdate={state.sideBarUpdateAutomation}
onRun={args.onAutomationRun}
/>
<div className={["automation-manager--editor"].join(" ")}>
{state.currentAutomationId !== null ? (
state.currentAutomation ? (
<AutomationEditor
dims={{
...DEFAULT_DIMS,
flipped: true,
}}
automation={state.currentAutomation}
onUpdate={state.editorUpdateAutomation}
onDelete={() => {
if (
state.currentAutomationId &&
state.currentAutomationEntityId
) {
onAutomationDelete(
state.currentAutomationId,
state.currentAutomationEntityId
);
}
}}
onTrigger={() => {
if (state.currentAutomationEntityId) {
args.onAutomationRun(state.currentAutomationEntityId);
}
}}
tagDB={state.tagsDB}
isNew={state.currentAutomationIsNew}
/>
) : (
<div>
<Alert color="warning">
Failed to find an automation on disk with id{" "}
{state.currentAutomationId}.
</Alert>
</div>
)
) : (
<></>
)}
</div>
</div>
);
};
@@ -0,0 +1,164 @@
import { HassEntities } from "home-assistant-js-websocket";
import { useState } from "react";
import { useCookies } from "react-cookie";
import { AutomationData } from "types/automations";
import { useTagDB } from "../TagDB";
import { useAutomationDB } from "./automationDB";
import { useConfirm } from "material-ui-confirm";
import { AutomationManagerAutoUpdatable } from "../types";
import { useSnackbar } from "notistack";
export type UseAutomationManagerStateArgs = {
configAutomations: AutomationData[];
hassEntities: HassEntities;
onUpdateTags: (aid: string, tags: Record<string, string>) => void;
onAutomationAdd: (auto: AutomationData) => void;
onAutomationUpdate: (aid: string, auto: AutomationData) => void;
onAutomationStateChange: (eid: string, on: boolean) => void;
onAutomationRun: (eid: string) => void;
};
export const useAutomationManagerState = ({
configAutomations,
hassEntities,
onUpdateTags,
onAutomationAdd,
onAutomationUpdate,
onAutomationStateChange,
}: UseAutomationManagerStateArgs) => {
// state
const confirm = useConfirm();
const snackbr = useSnackbar();
const cookies = useAMSCookies();
const tagsDB = useTagDB(
configAutomations.map(({ metadata: { id }, tags }) => ({
id,
tags,
})),
onUpdateTags
);
const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB);
// alias
const stillHaveNewAreYouSure = async () => {
try {
await confirm({
content:
"Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.",
confirmationText: "Switch Automation",
cancellationText: "Cancel",
});
return true;
} catch (_) {
return false;
}
};
const currentAutomation = automationDB.getAutomationData(
cookies.currentAutomationId ?? ""
);
const methods = {
get currentAutomationId() {
return cookies.currentAutomationId;
},
get automations() {
return automationDB.managerAutoList;
},
get tagsDB() {
return tagsDB;
},
get currentAutomation(): AutomationData | null {
return currentAutomation === null ? null : currentAutomation[1];
},
get currentAutomationIsNew() {
return automationDB.isAutoNew(cookies.currentAutomationId ?? "");
},
get currentAutomationEntityId(): string | null {
return currentAutomation === null ? null : currentAutomation[0].entityId;
},
async setSelectedAutomationId(i: string | null, force: boolean = false) {
if (methods.currentAutomationIsNew && !force) {
if (!(await stillHaveNewAreYouSure())) {
return;
}
automationDB.removeNew();
}
cookies.setSelectedAutomation(i);
},
async addNew() {
if (methods.currentAutomationIsNew) {
if (!(await stillHaveNewAreYouSure())) {
return;
}
}
const auto = automationDB.addNew();
methods.setSelectedAutomationId(auto.metadata.id, true);
},
editorUpdateAutomation(auto: AutomationData) {
if (methods.currentAutomationIsNew) {
onAutomationAdd(auto);
} else if (methods.currentAutomationId) {
onAutomationUpdate(methods.currentAutomationId, auto);
}
},
sideBarUpdateAutomation(
a: AutomationManagerAutoUpdatable,
aid: string,
eid: string
) {
const previousAuto = automationDB.getAutomationData(aid);
if (previousAuto && previousAuto[1]) {
const previousAutoState = previousAuto[1];
if (
previousAutoState.metadata.alias !== a.title ||
previousAutoState.metadata.description !== a.description
) {
onAutomationUpdate(aid, {
...previousAutoState,
metadata: {
...previousAutoState.metadata,
alias: a.title,
description: a.description,
},
});
}
} else {
snackbr.enqueueSnackbar(
`Failed to save automation "${aid}" contents - ${JSON.stringify(
a
)} -- not found in /config`,
{ variant: "error" }
);
}
const previousState =
previousAuto === null ? null : previousAuto[0].state;
if (previousState !== a.state) {
onAutomationStateChange(eid, a.state === "on");
}
},
};
return methods;
};
const useAMSCookies = () => {
const [
cookies,
setCookies,
// eslint-disable-next-line
_,
] = useCookies(["selectedAutomation"]);
let initialCurrent = null;
try {
initialCurrent = cookies.selectedAutomation ?? null;
} catch (_) {}
const [selectedAutomation, setSelectedAutomation] =
useState<string | null>(initialCurrent);
return {
currentAutomationId: selectedAutomation,
setSelectedAutomation(i: string | null) {
setSelectedAutomation(i);
setCookies("selectedAutomation", i === null ? undefined : i);
},
};
};
@@ -0,0 +1,123 @@
.automation-manager--metadatabox .metadatabox--tags {
display: flex;
flex-direction: row;
flex-wrap: wrap;
gap: 0.25em;
margin-top: 0.25em;
padding: 0.25em;
}
.automation-manager--metadatabox .metadatabox--tags.modified {
border: 1px solid var(--mui-success-light);
border-radius: 10px;
}
.automation-manager--metadatabox .metadatabox--tags .tag,
.automation-manager--metadatabox .metadatabox--tags .buttons .tag-add {
display: flex;
max-width: fit-content;
align-items: center;
gap: 0.25em;
border-color: var(--mui-grey-400);
border-style: solid;
border-width: 1px;
border-radius: 0.5em;
padding: 0.1em 0.5em;
}
.automation-manager--metadatabox .metadatabox--tags .buttons {
display: flex;
justify-content: center;
align-items: center;
gap: 0.25em;
}
.automation-manager--metadatabox .metadatabox--tags .buttons .tag-add {
cursor: pointer;
color: var(--mui-primary-light);
border-color: var(--mui-primary-main);
}
.automation-manager--metadatabox .metadatabox--tags .buttons .tag-save {
cursor: pointer;
border-radius: 0.25em;
color: var(--mui-success-main);
height: 1em;
padding: 0.1em;
}
.automation-manager--metadatabox .metadatabox--tags .buttons .tag-add:hover {
background-color: var(--mui-primary-light);
color: var(--mui-primary-contrastText);
}
.automation-manager--metadatabox .metadatabox--tags .buttons .tag-save:hover {
background-color: var(--mui-success-light);
color: var(--mui-success-contrastText);
}
.automation-manager--metadatabox .metadatabox--tags .tag .delete-tag {
font-size: 1em;
}
.automation-manager--metadatabox .metadatabox--tags .tag .delete-tag:hover {
cursor: pointer;
color: var(--mui-error-light);
outline: 1px solid var(--mui-error-dark);
border-radius: 20px;
}
.automation-manager--metadatabox .metadatabox--tags .tag .inner {
font-size: 1em;
display: flex;
justify-content: center;
align-items: center;
gap: 0.25em;
cursor: text;
user-select: none;
text-overflow: ellipsis;
overflow: hidden;
word-wrap: break-word;
}
.automation-manager--metadatabox .metadatabox--tags .tag .inner span,
.automation-manager--metadatabox .metadatabox--tags .tag .inner b {
font-size: 0.9em;
overflow: hidden;
text-overflow: ellipsis;
word-wrap: break-word;
}
.automation-manager--metadatabox .metadatabox--tags .tag .edit-icon {
height: 0.7em;
width: 0.7em;
padding: 0.15em;
cursor: text;
}
.automation-manager--metadatabox .metadatabox--tags .tag:hover .edit-icon {
transform: rotate(10deg);
}
.metadatabox--tags--modal {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 0.25em;
}
.metadatabox--tags--modal .input-autotext {
min-width: calc(max(10em, 100%));
}
.metadatabox--tags--modal .buttons {
display: flex;
gap: 0.5em;
justify-content: space-evenly;
}
@@ -0,0 +1,158 @@
import "./Tags.css";
import { FC, ReactNode, useState } from "react";
import DeleteIcon from "@mui/icons-material/ClearTwoTone";
import EditIcon from "@mui/icons-material/EditOutlined";
import SaveIcon from "@mui/icons-material/SaveOutlined";
import { cleanUpUndefined } from "utils/helpers";
import { Modal } from "components/Modal";
import { Button } from "components/Inputs/Buttons/Button";
import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "../TagDB";
export type TagsProps = {
automationId: string;
tagsDB: TagDB;
};
export type TagModalState =
| {
open: false;
}
| {
open: true;
tag: [string, string];
isNew: boolean;
};
export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
const [modalState, setModal] = useState<TagModalState>({ open: false });
const tags = tagsDB.getTags(automationId, true);
const onUpdate = (t: Record<string, string>) =>
tagsDB.update(automationId, t);
let innerModal: ReactNode = <></>;
if (modalState.open) {
const validTag =
modalState.tag[0].trim().length > 0 &&
modalState.tag[1].trim().length > 0;
innerModal = (
<div className="metadatabox--tags--modal">
<InputAutoText
className="name"
options={tagsDB.getTagNames(Object.keys(tags))}
label="Tag Name"
value={modalState.tag[0]}
onChange={(v) =>
setModal({
...modalState,
tag: [v ?? "", modalState.tag[1]],
})
}
/>
<InputAutoText
className="value"
options={tagsDB.getTagValues(modalState.tag[0])}
label="Tag Value"
value={modalState.tag[1]}
onChange={(v) =>
setModal({
...modalState,
tag: [modalState.tag[0], v ?? ""],
})
}
/>
<div className="buttons">
<Button onClick={() => setModal({ open: false })} color="info">
Close
</Button>
<Button
disabled={!validTag}
onClick={() => {
onUpdate({
...tags,
[modalState.tag[0]]: modalState.tag[1],
});
setModal({ open: false });
}}
color="success"
>
{modalState.isNew ? "Create" : "Save"}
</Button>
</div>
</div>
);
}
return (
<div
className={[
"metadatabox--tags",
tagsDB.isModified(automationId) ? "modified" : "",
].join(" ")}
>
<Modal open={modalState.open}>{innerModal}</Modal>
{Object.entries(tags).map(([tagName, tagValue]) => (
<div key={tagName} className="tag">
<DeleteIcon
onClick={() =>
onUpdate(
cleanUpUndefined({
...tags,
[tagName]: undefined,
})
)
}
className="delete-tag"
/>
<div
className="inner"
onClick={() =>
setModal({
open: true,
isNew: false,
tag: [tagName, tagValue],
})
}
>
<b>{tagName}: </b>
<span>{tagValue}</span>
</div>
<EditIcon
className="edit-icon"
onClick={() =>
setModal({
open: true,
isNew: false,
tag: [tagName, tagValue],
})
}
/>
</div>
))}
<div className="buttons">
<span
className="tag-add"
onClick={() =>
setModal({
open: true,
isNew: true,
tag: ["", ""],
})
}
>
+
</span>
{tagsDB.isModified(automationId) && (
<SaveIcon
className="tag-save"
onClick={() => tagsDB.save(automationId)}
/>
)}
</div>
</div>
);
};
@@ -0,0 +1,87 @@
.automation-manager--metadatabox {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
gap: 0.25em;
padding: 0.25em;
background-color: var(--mui-background-paper);
border-style: solid;
border-width: 1px;
border-color: transparent;
border-radius: 10px;
}
.automation-manager--metadatabox:hover, .automation-manager--metadatabox.selected {
border-color: var(--mui-action-focus);
background-color: var(--mui-action-focus);
}
.automation-manager--metadatabox .metadatabox--title .input-text-view {
max-width: fit-content;
}
.automation-manager--metadatabox .metadatabox--title {
flex: 1;
}
.automation-manager--metadatabox .metadatabox--title .title {
font-size: 1.25em;
font-weight: bold;
}
.automation-manager--metadatabox .metadatabox--title .issue {
padding: 0 0.5em;
user-select: none;
max-width: fit-content;
}
.automation-manager--metadatabox .metadatabox--title .description {
font-size: 0.9em;
}
.automation-manager--metadatabox .buttons {
display: flex;
flex-direction: row;
gap: 0.25em;
}
.automation-manager--metadatabox .delete:hover {
cursor: pointer;
color: var(--mui-error-light);
color: var(--mui-error-contrastText);
background-color: var(--mui-error-dark);
}
.automation-manager--metadatabox .run:hover {
cursor: pointer;
color: var(--mui-success-contrastText);
background-color: var(--mui-success-dark);
}
.automation-manager--metadatabox .select:hover,
.automation-manager--metadatabox.selected.automation-manager--metadatabox .select {
cursor: pointer;
color: var(--mui-primary-light);
background-color: var(--mui-primary-dark);
}
.automation-manager--metadatabox.selected.automation-manager--metadatabox .select:hover {
color: var(--mui-secondary-light);
background-color: var(--mui-secondary-dark);
cursor: default;
}
.automation-manager--metadatabox .metadatabox--switch {
display: flex;
cursor: pointer;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
font-size: 0.75em;
user-select: none;
max-width: 5em;
}
@@ -0,0 +1,5 @@
.mobile .automation-manager--metadatabox .buttons {
display: flex;
flex-direction: column;
gap: 0.5em;
}
@@ -0,0 +1,45 @@
import { MetadataBox } from ".";
import { useTagDB } from "../TagDB";
import { useState } from "react";
import { makeStory } from "devUtils";
const { make, componentMeta } = makeStory({
Component: MetadataBox,
meta: {
title: "App/AutomationManager/MetadataBox",
args: {
id: "dummy",
title: "Example",
description: "Cool!",
state: "on",
isSelected: false,
tags: {
room: "main bedroom",
routine: "night time",
},
},
},
BaseTemplate: (args) => {
const [autoTags, setTags] = useState([{ id: args.id, tags: args.tags }]);
const tagsDB = useTagDB(autoTags, (aid, t) =>
setTags(
autoTags
.filter(({ id }) => id !== aid)
.concat({
id: aid,
tags: t,
})
)
);
return <MetadataBox {...args} tagsDB={tagsDB} />;
},
});
export default componentMeta;
export const Basic = make({});
export const IsSelected = make({ isSelected: true });
export const InvalidState = make({ state: "unavailable" });
export const WithIssue = make({ issue: "look at me" });
export const NewAutomation = make({ isNew: true });
@@ -0,0 +1,94 @@
import "./index.css";
import "./index.mobile.css";
import { FC } from "react";
import Switch from "@mui/material/Switch";
import Alert from "@mui/material/Alert";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import SelectIcon from "@mui/icons-material/HighlightAltSharp";
import RunIcon from "@mui/icons-material/RunCircleOutlined";
import { InputTextView } from "components/Inputs/InputTextView";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { AutomationManagerAuto } from "../types";
import { Tags } from "./Tags";
import { TagDB } from "../TagDB";
export type MetadataBoxProps = AutomationManagerAuto & {
onDelete: () => void;
onSelect: () => void;
onRun: () => void;
onStateUpdate: (s: "on" | "off") => void;
onTitleUpdate: (t: string) => void;
onDescriptionUpdate: (t: string) => void;
tagsDB: TagDB;
isSelected: boolean;
};
export const MetadataBox: FC<MetadataBoxProps> = (props) => {
const isValidState = ["on", "off"].includes(props.state);
return (
<div
className={[
"automation-manager--metadatabox",
props.isSelected ? "selected" : "",
props.isNew ? "new" : "",
].join(" ")}
>
<div
className="metadatabox--switch"
title={!isValidState ? "Invalid state" : `Automation is ${props.state}`}
>
<Switch
checked={props.state !== "off"}
onChange={() =>
props.onStateUpdate(props.state === "on" ? "off" : "on")
}
disabled={!isValidState}
color={!isValidState ? "error" : "info"}
/>
{!isValidState && `Invalid state: '${props.state}'`}
</div>
<div
className="metadatabox--title"
title={`ID=${props.id}, EntityID=${props.entityId}`}
>
<InputTextView
className="title"
placeholder="Title"
value={props.title}
onChange={props.onTitleUpdate}
disabled={props.isNew}
/>
<InputTextView
className="description"
placeholder="Description"
value={props.description}
onChange={props.onDescriptionUpdate}
disabled={props.isNew}
/>
{!props.isNew && <Tags automationId={props.id} tagsDB={props.tagsDB} />}
{props.issue ? (
<Alert severity="warning" className="issue">
{props.issue}
</Alert>
) : (
<></>
)}
</div>
<div className="buttons">
<ButtonIcon
className="select"
icon={<SelectIcon />}
onClick={props.onSelect}
/>
<ButtonIcon className="run" icon={<RunIcon />} onClick={props.onRun} />
<ButtonIcon
className="delete"
icon={<DeleteForeverIcon />}
onClick={props.onDelete}
/>
</div>
</div>
);
};
@@ -0,0 +1,19 @@
import { AutomationManagerAuto } from "../types";
export const filterAutomations = (
autos: AutomationManagerAuto[],
searchText: string
): AutomationManagerAuto[] =>
autos.filter((a) => {
if (searchText.length > 0) {
if (
!(
(a.description ?? "").toLocaleLowerCase().includes(searchText) ||
(a.title ?? "").toLocaleLowerCase().includes(searchText)
)
) {
return false;
}
}
return true;
});
@@ -0,0 +1,51 @@
.automation-manager--sidebar {
display: flex;
flex-direction: column;
--nav-height: 10em;
--bottom-height: 3em;
position: relative;
height: 100%;
min-width: calc(min(max(25vw, 35em), 50vw));
}
.automation-manager--sidebar-box--nav {
max-height: var(--nav-height);
}
.automation-manager--sidebar .automation-manager--sidebar-box--list {
flex: 1;
max-height: calc(100vh - var(--bottom-height) - var(--nav-height));
min-height: calc(100vh - var(--bottom-height) - var(--nav-height));
overflow: auto;
box-shadow: 1px 1px var(--mui-primary-light);
}
.automation-manager--sidebar-box--bottom-buttons {
height: 100%;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
position: relative;
}
.automation-manager--sidebar-box--bottom-buttons .hide-btn {
position: absolute;
right: 0;
}
.automation-manager--sidebar.hidden {
width: 2.5em;
min-width: 0;
}
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--nav,
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--list,
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--bottom-buttons .add-btn {
width: 0;
opacity: 0;
}
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--bottom-buttons .hide-btn {
transform: rotate(180deg);
}
@@ -0,0 +1,33 @@
.mobile .automation-manager--sidebar.shown {
height: 100vh;
min-height: 100vh;
min-width: 100vw;
}
.mobile .automation-manager--sidebar .automation-manager--sidebar-box--bottom-buttons .hide-btn {
transform: rotate(-90deg);
left: 0.5em;
background-color: var(--mui-background-paper);
height: 2em;
width: 2em;
}
.mobile .automation-manager--sidebar.hidden {
height: 0;
min-height: 0;
}
.mobile .automation-manager--sidebar.hidden .automation-manager--sidebar-box--nav,
.mobile .automation-manager--sidebar.hidden .automation-manager--sidebar-box--list {
display: none;
}
.mobile .automation-manager--sidebar.hidden .automation-manager--sidebar-box--bottom-buttons {
height: 0;
}
.mobile .automation-manager--sidebar.hidden .automation-manager--sidebar-box--bottom-buttons .hide-btn {
transform: rotate(90deg);
top: 1em;
z-index: 100;
}
@@ -0,0 +1,123 @@
import { AutomationManagerSidebar } from ".";
import { useTagDB } from "../TagDB";
import { useState } from "react";
import { AutomationManagerAuto } from "../types";
import { makeStory } from "devUtils";
const story = makeStory({
meta: {
title: "App/AutomationManager/Sidebar",
},
Component: AutomationManagerSidebar,
BaseTemplate: (args) => {
const [automations, setAutomations] = useState(args.automations);
const [selectedAutomationId, setSelAutoId] = useState(
args.selectedAutomationId
);
const onTagUpdate = (tags: Record<string, string>, aid: string) => {
const index = automations.findIndex(({ id }) => id === aid);
if (index >= 0) {
setAutomations([
...automations.slice(0, index),
{
...automations[index],
tags,
},
...automations.slice(index + 1),
]);
}
};
return (
<AutomationManagerSidebar
selectedAutomationId={selectedAutomationId}
tagsDB={useTagDB(automations, (a, t) => onTagUpdate(t, a))}
automations={automations}
onRun={args.onRun}
onSelectedAutomationId={(aid) => {
args.onSelectedAutomationId(aid);
setSelAutoId(aid);
}}
onAutomationDelete={(aid, eid) => {
args.onAutomationDelete(aid, eid);
setAutomations(automations.filter(({ id }) => id !== aid));
}}
onAutomationUpdate={(a, aid, eid) => {
args.onAutomationUpdate(a, aid, eid);
const index = automations.findIndex(({ id }) => id === aid);
if (index >= 0) {
setAutomations([
...automations.slice(0, index),
{
...automations[index],
...a,
},
...automations.slice(index + 1),
]);
}
}}
onAutomationAdd={() => {
args.onAutomationAdd();
const id = String(Date.now());
setAutomations([
...automations,
{
id,
description: "",
title: "new",
tags: {},
entityId: "automation." + id,
state: "on",
},
]);
setSelAutoId(id);
}}
/>
);
},
});
export default story.componentMeta;
const make = (automations: AutomationManagerAuto[]) =>
story.make({
automations,
});
const makeAuto = (
data: Partial<AutomationManagerAuto>
): AutomationManagerAuto => {
const id = `${Date.now()}_${Math.random().toString(26).slice(3, 6)}`;
return {
id,
entityId: `automation.${id}`,
title: "",
description: "",
state: "on",
tags: {},
...data,
};
};
export const Empty = make([]);
export const Basic = make([
makeAuto({ title: "example 1" }),
makeAuto({ title: "example 2", state: "off" }),
makeAuto({ title: "example 3", state: "invalid" }),
makeAuto({ title: "example 4", issue: "I have an issue!" }),
]);
export const Tagged = make([
makeAuto({ title: "example 1", tags: { room: "bathroom", floor: "1" } }),
makeAuto({ title: "example 2", tags: { type: "routine" } }),
makeAuto({
title: "example 3",
tags: { room: "living room", type: "climate" },
}),
makeAuto({
title: "example 4",
tags: { room: "bedroom", floor: "2", type: "button" },
}),
makeAuto({
title: "example 5",
tags: { room: "bedroom", floor: "2", type: "routine", mode: "party" },
}),
]);
@@ -0,0 +1,123 @@
import "./index.css";
import "./index.mobile.css";
import { FC, useState } from "react";
import ArrowIcon from "@mui/icons-material/ArrowBackIosNewOutlined";
import InputText from "components/Inputs/Base/InputText";
import InputMultiSelect from "components/Inputs/InputMultiSelect";
import { ListBoxGroup } from "../ListBoxGroup";
import { filterAutomations } from "./helpers";
import { TagDB } from "../TagDB";
import { convertGroupingToItems, makeGrouping } from "../automationGrouper";
import {
AutomationManagerAuto,
AutomationManagerAutoUpdatable,
} from "../types";
import { Button } from "components/Inputs/Buttons/Button";
import { ButtonIcon } from "components/Icons/ButtonIcons";
export type AutomationManagerSidebarProps = {
tagsDB: TagDB;
automations: AutomationManagerAuto[];
selectedAutomationId: string | null;
onAutomationUpdate: (
a: AutomationManagerAutoUpdatable,
aid: string,
eid: string
) => void;
onAutomationDelete: (aid: string, eid: string) => void;
onAutomationAdd: () => void;
onSelectedAutomationId: (aid: string) => void;
onRun: (eid: string) => void;
};
export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
automations,
tagsDB,
onAutomationAdd,
selectedAutomationId,
onSelectedAutomationId,
...events
}) => {
const [searchText, setSearchText] = useState("");
const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>([]);
const [isHidden, setHidden] = useState(false);
const tags = tagsDB.getTagNames([]);
if (searchText.trim().length > 0) {
automations = filterAutomations(
automations,
searchText.toLocaleLowerCase()
);
}
const grouping = makeGrouping(
automations,
selectedTagIdx.map((i) => tags[i]),
selectedAutomationId
);
const items = grouping.top.map((i) =>
convertGroupingToItems(i, automations, grouping, (aid, t) => ({
...t,
isSelected: aid === selectedAutomationId,
isModified: tagsDB.isModified(aid),
}))
);
return (
<div
className={[
"automation-manager--sidebar",
isHidden ? "hidden" : "shown",
].join(" ")}
>
<div className="automation-manager--sidebar-box--nav">
<InputText label="Search" value={searchText} onChange={setSearchText} />
<InputMultiSelect
label="Tags"
selected={selectedTagIdx}
onChange={setSelectedTagIdx}
options={tags}
max={3}
/>
</div>
<div className="automation-manager--sidebar-box--list">
{items.map((item, i) => (
<ListBoxGroup
{...item}
key={i}
onSelect={(id) => {
onSelectedAutomationId(id);
setHidden(true);
}}
{...events}
tagsDB={tagsDB}
initialOpenState={true}
/>
))}
</div>
<div className="automation-manager--sidebar-box--bottom-buttons">
<Button
onClick={() => {
onAutomationAdd();
setHidden(true);
}}
color="primary"
className="add-btn"
>
Add
</Button>
<ButtonIcon
className="hide-btn"
color="secondary"
icon={<ArrowIcon />}
onClick={() => setHidden(!isHidden)}
/>
</div>
</div>
);
};
@@ -0,0 +1,110 @@
import { useEffect, useRef, useState } from "react";
type TagDBState = {
original: Record<string, Record<string, string>>;
changed: Record<string, Record<string, string>>;
};
export type TagDB = ReturnType<typeof useTagDB>;
export const useTagDB = (
automations: Array<{
id: string;
tags: Record<string, string>;
}>,
onUpdate: (aid: string, tags: Record<string, string>) => void
) => {
const lastAuto = useRef(JSON.stringify(automations));
const [{ original, changed }, setState] = useState<TagDBState>({
original: convertAutoListToMap(automations),
changed: {},
});
const allTags = computeAllTags(original);
const allTagNames = Object.keys(allTags);
const isModified = Object.keys(changed).length > 0;
useEffect(() => {
const c = JSON.stringify(automations);
if (lastAuto.current !== c) {
lastAuto.current = c;
setState({
original: convertAutoListToMap(automations),
changed: {},
});
}
}, [automations, setState]);
return {
getTags(automationId: string, includeChanged: boolean = false) {
if (includeChanged) {
return changed[automationId] ?? original[automationId] ?? {};
}
return original[automationId] ?? {};
},
getTagNames(myTags: string[]): string[] {
return allTagNames.filter((n) => !myTags.includes(n)).sort();
},
getTagValues(tagName: string): string[] {
return allTags[tagName]
? Array.from(allTags[tagName].values()).sort()
: [];
},
isModified(aid: string): boolean {
return aid in changed;
},
update(aid: string, tags: Record<string, string>) {
const update = JSON.stringify(tags);
if (aid in changed) {
if (update === JSON.stringify(changed[aid])) {
return;
}
} else if (update === JSON.stringify(original[aid])) {
return;
}
setState({
changed: {
...changed,
[aid]: tags,
},
original,
});
},
save(aid: string | null) {
if (isModified) {
if (aid) {
onUpdate(aid, changed[aid]);
} else {
for (const [aid, change] of Object.entries(changed)) {
onUpdate(aid, change);
}
}
}
},
};
};
const convertAutoListToMap = (
automations: Array<{
id: string;
tags: Record<string, string>;
}>
) => {
const automationTags: Record<string, Record<string, string>> = {};
automations.forEach(({ id, tags }) => {
automationTags[id] = tags;
});
return automationTags;
};
const computeAllTags = (
automations: Record<string, Record<string, string>>
) => {
const allTags: Record<string, Set<string>> = {};
Object.values(automations).forEach((tags) => {
Object.keys(tags).forEach((tagName) => {
const tagValue = tags[tagName];
if (!allTags[tagName]) {
allTags[tagName] = new Set();
}
allTags[tagName].add(tagValue);
});
});
return allTags;
};
@@ -0,0 +1,137 @@
import { convertGroupingToItems, makeGrouping } from "./automationGrouper";
import { bigMockAutoList, createMockAuto } from "utils/mocks";
import { AutomationManagerAuto } from "./types";
const automations: AutomationManagerAuto[] = [
createMockAuto({
Room: "Living Room",
Type: "Lights",
}),
createMockAuto({
Room: "Living Room",
Type: "Climate",
}),
createMockAuto({
Room: "Kitchen",
Type: "Climate",
}),
createMockAuto({
Type: "Climate",
}),
createMockAuto({
Room: "Living Room",
}),
createMockAuto({}),
].map<AutomationManagerAuto>((a) => ({
title: a.metadata.alias ?? "",
entityId: "automation." + a.metadata.id,
description: a.metadata.description ?? "",
state: "on",
tags: a.tags,
id: a.metadata.id,
isSelected: false,
}));
const bigList = bigMockAutoList.map<AutomationManagerAuto>((a) => ({
entityId: "automation." + a.metadata.id,
title: a.metadata.alias ?? "",
description: a.metadata.description ?? "",
state: "on",
tags: a.tags,
id: a.metadata.id,
isSelected: false,
}));
test("no grouping", () => {
const grouped = makeGrouping(automations, [], automations[0].id);
expect(grouped.top).toStrictEqual([0]);
expect(grouped.getAutomations(0)).toStrictEqual([0, 1, 2, 3, 4, 5]);
});
test("1 grouping", () => {
const grouped = makeGrouping(automations, ["Room"], automations[0].id);
expect(grouped.top).toHaveLength(3);
expect(grouped.getAutomations(0)).toStrictEqual([0, 1, 4]);
expect(grouped.getAutomations(1)).toStrictEqual([2]);
expect(grouped.getAutomations(2)).toStrictEqual([3, 5]);
});
test("2 groupings", () => {
const grouped = makeGrouping(
automations,
["Room", "Type"],
automations[0].id
);
expect(grouped.top).toHaveLength(3);
expect(grouped.getAutomations(grouped.top[0])).toHaveLength(0);
expect(grouped.getSubGroups(grouped.top[0])).toHaveLength(3);
expect(grouped.getAutomations(grouped.top[1])).toHaveLength(0);
expect(grouped.getSubGroups(grouped.top[1])).toHaveLength(1);
expect(grouped.getAutomations(grouped.top[2])).toHaveLength(2);
expect(grouped.getSubGroups(grouped.top[2])).toHaveLength(0);
});
test("bigAutoList groupings has not duplicate ids", () => {
const grouped = makeGrouping(bigList, ["Room", "Remote"], bigList[0].id);
const flattenAndCount = (gid: number): Record<number, number[]> => {
const subgroups = grouped.getSubGroups(gid);
if (subgroups.length > 0) {
return flattenAndConsolidate(subgroups);
} else {
return grouped
.getAutomations(gid)
.reduce((sum: Record<number, number[]>, b) => {
sum[b] = (sum[b] ?? []).concat(gid);
return sum;
}, {});
}
};
const flattenAndConsolidate = (gids: number[]): Record<number, number[]> =>
gids.map(flattenAndCount).reduce((a, b) => {
for (const k of Object.keys(b).map(Number)) {
a[k] = (a[k] ?? []).concat(b[k]);
}
return a;
}, {});
const countedAutos = flattenAndConsolidate(grouped.top);
for (const key of Object.keys(countedAutos).map(Number)) {
expect(countedAutos[key]).toHaveLength(1);
}
});
test("convert grouper to items when no tags are selected", () => {
const grouping = makeGrouping(automations, [], null);
const items = grouping.top.map((i) =>
convertGroupingToItems(i, automations, grouping)
);
expect(items.filter((i) => i.type === "group")).toHaveLength(0);
expect(items).toHaveLength(1);
expect(items[0].data).toHaveLength(automations.length);
});
test("convert grouper to items when 1 tag is selected", () => {
const grouping = makeGrouping(automations, ["Room"], null);
const items = grouping.top.map((i) =>
convertGroupingToItems(i, automations, grouping)
);
expect(grouping.top).toHaveLength(3);
expect(items.filter((i) => i.type === "group")).toHaveLength(0);
expect(items).toHaveLength(3);
expect(items[0].data).toHaveLength(3);
expect(items[1].data).toHaveLength(1);
expect(items[2].data).toHaveLength(2);
expect(items[0].title).toEqual("Living Room");
expect(items[1].title).toEqual("Kitchen");
expect(items[2].title).toEqual("");
});
test("convert grouper to items when 2 tag is selected", () => {
const grouping = makeGrouping(automations, ["Room", "Type"], null);
const items = grouping.top.map((i) =>
convertGroupingToItems(i, automations, grouping)
);
expect(grouping.top).toHaveLength(3);
expect(items.filter((i) => i.type === "group")).toHaveLength(2);
expect(items.filter((i) => i.type === "items")).toHaveLength(1);
expect(items).toHaveLength(3);
expect(items[0].data).toHaveLength(3);
expect(items[1].data).toHaveLength(1);
expect(items[2].data).toHaveLength(2);
});
@@ -0,0 +1,212 @@
import {
AutomationManagerAuto,
AutomationManagerAutoItem,
AutomationManagerItem,
AutomationManagerItemFlags,
} from "./types";
const makeGrouper = () => {
const groupIdNames: string[] = [];
const groupSubGroups: Array<Set<number>> = []; // groupIdx => Array<groupIdx>
const groupAutomations: number[][] = []; // groupIdx => Array<automationIdx>
const groupData: Array<{
name: string;
selected: boolean;
isOther: boolean;
isTop: boolean;
}> = []; // source of truth for groupIdx
const topGroups: number[] = [];
return {
groupIdNames,
groupSubGroups,
groupAutomations,
groupData,
topGroups,
addNew(
groupId: string,
groupName: string,
theChosenOne: boolean,
isTopLevel: boolean,
isOther: boolean = false
): number {
groupIdNames.push(groupId);
groupSubGroups.push(new Set());
groupAutomations.push([]);
groupData.push({
name: groupName,
selected: theChosenOne,
isTop: isTopLevel,
isOther,
});
const groupIdx = groupIdNames.length - 1;
if (isTopLevel) {
topGroups.push(groupIdx);
}
return groupIdx;
},
updateGroup(
groupIdx: number,
update: {
isChosen: boolean;
lastGroupIdx: number | null;
autoIdx: number | null;
}
) {
if (update.isChosen) {
groupData[groupIdx].selected = true;
}
if (update.lastGroupIdx !== null) {
groupSubGroups[update.lastGroupIdx].add(groupIdx);
}
if (update.autoIdx !== null) {
groupAutomations[groupIdx].push(update.autoIdx);
}
},
};
};
export type AutomationGrouping = ReturnType<typeof makeGrouping>;
export const makeGrouping = (
autos: AutomationManagerAuto[],
selectedTags: string[],
selectedAutomationId: string | null
) => {
const grouper = makeGrouper();
if (selectedTags.length === 0) {
grouper.addNew("$", "", selectedAutomationId !== null, true, true);
grouper.groupAutomations = [autos.map((_, i) => i)];
} else {
autos.forEach((auto, autoIdx) => {
const theChosenOne = selectedAutomationId === auto.id;
let lastGroupIdx: number | null = null;
let lastGroupId: string = "$";
for (let ti = 0; ti < selectedTags.length; ti++) {
const isTopLevel = ti === 0;
const selTag = selectedTags[ti];
if (selTag in auto.tags) {
const groupName = auto.tags[selTag];
const groupId = `${lastGroupId}>${selTag}:${groupName}`;
let groupIdx = grouper.groupIdNames.indexOf(groupId);
if (groupIdx < 0) {
groupIdx = grouper.addNew(
groupId,
groupName,
theChosenOne,
isTopLevel
);
}
grouper.updateGroup(groupIdx, {
isChosen: theChosenOne,
lastGroupIdx,
autoIdx: ti === selectedTags.length - 1 ? autoIdx : null,
});
lastGroupIdx = groupIdx;
lastGroupId = groupId;
} else {
const groupId = `${lastGroupId}>${selTag}:$`;
let groupIdx = grouper.groupIdNames.indexOf(groupId);
if (groupIdx < 0) {
groupIdx = grouper.addNew(
groupId,
"",
theChosenOne,
isTopLevel,
true
);
}
grouper.updateGroup(groupIdx, {
isChosen: theChosenOne,
lastGroupIdx,
autoIdx,
});
break;
}
}
});
}
const sortGroupIds = (groupIds: number[]) =>
groupIds.sort((a, b) => {
const adata = grouper.groupData[a];
const bdata = grouper.groupData[b];
if (adata.isOther) {
return 1;
} else {
return adata.name > bdata.name ? -1 : 1;
}
});
return {
top: sortGroupIds(grouper.topGroups),
getSubGroups(groupIdx: number) {
return sortGroupIds(
Array.from(grouper.groupSubGroups[groupIdx].values())
);
},
getAutomations(groupIdx: number) {
return grouper.groupAutomations[groupIdx];
},
getData(groupIdx: number) {
return grouper.groupData[groupIdx];
},
};
};
export const convertGroupingToItems = (
currentGroupIdx: number,
autos: AutomationManagerAuto[],
grouping: AutomationGrouping,
computeFlags: (
aid: string,
f: AutomationManagerItemFlags
) => AutomationManagerItemFlags = (aid, t) => t
): AutomationManagerItem => {
const groupData = grouping.getData(currentGroupIdx);
const automationIds = grouping.getAutomations(currentGroupIdx);
if (automationIds.length > 0) {
const data = automationIds.map<AutomationManagerAutoItem>((i) => {
return {
...autos[i],
flags: computeFlags(autos[i].id, {
isSelected: false,
isModified: false,
}),
};
});
return {
type: "items",
title: groupData.name,
data,
flags: data.reduce<AutomationManagerItemFlags>(
(out, a) => ({
isSelected: out.isSelected || a.flags.isSelected,
isModified: out.isModified || a.flags.isModified,
}),
{
isSelected: false,
isModified: false,
}
),
};
}
const subgroups = grouping.getSubGroups(currentGroupIdx);
const data = subgroups.map((i) =>
convertGroupingToItems(i, autos, grouping, computeFlags)
);
return {
type: "group",
title: groupData.name,
data,
flags: data.reduce<AutomationManagerItemFlags>(
(out, a) => ({
isSelected: out.isSelected || a.flags.isSelected,
isModified: out.isModified || a.flags.isModified,
}),
{
isSelected: false,
isModified: false,
}
),
};
};
@@ -0,0 +1,26 @@
.automation-manager {
display: flex;
flex-direction: row;
height: 100%;
width: 100%;
gap: 0.25em;
}
.mobile .automation-manager, .automation-manager.error {
flex-direction: column;
}
.automation-manager.loading .automation-manager--sidebar.loading {
width: 25vh;
height: 100%;
}
.automation-manager.loading .MuiSkeleton-root {
height: 100%;
width: 100%;
}
.automation-manager.loading .automation-manager--editor.loading {
flex: 1;
height: 100%;
}
@@ -0,0 +1,173 @@
import { makeStory } from "devUtils";
import { useMockApiService } from "apiService";
import { AutomationManager } from ".";
import {
MockHAEntitiesProps,
useMockHAEntities,
} from "haService/HAEntities.mock";
import { AutomationData } from "types/automations";
import { createMockAuto } from "utils/mocks";
import { useState } from "react";
const { make, componentMeta } = makeStory({
Component: (args: {
automations?: AutomationData[];
haProps: MockHAEntitiesProps;
}) => {
const [haEntities, setHAE] = useState(args.haProps);
return (
<AutomationManager
api={useMockApiService(args.automations ?? [], !args.automations)}
haEntities={useMockHAEntities(haEntities)}
refreshAutomations={() => {}}
triggerAutomation={() => {}}
forceDeleteAutomation={() => {}}
onAutomationStateChange={(eid, on) => {
if (!haEntities.loading && !haEntities.error) {
setHAE({
...haEntities,
entities: {
...haEntities.entities,
[eid]: {
...haEntities.entities[eid],
state: on ? "on" : "off",
},
},
});
}
}}
/>
);
},
meta: {
title: "App/AutomationManager",
args: {
automations: [],
haProps: {
loading: true,
},
},
},
});
export default componentMeta;
export const Loading = make({});
export const ErroredByAPI = make({
automations: undefined,
haProps: {
loading: false,
entities: {},
entitySource: {},
},
});
export const ErroredByWS = make({
automations: [],
haProps: {
loading: false,
error: {
entities: { originalError: "1", message: "Failed to connect" },
entitySource: { originalError: "1", message: "Failed to connect" },
},
},
});
export const Empty = make({
automations: [],
haProps: {
loading: false,
entities: {},
entitySource: {},
},
});
const auto1 = createMockAuto({
type: "button",
});
export const One = make({
automations: [auto1],
haProps: {
loading: false,
entities: {
[`automation.${auto1.metadata.id}`]: {
entity_id: `automation.${auto1.metadata.id}`,
attributes: {
id: auto1.metadata.id,
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
last_updated: "",
state: "on",
},
},
entitySource: {},
},
});
export const MissingAutoInConfig = make({
automations: [],
haProps: {
loading: false,
entities: {
[`automation.${auto1.metadata.id}`]: {
entity_id: `automation.${auto1.metadata.id}`,
attributes: {
id: auto1.metadata.id,
friendly_name: auto1.metadata.alias,
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
last_updated: "",
state: "on",
},
},
entitySource: {},
},
});
export const BadAutomation = make({
haProps: {
loading: false,
entities: {
[`automation.${auto1.metadata.id}`]: {
entity_id: `automation.${auto1.metadata.id}`,
attributes: {
id: "test",
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
last_updated: "",
state: "on",
},
},
entitySource: {},
},
automations: [
{
tags: {},
metadata: {
id: "test",
mode: "single",
alias: "Light.Tank_Day",
description: "",
},
trigger: [
{
platform: "sun",
event: "sunrise",
offset: "30",
} as any,
{ whoAmI: "bad node is who" } as any,
],
condition: [{ whoAmI: "bad node is who" } as any],
sequence: [
{ scene: "scene.light_day" } as any,
{ whoAmI: "bad node is who" } as any,
{
service: "input_select.set_options",
target: {
entity_id: "input_select.tank_light_mode",
},
data: {
options: "day",
},
},
],
},
],
});
@@ -0,0 +1,152 @@
import "./index.css";
import { FC, useEffect, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress";
import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "apiService/core";
import { HAEntitiesState } from "haService/HAEntities";
import { AutomationManagerLoaded } from "./Loaded";
import { Alert } from "@mui/material";
import { useSnackbar } from "notistack";
export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => void;
refreshAutomations: () => void;
forceDeleteAutomation: (eid: string) => void;
triggerAutomation: (eid: string) => void;
haEntities: HAEntitiesState;
api: ApiService;
};
export const AutomationManager: FC<AutomationManagerProps> = ({
api,
haEntities,
onAutomationStateChange,
refreshAutomations,
forceDeleteAutomation,
triggerAutomation,
}) => {
const snackbr = useSnackbar();
const [isSaving, setIsSaving] = useState(false);
useEffect(() => {
refreshAutomations();
// eslint-disable-next-line
}, []);
// handle bad states
if (!haEntities.ready && haEntities.error) {
return (
<div className="automation-manager error">
<Alert color="error">
Failed to connect to websocket, please check that your access token is
properly setup
</Alert>{" "}
<br />
<code>{JSON.stringify(haEntities.error)}</code>
</div>
);
}
if (!haEntities.ready || !api.state.automations.ready) {
return (
<div className="automation-manager loading">
<div className="automation-manager--sidebar loading">
<Skeleton />
</div>
<div className="automation-manager--editor loading">
<Skeleton />
</div>
</div>
);
}
if (!api.state.automations.ok) {
return (
<div className="automation-manager error">
<Alert color="error">
Failed to load automations from <code>/config</code>
</Alert>{" "}
<br />
<code>{api.state.automations.error}</code>
</div>
);
}
// alias
const configAutomations = api.state.automations.data;
const hassEntities = haEntities.collection;
return (
<AutomationManagerLoaded
configAutomations={configAutomations.data}
hassEntities={hassEntities}
onAutomationRun={triggerAutomation}
onAutomationStateChange={onAutomationStateChange}
onAutomationAdd={async (auto) => {
await api.updateAutomation({
index: configAutomations.totalItems + 1,
auto,
});
refreshAutomations();
}}
onAutomationDelete={(aid, eid) => {
const index = configAutomations.data.findIndex(
({ metadata }) => metadata.id === aid
);
let deleteSent = false;
if (index >= 0) {
api.removeAutomation({
index,
});
deleteSent = true;
}
const hassAuto = hassEntities[eid];
if (hassAuto) {
forceDeleteAutomation(eid);
deleteSent = true;
}
if (!deleteSent) {
snackbr.enqueueSnackbar(
"Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant",
{
variant: "error",
}
);
}
// refreshAutomations();
}}
onAutomationUpdate={(aid, auto) => {
const index = configAutomations.data.findIndex(
({ metadata }) => metadata.id === aid
);
if (index >= 0) {
api.updateAutomation({
index: configAutomations.data.findIndex(
({ metadata }) => metadata.id === aid
),
auto,
});
refreshAutomations();
} else {
snackbr.enqueueSnackbar(
"Failed to update automation, this may be resolved by a refresh or reboot of Home Assistant.",
{
variant: "error",
}
);
}
}}
onUpdateTags={async (aid, t) => {
setIsSaving(true);
await api.updateTags({
automation_id: aid,
tags: t,
});
setIsSaving(false);
}}
>
{isSaving && <LinearProgress />}
</AutomationManagerLoaded>
);
};
@@ -0,0 +1,32 @@
export type AutomationManagerAutoUpdatable = {
title: string;
description: string;
state: "on" | "off" | string;
};
export type AutomationManagerAuto = AutomationManagerAutoUpdatable & {
id: string;
entityId: string;
tags: Record<string, string>;
issue?: string;
isNew?: boolean;
};
export type AutomationManagerAutoItem = AutomationManagerAuto & {
flags: AutomationManagerItemFlags;
};
export type AutomationManagerItemFlags = {
isSelected: boolean;
isModified: boolean;
};
export type AutomationManagerItem = {
title: string;
flags: AutomationManagerItemFlags;
} & (
| {
type: "group";
data: Array<AutomationManagerItem>;
}
| {
type: "items";
data: Array<AutomationManagerAutoItem>;
}
);
@@ -1,19 +1,19 @@
.condition-node-base.mobile {
.mobile .condition-node-base {
flex-direction: column;
justify-content: center;
}
.condition-node-base.mobile .condition-node-base--list {
.mobile .condition-node-base .condition-node-base--list {
flex-direction: row;
display: flex;
min-width: 100%;
}
.condition-node-base.mobile .condition-node-base--body {
.mobile .condition-node-base .condition-node-base--body {
min-height: 3em;
max-width: 100%;
}
.condition-node-base.mobile .condition-node-base--body.edit {
.mobile .condition-node-base .condition-node-base--body.edit {
max-height: 500px;
}
@@ -7,7 +7,7 @@ import { AutomationCondition } from "types/automations/conditions";
import { getSubTypeList } from "utils/automations";
import { getConditionDefaultValues } from "utils/defaults";
import { useHA } from "haService";
import InputYaml from "components/Inputs/InputYaml";
import InputYaml from "components/Inputs/Base/InputYaml";
import { getViewer } from "./viewRender";
import { getEditor } from "./editorRender";
import useWindowSize from "utils/useWindowSize";
@@ -84,11 +84,7 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
// render
return (
<div
className={[
"condition-node-base",
isMobile ? "mobile" : "",
isEdited ? "is-edited" : "",
].join(" ")}
className={["condition-node-base", isEdited ? "is-edited" : ""].join(" ")}
>
<div className="condition-node-base--list">
<InputList
@@ -10,26 +10,26 @@ import {
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 InputNumber from "components/Inputs/Base/InputNumber";
import InputText from "components/Inputs/Base/InputText";
import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import {
ConditionNodeBase,
ConditionNodeBaseViewMode,
} from "./ConditionNodeBase";
import { genUpdateMethods } from "./nestedUpdater";
import { InputTime } from "components/Inputs/InputTime";
import InputYaml from "components/Inputs/InputYaml";
import { InputTime } from "components/Inputs/Base/InputTime";
import InputYaml from "components/Inputs/Base/InputYaml";
import { HAService } from "haService";
import { DeviceEditor } from "components/DeviceEditor";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import AddIcon from "@mui/icons-material/Add";
import { getEntityDomains } from "utils/automations";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { InputTimeEntity } from "components/Inputs/InputTimeEntity";
import { InputAutoComplete } from "components/Inputs/AutoComplete/InputAutoComplete";
import { InputTimeEntity } from "components/Inputs/AutoComplete/InputTimeEntity";
import { prettyName } from "utils/formatting";
import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button";
import { Button } from "components/Inputs/Buttons/Button";
import { RemoveCircle } from "@mui/icons-material";
interface Editor<C extends AutomationCondition>
@@ -6,7 +6,7 @@ export const NODE_HEIGHT = 80 as const;
export const DEFAULT_DIMS: DAGDims = {
collection: {
height: NODE_HEIGHT * 3,
width: NODE_WIDTH * 1.5,
width: NODE_WIDTH * 2.5,
},
node: {
height: NODE_HEIGHT,
@@ -8,67 +8,61 @@ import { AutomationActionData } from "types/automations";
import { createUpdaterFromAutomationData } from "../updater";
import { ModalState } from "../board/types";
import { DEFAULT_DIMS } from "./constants";
import { makeStory } from "devUtils";
const Demo: FC<{
automation: AutomationActionData;
flipped: boolean;
}> = (props) => {
const { namer } = useHA();
const [state, setState] = useState<AutomationActionData>(props.automation);
const [modalState, setModalState] =
useState<ModalState | undefined>(undefined);
const updater = createUpdaterFromAutomationData(
setModalState,
state,
setState
);
const elementData = useAutomationNodes(state, {
dims: {
...DEFAULT_DIMS,
flipped: props.flipped,
},
namer,
openModal: setModalState,
stateUpdater: updater,
});
return (
<DAGGraphBoard
modalState={modalState}
closeModal={() => setModalState(undefined)}
state={{
ready: true,
data: {
elements: elementData,
},
}}
/>
);
};
export default {
title: "DAGGraph/Elements",
component: Demo,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
flipped: true,
automation: {
trigger: [],
condition: [],
sequence: [],
const { make, componentMeta } = makeStory({
Component: (props: {
automation: AutomationActionData;
flipped: boolean;
}) => {
const { namer } = useHA();
const [state, setState] = useState<AutomationActionData>(props.automation);
const [modalState, setModalState] =
useState<ModalState | undefined>(undefined);
const updater = createUpdaterFromAutomationData(
setModalState,
state,
setState
);
const elementData = useAutomationNodes(state, {
dims: {
...DEFAULT_DIMS,
flipped: props.flipped,
},
namer,
openModal: setModalState,
stateUpdater: updater,
});
return (
<DAGGraphBoard
modalState={modalState}
closeModal={() => setModalState(undefined)}
state={{
ready: true,
data: {
elements: elementData,
},
}}
/>
);
},
meta: {
title: "DAGGraph/Elements",
args: {
flipped: true,
automation: {
trigger: [],
condition: [],
sequence: [],
},
},
},
} as ComponentMeta<typeof Demo>;
});
const Template: ComponentStory<typeof Demo> = (args) => (
<Page>
<Demo {...args} />
</Page>
);
export default componentMeta;
export const Empty = Template.bind({});
export const Trigger = Template.bind({});
Trigger.args = {
...Trigger.args,
export const Empty = make({});
export const Trigger = make({
automation: {
trigger: [
{ platform: "homeassistant", event: "up" },
@@ -82,10 +76,9 @@ Trigger.args = {
condition: [],
sequence: [],
},
};
export const Conditions = Template.bind({});
Conditions.args = {
...Conditions.args,
});
export const Conditions = make({
automation: {
trigger: [
{
@@ -119,11 +112,9 @@ Conditions.args = {
],
sequence: [],
},
};
});
export const FullAuto = Template.bind({});
FullAuto.args = {
...FullAuto.args,
export const FullAuto = make({
automation: {
condition: [
{
@@ -272,11 +263,9 @@ FullAuto.args = {
},
],
},
};
});
export const ChooseAuto = Template.bind({});
ChooseAuto.args = {
...ChooseAuto.args,
export const ChooseAuto = make({
automation: {
condition: [],
trigger: [],
@@ -370,12 +359,9 @@ ChooseAuto.args = {
},
],
},
};
});
export const EmptyChooseAuto = Template.bind({});
EmptyChooseAuto.args = {
...EmptyChooseAuto.args,
export const EmptyChooseAuto = make({
automation: {
condition: [],
trigger: [],
@@ -386,11 +372,9 @@ EmptyChooseAuto.args = {
},
],
},
};
});
export const RepeatAuto = Template.bind({});
RepeatAuto.args = {
...RepeatAuto.args,
export const RepeatAuto = make({
automation: {
condition: [],
trigger: [],
@@ -437,11 +421,9 @@ RepeatAuto.args = {
},
],
},
};
});
export const ParallelAuto = Template.bind({});
ParallelAuto.args = {
...ParallelAuto.args,
export const ParallelAuto = make({
automation: {
condition: [],
trigger: [],
@@ -467,11 +449,9 @@ ParallelAuto.args = {
},
],
},
};
});
export const BadNodes = Template.bind({});
BadNodes.args = {
...BadNodes.args,
export const BadNodes = make({
automation: {
condition: [
{
@@ -500,11 +480,9 @@ BadNodes.args = {
},
] as any,
},
};
});
export const IfElseNode = Template.bind({});
IfElseNode.args = {
...IfElseNode.args,
export const IfElseNode = make({
automation: {
condition: [],
trigger: [],
@@ -516,4 +494,24 @@ IfElseNode.args = {
},
],
},
};
});
export const TimeNodes = make({
automation: {
condition: [],
trigger: [
{
platform: "time",
at: "",
},
{
platform: "time_pattern",
},
],
sequence: [
{
condition: "time",
},
],
},
});
@@ -29,7 +29,7 @@ export const useDAGElementsState = () => {
},
getIsClosedActions(nodeId: string, node: AutomationNode) {
if (isSpecialNode(getNodeSubType(node))) {
if (isSpecialNode(getNodeSubType(node, true))) {
return {
isClosed: this.get(nodeId).isClosed ?? false,
setIsClosed: (v: boolean) => this.set(nodeId, "isClosed", v),
-1
View File
@@ -19,7 +19,6 @@ export const DAGAutomationGraph: FC<{
isFlipped: boolean;
additionalControls?: ReactNode;
}> = (props) => {
console.log({ props });
const { namer } = useHA();
const [modalState, setModalState] =
useState<ModalState | undefined>(undefined);
@@ -4,7 +4,7 @@ import { ButtonIcon } from "components/Icons/ButtonIcons";
import { FC } from "react";
import { ButtonNodeProps } from "./types";
import { Handle, Position } from "react-flow-renderer";
import { Button } from "components/Inputs/Button";
import { Button } from "components/Inputs/Buttons/Button";
export const ButtonNode: FC<ButtonNodeProps> = ({
height,
@@ -12,7 +12,7 @@ import Edit from "@mui/icons-material/Edit";
import KeyboardArrowDownSharpIcon from "@mui/icons-material/KeyboardArrowDownSharp";
import AddOutlined from "@mui/icons-material/AddOutlined";
import InputBoolean from "components/Inputs/InputBoolean";
import InputBoolean from "components/Inputs/Base/InputBoolean";
import { SpeedDial } from "components/SpeedDial";
import { SequenceNodeElementProps } from "./types";
import { useSequenceNodeColor } from "./util";
@@ -104,6 +104,9 @@ export const createUpdater = (
}),
trigger: createBasicUpdater("trigger", {
platform: "device",
domain: "",
type: "",
device_id: "",
})({
trigger: args.trigger,
openModal: args.openModal,
+5 -5
View File
@@ -1,11 +1,11 @@
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";
} from "components/Inputs/AutoComplete/InputAutoComplete";
import { InputDevice } from "components/Inputs/AutoComplete/InputDevice";
import { InputDeviceCapabilties } from "components/Inputs/AutoComplete/InputDeviceCapabilties";
import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { cleanUpUndefined } from "utils/helpers";
import { DeviceBaseType, DeviceTypeCapability } from "haService/types";
import { AutomationDeviceState } from "types/automations/common";
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more