Compare commits

..
55 Commits
Author SHA1 Message Date
ari 67f5358f45 $ 2022-07-21 09:55:01 -04:00
ari c40e441f33 t2 2022-07-21 09:53:27 -04:00
ari a3ee13e8e3 rename test 2022-07-21 09:50:41 -04:00
ari a3fa409eda pre 2022-07-21 09:49:49 -04:00
ari 7ac7d60468 testing releases 2022-07-21 09:49:16 -04:00
dependabot[bot] cb34db3c86 Bump terser from 4.8.0 to 4.8.1 in /webapp (#80)
Bumps [terser](https://github.com/terser/terser) from 4.8.0 to 4.8.1.
- [Release notes](https://github.com/terser/terser/releases)
- [Changelog](https://github.com/terser/terser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/terser/terser/commits)

---
updated-dependencies:
- dependency-name: terser
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-21 09:37:44 -04:00
ari ea8697137a fixed pytests 2022-07-21 09:37:23 -04:00
Ari Sosnovsky e9246a5b6c Update TriggerTime.tsx 2022-07-20 22:45:18 -04:00
Ari Sosnovsky d121082d4f Update triggers.ts 2022-07-20 22:44:10 -04:00
Ari Sosnovsky 2605978b43 Update editorRender.tsx 2022-07-20 22:43:18 -04:00
Ari Sosnovsky f5b21be26d Update README.md 2022-07-20 22:19:27 -04:00
ari 582859b35b added weekday and refactored condition time 2022-07-20 22:13:46 -04:00
ari 184734ee70 abstracted away input time entity 2022-07-20 22:13:46 -04:00
ari 3a44057a40 cleaned up time trigger 2022-07-20 22:13:46 -04:00
Ari Sosnovsky ef02abe0cb Update README.md 2022-07-19 21:59:37 -04:00
ari 1d52993253 cleaned up unused 2022-07-19 21:47:36 -04:00
ari 50031c4868 area id incorrect errror 2022-07-19 21:22:49 -04:00
ari b3dae6fea7 fixed area id incorrect error 2022-07-19 21:22:43 -04:00
ari fd35938fcb fixed state 2022-07-19 21:13:19 -04:00
ari 649ee0f31e fixed zones 2022-07-19 20:59:11 -04:00
ari e7110dc97b new conditions open up in edit mode 2022-07-19 20:44:37 -04:00
ari dcf577f84c cleaned up choose + distance between nodes 2022-07-19 20:27:02 -04:00
ari fabb5612d5 ground work for minimal tag update 2022-07-18 16:12:48 -04:00
ari 2958fa49f8 action fix 2022-07-18 14:29:33 -04:00
ari 211f5d8be7 updated actions + v0.3.2 2022-07-18 14:28:46 -04:00
ari 3dac905fda cleaner job 2022-07-18 13:50:50 -04:00
ari 75d70b1133 using slim 2022-07-18 13:47:59 -04:00
ari 47b0c89589 correct run.sh 2022-07-18 13:47:37 -04:00
ari 212349b4c0 nomo rust 2022-07-18 13:30:56 -04:00
ari a4789cf43e buster 2022-07-18 13:30:45 -04:00
ari 395a9d955e swiching to hypercorn 2022-07-18 13:30:33 -04:00
ari 937a3f97c4 switching to hypercorn 2022-07-18 13:30:24 -04:00
ari 6bb18563b4 using buster image 2022-07-18 12:58:57 -04:00
ari 2a9ba678d3 only run tests when api or webapp changes 2022-07-18 12:50:13 -04:00
ari 38e362a469 passing -y to rustup 2022-07-18 12:48:42 -04:00
ari b56b5fc184 added rust install 2022-07-18 12:41:32 -04:00
ari 1cce2d20f4 not publishing armhf 2022-07-18 11:58:26 -04:00
ari 717fada35e removed build from ignore 2022-07-18 10:46:30 -04:00
ari ca4be32d63 fixing docker image 2022-07-18 10:40:15 -04:00
ari ad4c1f66f2 fix commit build 2022-07-18 10:34:19 -04:00
ari 4af6b1688a using build stage 2022-07-18 10:07:03 -04:00
ari 045ce75362 added symlink 2022-07-17 20:56:26 -04:00
ari 442a49da8b fixed trigger validator 2022-07-17 20:47:45 -04:00
ari 8e859ff191 using n for docker node versions 2022-07-17 20:46:28 -04:00
ari 3b1b88b404 using buster image 2022-07-17 19:58:54 -04:00
ari 8306686e4c removed standard 2022-07-16 10:04:29 -04:00
ari 6d67dd129c upgrading alpine 2022-07-16 00:39:32 -04:00
ari 5086ecd993 imporoved build failures 2022-07-16 00:29:34 -04:00
ari bbb87ebf9e support for if/else 2022-07-15 23:41:14 -04:00
ari a1ca9d62b7 opening modal when adding new parallel node 2022-07-15 23:15:23 -04:00
ari 0e4e4783fa Moved infobox to modal 2022-07-15 22:53:51 -04:00
ari 1719148c58 editable title 2022-07-15 21:21:15 -04:00
ari 2ea96973ad top bar 2022-07-15 18:35:25 -04:00
ari a35e8e127f v0.3.1 2022-07-15 13:42:35 -04:00
renovate[bot] 46a67b1395 Update dependency @types/react to v18.0.15 (#75)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-07-15 13:26:40 -04:00
103 changed files with 2217 additions and 1091 deletions

No files matched your search

-1
View File
@@ -1,5 +1,4 @@
webapp/node_modules webapp/node_modules
webapp/build
webapp/.storybook webapp/.storybook
webapp/.vscode webapp/.vscode
webapp/.env.local webapp/.env.local
+77 -7
View File
@@ -1,18 +1,53 @@
name: "Manual Build" name: Build
on: on:
workflow_dispatch: workflow_dispatch:
inputs: inputs:
version: version:
type: string type: string
description: "Version Number" description: "Version Number"
required: true push:
branch: [main]
jobs: jobs:
build: metadata:
runs-on: ubuntu-latest runs-on: ubuntu-latest
name: "${{ github.event.inputs.version }} / ${{ matrix.arch }}" name: Metadata
outputs:
version: ${{ steps.version.outputs.VERSION }}
steps:
- name: Check out repository
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Get Version
id: version
shell: bash
run: |
if [ -z "${INPUT_VERSION}" ]; then
echo ::set-output name=VERSION::$(git describe --tags | sed 's/\([^-]*-g\)/r\1/;s/-/./g')
else
echo ::set-output name=VERSION::${INPUT_VERSION}
fi
env:
INPUT_VERSION: ${{ github.event.inputs.version }}
- name: ${{ steps.version.outputs.VERSION }}
shell: bash
run: |
echo ${{ steps.version.outputs.VERSION }}
deploy:
runs-on: ubuntu-latest
name: Build & Publish ${{ matrix.arch }} / ${{ needs.metadata.outputs.version }}
if: github.event_name != 'pull_request'
needs:
- metadata
strategy: strategy:
matrix: matrix:
arch: ["aarch64", "amd64", "armhf", "armv7", "i386"] arch:
- "aarch64"
- "amd64"
- "armhf"
- "armv7"
- "i386"
steps: steps:
- name: Cancel Previous Runs - name: Cancel Previous Runs
@@ -24,16 +59,51 @@ jobs:
- name: Check out repository - name: Check out repository
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Setup node
uses: actions/setup-node@v3
with:
node-version: 16
cache: "yarn"
cache-dependency-path: webapp/yarn.lock
- name: Login to DockerHub - name: Login to DockerHub
uses: docker/login-action@v2.0.0 uses: docker/login-action@v2.0.0
with: with:
username: ${{ secrets.DOCKERHUB_USERNAME }} username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }} password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build & Push to Dockerhub - name: "Save version number"
run: echo "REACT_APP_BUILD_VERSION=${{ needs.metadata.outputs.version }}" > ./webapp/.env.production
- name: "Build Web"
run: cd webapp && yarn install && yarn build
- name: ${{ matrix.arch }} / ${{ needs.metadata.outputs.version }}
uses: home-assistant/builder@2022.07.0 uses: home-assistant/builder@2022.07.0
with: with:
args: | args: |
--${{ matrix.arch }} \ --${{ matrix.arch }} \
--version ${{ github.event.inputs.version }} \ --no-latest \
--version ${{ needs.metadata.outputs.version }} \
--target . --target .
publish:
runs-on: ubuntu-latest
if: "${{ github.event.inputs.version != '' }}"
needs:
- metadata
- deploy
name: Publish Github Release
steps:
- name: Publish Release ${{ needs.metadata.outputs.version }}
uses: actions/github-script@v6
env:
VERSION: ${{ needs.metadata.outputs.version }}
CHANGELOG: ${{ needs.metadata.outputs.changlelog }}
with:
script: |
github.rest.repos.createRelease({
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: process.env.VERSION,
});
-76
View File
@@ -1,76 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ main ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
schedule:
- cron: '29 23 * * 0'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript', 'python' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.10.0
with:
all_but_latest: true
access_token: ${{ github.token }}
- name: Checkout repository
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
-46
View File
@@ -1,46 +0,0 @@
name: Deploy
on:
workflow_dispatch:
push:
branch: [main]
paths:
- "config.yaml"
jobs:
metadata:
runs-on: ubuntu-latest
name: Metadata
outputs:
version: ${{ steps.version.outputs.VERSION }}
changlelog: ${{ steps.changlelog.outputs.CHANGELOG }}
steps:
- name: Check out repository
uses: actions/checkout@v3
- name: Get Version
id: version
shell: bash
run: |
echo ::set-output name=VERSION::$(cat config.yaml | sed -nr 's/version: (.*)/\1/p')
- name: Get Changelog
id: changlelog
shell: bash
run: |
echo ::set-output name=CHANGELOG::$(cat CHANGELOG.md)
publish:
runs-on: ubuntu-latest
needs:
- metadata
name: Publish Github Release
steps:
- name: Publish Release ${{ needs.metadata.outputs.version }}
uses: actions/github-script@v6
env:
VERSION: ${{ needs.metadata.outputs.version }}
CHANGELOG: ${{ needs.metadata.outputs.changlelog }}
with:
script: |
github.rest.repos.createRelease({
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: process.env.VERSION,
});
+44
View File
@@ -0,0 +1,44 @@
name: Test Release
on:
workflow_dispatch:
inputs:
version:
type: string
description: "Version Number"
jobs:
release:
runs-on: ubuntu-latest
name: Publish Github Release
permissions:
contents: write
steps:
- name: "${{ github.event.inputs.version }}"
uses: actions/github-script@v6
env:
VERSION: "${{ github.event.inputs.version }}"
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
github.rest.repos.createRelease({
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: process.env.VERSION,
});
pre:
runs-on: ubuntu-latest
name: Publish Github PreRelease
permissions:
contents: write
steps:
- name: "${{ github.event.inputs.version }}"
uses: actions/github-script@v6
env:
VERSION: pre-${{ github.event.inputs.version }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
github.rest.repos.createRelease({
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: process.env.VERSION,
});
+6 -40
View File
@@ -1,10 +1,13 @@
name: Tests name: Commit Tests
on: on:
push: push:
branch: branch:
- main - main
paths:
- "webapp"
- "api"
pull_request: pull_request:
branch: branch:
- main - main
jobs: jobs:
metadata: metadata:
@@ -72,40 +75,3 @@ jobs:
run: cd webapp && yarn install run: cd webapp && yarn install
- name: ${{ needs.metadata.outputs.version }} / ${{ matrix.action }} - name: ${{ needs.metadata.outputs.version }} / ${{ matrix.action }}
run: cd webapp && yarn ${{ matrix.action }} run: cd webapp && yarn ${{ matrix.action }}
deploy:
runs-on: ubuntu-latest
name: Build & Publish ${{ matrix.arch }}
if: github.event_name != 'pull_request'
needs:
- metadata
- nodejs
- python
strategy:
matrix:
arch: ["aarch64", "amd64", "armhf", "armv7", "i386"]
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.10.0
with:
all_but_latest: true
access_token: ${{ github.token }}
- name: Check out repository
uses: actions/checkout@v3
- name: Login to DockerHub
uses: docker/login-action@v2.0.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build & Push to Dockerhub - ${{ matrix.arch }} / ${{ needs.metadata.outputs.version }}
uses: home-assistant/builder@2022.07.0
with:
args: |
--${{ matrix.arch }} \
--no-latest \
--version ${{ needs.metadata.outputs.version }} \
--target .
+1
View File
@@ -1 +1,2 @@
.vscode/*.log .vscode/*.log
webapp/src/types/validators/index.test.ts
+16 -3
View File
@@ -1,10 +1,24 @@
# Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge) # Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge)
## [0.3.2] - Fixed Addon Image for arm-based devices
- Using hypercon instead of uvicorn (this losses the rust dependency which makes it easier to install on arm)
- Pre-building web assets outside of docker (this takes the image size down and speeds up instaltion of addon)
- Updated build scripts to actually fail installation when build/prep steps fail
- Ensured that builds for all architecture run successfully
- Re-worked github actions (quicker test phases)
## [0.3.1] - Increased Pagination + Restricted Repeat Node
- Increased pagination to display up to 10,000 autos for now
- Repeat node now has types
## [0.3.0] - Complete Refactor of Graphs ## [0.3.0] - Complete Refactor of Graphs
- Added visual support for - Added visual support for
* Repeat Nodes
* Parallel Nodes - Repeat Nodes
- Parallel Nodes
- Using collections for conditions & triggers - Using collections for conditions & triggers
- Fixed several bugs with improper alerts - Fixed several bugs with improper alerts
@@ -17,7 +31,6 @@
![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png) ![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png)
## [0.1.22] - Many Visual improvements ## [0.1.22] - Many Visual improvements
- Deprecated several custom components in favor of mui.com - Deprecated several custom components in favor of mui.com
+7 -14
View File
@@ -1,8 +1,8 @@
# <--- Pre-Build Args --> # <--- Pre-Build Args -->
ARG BUILD_ARCH ARG BUILD_ARCH
# <--- Image Setup --> # <--- Main Image -->
FROM homeassistant/${BUILD_ARCH}-base-python:3.9-alpine3.14 FROM python:3.9.13-slim-buster
WORKDIR /app WORKDIR /app
# <--- Post-Build Args --> # <--- Post-Build Args -->
@@ -13,11 +13,8 @@ ENV BUILD_VERSION $BUILD_VERSION
# <--- System Wide Dependencies --> # <--- System Wide Dependencies -->
ENV LANG C.UTF-8 ENV LANG C.UTF-8
RUN apk add --no-cache \ RUN apt-get update -y && \
nodejs \ apt-get install -y gcc git build-essential libtool automake curl
npm \
build-base \
python3-dev
# <--- Scripts --> # <--- Scripts -->
COPY docker/bin /app/bin COPY docker/bin /app/bin
@@ -28,16 +25,12 @@ RUN /app/bin/prep.sh
# <--- Python Dependencies --> # <--- Python Dependencies -->
COPY api/setup.py /app/setup.py COPY api/setup.py /app/setup.py
# <--- Webapp Build -->
COPY webapp/ /app/web-builder
RUN cd /app/web-builder && \
echo "REACT_APP_BUILD_VERSION=${BUILD_VERSION}" > /app/web-builder/.env.production
# <--- BUILD --> # <--- BUILD -->
RUN /app/bin/build.sh /app /app/web-builder RUN /app/bin/build.sh /app
# <--- Api Code --> # <--- Api Code -->
COPY api/src /app/src COPY api/src /app/src
COPY webapp/build /app/web
# <--- Ports --> # <--- Ports -->
EXPOSE 8000 EXPOSE 8000
@@ -45,7 +38,7 @@ EXPOSE 8000
# <--- Final --> # <--- Final -->
LABEL \ LABEL \
io.hass.type="addon" \ io.hass.type="addon" \
io.hass.arch="armhf|aarch64|i386|amd64" io.hass.arch="armhf|aarch64|i386|amd64|armv7"
ENTRYPOINT [ "/app/bin/run.sh" ] ENTRYPOINT [ "/app/bin/run.sh" ]
CMD [ "/app" ] CMD [ "/app" ]
+2
View File
@@ -15,9 +15,11 @@ build-with-builder:
-t /data -t /data
build: build:
cd webapp && yarn build
$(DC) build $(DC) build
build-no-cache: build-no-cache:
cd webapp && yarn buil
$(DC) build --no-cache $(DC) build --no-cache
push: push:
+3 -3
View File
@@ -1,7 +1,7 @@
# Shortumation ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=platsic) # 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) [![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)
![GitHub Workflow Status](https://img.shields.io/github/workflow/status/asosnovsky/Shortumation/Manual%20Build)
| | Stable | Edge | | Stable | Edge
| --- | --- | --- | --- | --- | ---
| 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) | 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)
@@ -73,7 +73,7 @@ If this warning does not scare you or you still want to try things out, then tak
**How is this different from Node-Red?** **How is this different from Node-Red?**
> Node-Red is both an execution engine and an automation editor, which means that in order for you automations to run you have to have an additional component running and executing the automations. Shortumation simply provides a different editor and manager for writing Homeassistant automations, while relying on Homeassistant to execute the automations (this uses the `automations.yaml` file as the backend database) > Node-Red is both an execution engine and an automation editor, which means that in order for your automations to run you have to have an additional component running and executing the automations. Shortumation simply provides a different editor and manager for writing Homeassistant automations, while relying on Homeassistant to execute the automations (this uses the `automations.yaml` file as the backend database)
**Which HA Installation does this support?** **Which HA Installation does this support?**
+1 -1
View File
@@ -43,4 +43,4 @@ clean:
run-local: run-local:
rm -f web rm -f web
ln -s ../webapp/build web ln -s ../webapp/build web
USE_EXAMPLE_REPO=1 $(VENV_BIN)/uvicorn src.app:app --reload USE_EXAMPLE_REPO=1 $(VENV_BIN)/hypercorn src.app:app --reload
+2 -1
View File
@@ -7,8 +7,9 @@ setuptools.setup(
"PyYAML==6.0", "PyYAML==6.0",
"fastapi==0.78.0", "fastapi==0.78.0",
"pydantic==1.9.1", "pydantic==1.9.1",
"uvicorn[standard]==0.18.2", "hypercorn==0.13.2",
"python-decouple==3.6", "python-decouple==3.6",
"websockets==10.3"
], ],
extras_require={ extras_require={
"dev": [ "dev": [
+5
View File
@@ -5,6 +5,7 @@ from src.api.types import (
ListData, ListData,
ListParams, ListParams,
UpdateAutoRequest, UpdateAutoRequest,
UpdateTags,
) )
from src.automations.errors import FailedDeletion from src.automations.errors import FailedDeletion
from src.automations.manager import AutomationManager from src.automations.manager import AutomationManager
@@ -29,6 +30,10 @@ def make_automation_router(automations: AutomationManager) -> APIRouter:
def upsert_auto(body: UpdateAutoRequest): def upsert_auto(body: UpdateAutoRequest):
automations.update(body.index, body.data) automations.update(body.index, body.data)
@router.post("/item/tags")
def update_tags(body: UpdateTags):
automations.update_tags(body.automation_id, body.tags)
@router.delete("/item") @router.delete("/item")
def delete_auto(body: DeleteAutoRequest): def delete_auto(body: DeleteAutoRequest):
try: try:
+6 -1
View File
@@ -1,4 +1,4 @@
from typing import Generic, List, TypeVar from typing import Dict, Generic, List, TypeVar
from pydantic import BaseModel from pydantic import BaseModel
from pydantic.fields import Field from pydantic.fields import Field
@@ -25,5 +25,10 @@ class UpdateAutoRequest(BaseModel):
data: ExtenededAutomationData data: ExtenededAutomationData
class UpdateTags(BaseModel):
automation_id: str = Field(description="Automation Id to update")
tags: Dict[str, str]
class DeleteAutoRequest(BaseModel): class DeleteAutoRequest(BaseModel):
index: int = Field(description="Index of the automation to update") index: int = Field(description="Index of the automation to update")
+7 -2
View File
@@ -1,4 +1,4 @@
from typing import Iterator, List, Optional from typing import Dict, Iterator, List, Optional
from src.automations.errors import FailedDeletion, InvalidAutomationFile from src.automations.errors import FailedDeletion, InvalidAutomationFile
from src.automations.types import AutomationData, ExtenededAutomationData from src.automations.types import AutomationData, ExtenededAutomationData
@@ -24,7 +24,7 @@ class AutomationManager:
break break
yield from load_automation(auto, tags.get(auto.get("id", ""), {})) yield from load_automation(auto, tags.get(auto.get("id", ""), {}))
def get(self, index: int) -> Optional[AutomationData]: def get(self, index: int) -> Optional[ExtenededAutomationData]:
tags = self.hass_config.automation_tags tags = self.hass_config.automation_tags
if index >= 0: if index >= 0:
for i, auto in enumerate(self.hass_config.automations): for i, auto in enumerate(self.hass_config.automations):
@@ -51,6 +51,11 @@ class AutomationManager:
self.hass_config.save_automations(automations) self.hass_config.save_automations(automations)
self.hass_config.save_tags(tags) self.hass_config.save_tags(tags)
def update_tags(self, auto_id: str, tags: Dict[str, str]):
autos_tags = self.hass_config.automation_tags
autos_tags[auto_id] = tags
self.hass_config.save_tags(autos_tags)
def delete(self, index: int): def delete(self, index: int):
automations: List[dict] = [] automations: List[dict] = []
deleted = False deleted = False
+4 -1
View File
@@ -10,7 +10,10 @@ def find_hass_config() -> HassConfig:
"""Try to find HASS config.""" """Try to find HASS config."""
if config("USE_EXAMPLE_REPO", False, cast=bool): if config("USE_EXAMPLE_REPO", False, cast=bool):
print("using USE_EXAMPLE_REPO") print("using USE_EXAMPLE_REPO")
from tests.utils import create_copy_of_example_config, HA_CONFIG3_EXAMPLE from tests.utils import (
HA_CONFIG3_EXAMPLE,
create_copy_of_example_config,
)
path = create_copy_of_example_config(HA_CONFIG3_EXAMPLE) path = create_copy_of_example_config(HA_CONFIG3_EXAMPLE)
print("|-> ", path) print("|-> ", path)
@@ -100,3 +100,16 @@ class manager_tests(TestCase):
self.assertEqual(manager.get_total_items(), 3) self.assertEqual(manager.get_total_items(), 3)
with self.assertRaises(FailedDeletion): with self.assertRaises(FailedDeletion):
manager.delete(10) manager.delete(10)
def test_save_tags(self):
_, _, manager = get_dummy_automation_loader(
[
ExtenededAutomationData(metadata=AutomationMetdata(id="test1")),
ExtenededAutomationData(metadata=AutomationMetdata(id="test2")),
ExtenededAutomationData(metadata=AutomationMetdata(id="test3")),
],
automation_in_conifguration_mode="none",
)
manager.update_tags("test1", {"room": "bathroom"})
auto = manager.get(0)
assert auto.tags == {"room": "bathroom"}
+1 -1
View File
@@ -1,5 +1,5 @@
name: Shortumation name: Shortumation
version: v0.3.0 version: v0.3.2
slug: shortumation slug: shortumation
image: asosnovsky/shortumation-{arch} image: asosnovsky/shortumation-{arch}
url: "https://github.com/asosnovsky/Shortumation" url: "https://github.com/asosnovsky/Shortumation"
+4 -8
View File
@@ -2,7 +2,7 @@
set -e set -e
api_location=${1} api_location=${1}
web_location=${2} # web_location=${2}
function install_yarn() { function install_yarn() {
pushd $web_location pushd $web_location
@@ -18,11 +18,7 @@ function install_py() {
popd popd
} }
declare -i err=0 werr=0 install_py
install_py & # install_yarn
install_yarn &
while wait -fn || werr=$?; ((werr != 127)); do
err=$werr
done
echo "DONE BUILD" echo "DONE BUILD"
+7 -8
View File
@@ -2,18 +2,17 @@
set -e set -e
function prep_yarn() { function prep_yarn() {
curl -L https://raw.githubusercontent.com/tj/n/master/bin/n -o n
ln -s /usr/bin/nodejs /usr/bin/node
bash n lts
npm i -g yarn npm i -g yarn
} }
function prep_py() { function prep_py() {
pip install -U wheel setuptools pip pip install -U wheel setuptools pip Cython
} }
declare -i err=0 werr=0 prep_py
prep_py & # prep_yarn
prep_yarn &
while wait -fn || werr=$?; ((werr != 127)); do
err=$werr
done
echo "DONE PREP" echo "DONE PREP"
+1 -1
View File
@@ -7,4 +7,4 @@ echo "--------------------"
echo "BUILD_VERSION = "$BUILD_VERSION echo "BUILD_VERSION = "$BUILD_VERSION
echo $(python --version) echo $(python --version)
echo "--------------------" echo "--------------------"
python -m uvicorn src.app:app --host "0.0.0.0" --port 8000 python -m hypercorn src.app:app -b "0.0.0.0:8000"
+1 -1
View File
@@ -11,7 +11,7 @@
"@mui/styles": "5.8.6", "@mui/styles": "5.8.6",
"@types/jest": "28.1.5", "@types/jest": "28.1.5",
"@types/node": "17.0.36", "@types/node": "17.0.36",
"@types/react": "18.0.14", "@types/react": "18.0.15",
"@types/react-dom": "18.0.6", "@types/react-dom": "18.0.6",
"@types/ws": "8.5.3", "@types/ws": "8.5.3",
"@uiw/react-codemirror": "4.10.4", "@uiw/react-codemirror": "4.10.4",
+29 -11
View File
@@ -1,27 +1,46 @@
import { AutomationData } from "types/automations"; import { AutomationData } from "types/automations";
import { API } from "./base"; import { API } from "./base";
import { ListData, ListParams } from "./types"; import { ListData, ListParams } from "./types";
import { AUTOMTAION_LIST, AUTOMTAION_ITEM } from './paths'; import {
AUTOMTAION_LIST,
AUTOMTAION_ITEM,
AUTOMTAION_ITEM_TAGS,
} from "./paths";
export const makeAutomationAPI = (api: API) => ({ export const makeAutomationAPI = (api: API) => ({
async list({ offset, limit }: ListParams) { async list({ offset, limit }: ListParams) {
const data = await api.makeCall<ListData<AutomationData>, ListParams>({ const data = await api.makeCall<ListData<AutomationData>, ListParams>({
path: AUTOMTAION_LIST, path: AUTOMTAION_LIST,
data: { data: {
offset, limit, offset,
} limit,
},
}); });
return data; return data;
}, },
async update({ index, auto }: { index: number, auto: AutomationData }) { async update({ index, auto }: { index: number; auto: AutomationData }) {
return await api.makeCall({ return await api.makeCall({
path: AUTOMTAION_ITEM, path: AUTOMTAION_ITEM,
data: { data: {
index, index,
data: auto data: auto,
}, },
}) });
},
async updateTags({
automation_id,
tags,
}: {
automation_id: string;
tags: Record<string, string>;
}) {
return await api.makeCall({
path: AUTOMTAION_ITEM_TAGS,
data: {
automation_id,
tags,
},
});
}, },
async remove({ index }: { index: number }) { async remove({ index }: { index: number }) {
return await api.makeCall({ return await api.makeCall({
@@ -29,10 +48,9 @@ export const makeAutomationAPI = (api: API) => ({
path: AUTOMTAION_ITEM, path: AUTOMTAION_ITEM,
data: { data: {
index, index,
} },
}) });
} },
}); });
export type AutomationAPI = ReturnType<typeof makeAutomationAPI>; export type AutomationAPI = ReturnType<typeof makeAutomationAPI>;
+12 -10
View File
@@ -1,15 +1,16 @@
import { useEffect } from 'react'; import { useEffect } from "react";
import { useDefaultApiState, makeReloadAutomations } from './util'; import { useDefaultApiState, makeReloadAutomations } from "./util";
import { AutomationAPI } from './automations'; import { AutomationAPI } from "./automations";
export type ApiService = ReturnType<typeof useAPIService>; export type ApiService = ReturnType<typeof useAPIService>;
export const useAPIService = ( export const useAPIService = (automationAPI: AutomationAPI) => {
automationAPI: AutomationAPI
) => {
// state // state
const [state, setState] = useDefaultApiState(); const [state, setState] = useDefaultApiState();
const { reload, wrapCall } = makeReloadAutomations(automationAPI, state, setState); const { reload, wrapCall } = makeReloadAutomations(
automationAPI,
state,
setState
);
// initial load of autos // initial load of autos
useEffect(() => { useEffect(() => {
@@ -21,5 +22,6 @@ export const useAPIService = (
state, state,
removeAutomation: wrapCall(automationAPI.remove), removeAutomation: wrapCall(automationAPI.remove),
updateAutomation: wrapCall(automationAPI.update), updateAutomation: wrapCall(automationAPI.update),
} updateTags: wrapCall(automationAPI.updateTags),
} };
};
+64 -28
View File
@@ -1,57 +1,93 @@
import { useMockAPI } from "./mock" import { useMockAPI } from "./mock";
import { makeAutomationAPI } from "./automations"; import { makeAutomationAPI } from "./automations";
import { createMockAuto } from '../utils/mocks'; import { createMockAuto } from "../utils/mocks";
import { AutomationData } from "types/automations";
const fakeUseRef = (a: any) => ({ current: a }); const fakeUseRef = (a: any) => ({ current: a });
test('mock api uses initial autos for initial population -- empty', async () => { test("mock api uses initial autos for initial population -- empty", async () => {
const mockApi = makeAutomationAPI(useMockAPI([], fakeUseRef as any)); const mockApi = makeAutomationAPI(useMockAPI([], fakeUseRef as any));
const data = await mockApi.list({ limit: 10, offset: 0 }); const data = await mockApi.list({ limit: 10, offset: 0 });
expect(data.ok).toBe(true); expect(data.ok).toBe(true);
expect((data as any).data.data).toHaveLength(0); expect((data as any).data.data).toHaveLength(0);
expect((data as any).data.totalItems).toBe(0); expect((data as any).data.totalItems).toBe(0);
}) });
test('mock api uses initial autos for initial population -- some data', async () => { test("mock api uses initial autos for initial population -- some data", async () => {
const initials = [ const initials = [createMockAuto(), createMockAuto()];
createMockAuto(),
createMockAuto()
];
const mockApi = makeAutomationAPI(useMockAPI(initials, fakeUseRef as any)); const mockApi = makeAutomationAPI(useMockAPI(initials, fakeUseRef as any));
const data = await mockApi.list({ limit: 10, offset: 0 }); const data = await mockApi.list({ limit: 10, offset: 0 });
expect(data.ok).toBe(true); expect(data.ok).toBe(true);
expect((data as any).data.data).toHaveLength(2); expect((data as any).data.data).toHaveLength(2);
expect((data as any).data.totalItems).toBe(2); expect((data as any).data.totalItems).toBe(2);
}) });
test('populate mock api with some data', async () => { test("populate mock api with some data", async () => {
const mockApi = makeAutomationAPI(useMockAPI([], fakeUseRef as any)); const mockApi = makeAutomationAPI(useMockAPI([], fakeUseRef as any));
await mockApi.update({index: 0, auto: createMockAuto()}) await mockApi.update({ index: 0, auto: createMockAuto() });
let data = await mockApi.list({ limit: 10, offset: 0 }); let data = await mockApi.list({ limit: 10, offset: 0 });
expect(data.ok).toBe(true); expect(data.ok).toBe(true);
expect((data as any).data.data).toHaveLength(1); expect((data as any).data.data).toHaveLength(1);
expect((data as any).data.totalItems).toBe(1); expect((data as any).data.totalItems).toBe(1);
await mockApi.update({index: 1, auto: createMockAuto()}) await mockApi.update({ index: 1, auto: createMockAuto() });
data = await mockApi.list({ limit: 10, offset: 0 }); data = await mockApi.list({ limit: 10, offset: 0 });
expect((data as any).data.data).toHaveLength(2); expect((data as any).data.data).toHaveLength(2);
expect((data as any).data.totalItems).toBe(2); expect((data as any).data.totalItems).toBe(2);
}) });
test('delete/update data from mock api', async () => { test("delete/update data from mock api", async () => {
const mockApi = makeAutomationAPI(useMockAPI([ const mockApi = makeAutomationAPI(
createMockAuto(), useMockAPI(
createMockAuto(), [
createMockAuto(), createMockAuto(),
createMockAuto(), createMockAuto(),
createMockAuto(), createMockAuto(),
], fakeUseRef as any)); createMockAuto(),
let data = (await mockApi.list({ limit: 10, offset: 0 }) as any).data.data; createMockAuto(),
],
fakeUseRef as any
)
);
let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data;
const toBeEdited = data[0]; const toBeEdited = data[0];
toBeEdited.metadata.alias = "Bob is my uncle"; toBeEdited.metadata.alias = "Bob is my uncle";
await mockApi.update({index: 0, auto: toBeEdited}) await mockApi.update({ index: 0, auto: toBeEdited });
data = (await mockApi.list({ limit: 10, offset: 0 }) as any).data.data; data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data;
expect(data[0].metadata.alias).toEqual("Bob is my uncle"); expect(data[0].metadata.alias).toEqual("Bob is my uncle");
await mockApi.remove({index: 0}) await mockApi.remove({ index: 0 });
data = (await mockApi.list({ limit: 10, offset: 0 }) as any).data.data; data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data.data;
expect(data[0].metadata.alias === "Bob is my uncle").toEqual(false); expect(data[0].metadata.alias === "Bob is my uncle").toEqual(false);
}) });
test("update tags from mock api", async () => {
const mockApi = makeAutomationAPI(
useMockAPI(
[
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
createMockAuto(),
],
fakeUseRef as any
)
);
let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data
.data as AutomationData[];
const autoId = data[0].metadata.id;
expect(data[0].tags).toStrictEqual({});
mockApi.updateTags({
automation_id: autoId,
tags: {
room: "bathroom",
type: "popup",
},
});
data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data
.data as AutomationData[];
expect(data[0].metadata.id).toEqual(autoId);
expect(data[0].tags).toStrictEqual({
room: "bathroom",
type: "popup",
});
});
+44 -27
View File
@@ -1,33 +1,34 @@
import { useRef } from 'react'; import { useRef } from "react";
import { AutomationData } from 'types/automations'; import { AutomationData } from "types/automations";
import { API } from './base'; import { API } from "./base";
import { AUTOMTAION_LIST, AUTOMTAION_ITEM } from './paths'; import {
AUTOMTAION_LIST,
AUTOMTAION_ITEM,
AUTOMTAION_ITEM_TAGS,
} from "./paths";
export const useMockAPI = ( export const useMockAPI = (
initialAutos: AutomationData[] = [], initialAutos: AutomationData[] = [],
makeRef = useRef, makeRef = useRef
): API => { ): API => {
const automationsRef = makeRef(initialAutos); const automationsRef = makeRef(initialAutos);
return { return {
async makeCall({ async makeCall({ path, method = "POST", data = {} }) {
path,
method = "POST",
data = {}
}) {
// console.debug("[[mockCall]]", method, path, data); // console.debug("[[mockCall]]", method, path, data);
if (path === AUTOMTAION_LIST) { if (path === AUTOMTAION_LIST) {
return { return {
ok: true, ok: true,
data: JSON.parse(JSON.stringify({ data: JSON.parse(
totalItems: automationsRef.current.length, JSON.stringify({
params: { offset: 0, limit: 100 }, totalItems: automationsRef.current.length,
data: automationsRef.current, params: { offset: 0, limit: 100 },
})) data: automationsRef.current,
} as any })
),
} as any;
} }
if (path === AUTOMTAION_ITEM) { if (path === AUTOMTAION_ITEM) {
if (method === 'POST') { if (method === "POST") {
const { index, data: auto } = data as any; const { index, data: auto } = data as any;
if (index >= automationsRef.current.length) { if (index >= automationsRef.current.length) {
automationsRef.current = [...automationsRef.current, auto]; automationsRef.current = [...automationsRef.current, auto];
@@ -35,29 +36,45 @@ export const useMockAPI = (
automationsRef.current = [ automationsRef.current = [
...automationsRef.current.slice(0, index), ...automationsRef.current.slice(0, index),
auto, auto,
...automationsRef.current.slice(index + 1) ...automationsRef.current.slice(index + 1),
]; ];
} }
return { return {
ok: true, ok: true,
data: {} data: {},
} };
} else if (method === "DELETE") { } else if (method === "DELETE") {
const { index } = data as any; const { index } = data as any;
automationsRef.current = [ automationsRef.current = [
...automationsRef.current.slice(0, index), ...automationsRef.current.slice(0, index),
...automationsRef.current.slice(index + 1) ...automationsRef.current.slice(index + 1),
]; ];
return { return {
ok: true, ok: true,
data: {} data: {},
};
}
}
if (path === AUTOMTAION_ITEM_TAGS) {
if (method === "POST") {
const { automation_id, tags } = data as any;
for (let i = 0; i < automationsRef.current.length; i++) {
const auto = automationsRef.current[i];
if (auto.metadata.id === automation_id) {
automationsRef.current[i].tags = JSON.parse(JSON.stringify(tags));
break;
}
} }
return {
ok: true,
data: {},
};
} }
} }
return { return {
ok: false, ok: false,
error: "PATH NOT FOUND " + method + ": " + path, error: "PATH NOT FOUND " + method + ": " + path,
} };
} },
} };
} };
+2 -3
View File
@@ -1,5 +1,4 @@
export const AUTOMTAION_ROOT = "/" as const;
export const AUTOMTAION_ROOT = '/' as const;
export const AUTOMTAION_LIST = `${AUTOMTAION_ROOT}list` as const; export const AUTOMTAION_LIST = `${AUTOMTAION_ROOT}list` as const;
export const AUTOMTAION_ITEM = `${AUTOMTAION_ROOT}item` as const; export const AUTOMTAION_ITEM = `${AUTOMTAION_ROOT}item` as const;
export const AUTOMTAION_ITEM_TAGS = `${AUTOMTAION_ITEM}/tags` as const;
@@ -1,31 +1,16 @@
.automation-editor--info-box { .automation-editor--info-box {
height: 100%;
padding-left: 10px;
padding-right: 10px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: flex-start; align-items: center;
overflow: hidden; gap: 0.5em;
position: relative;
} }
.automation-editor--info-box-inner { .automation-editor--info-box-inner {
height: 100%; max-width: 95vw;
max-height: 90vh;
overflow: auto; overflow: auto;
} }
.automation-editor--info-box.show {
min-width: 20em;
}
.automation-editor--info-box.hide {
min-width: 1em;
}
.automation-editor--info-box.hide>.automation-editor--info-box-inner {
display: none;
}
.automation-editor--info-box--tags { .automation-editor--info-box--tags {
padding: 0.25em 0.75em 1em 0.75em; padding: 0.25em 0.75em 1em 0.75em;
border-color: var(--mui-grey-400); border-color: var(--mui-grey-400);
@@ -1,40 +1,35 @@
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { makeTagDB } from "components/AutomationList/TagDB"; import { makeTagDB } from "components/AutomationList/TagDB";
import { Page } from "components/Page"; import { Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import { AutoInfoBox } from "./AutoInfoBox"; import { AutoInfoBox } from "./AutoInfoBox";
import { defaultAutomation } from 'utils/defaults'; import { defaultAutomation } from "utils/defaults";
export default { export default {
title: 'App/AutomationList/Editor/InfoBox', title: "App/AutomationList/Editor/InfoBox",
component: AutoInfoBox, component: AutoInfoBox,
parameters: { actions: { argTypesRegex: '^on.*' } }, parameters: { actions: { argTypesRegex: "^on.*" } },
args: { args: {
tagDB: makeTagDB([ tagDB: makeTagDB([defaultAutomation("test")]),
defaultAutomation("test") },
])
}
} as ComponentMeta<typeof AutoInfoBox>; } as ComponentMeta<typeof AutoInfoBox>;
export const NoTags: ComponentStory<typeof AutoInfoBox> = (args) => {
export const NoTags: ComponentStory<typeof AutoInfoBox> = args => { const [[metadata, tags], setState] = useState([args.metadata, args.tags]);
const [[metadata, tags], setState] = useState([args.metadata, args.tags])
return ( return (
<Page> <Page>
<AutoInfoBox <AutoInfoBox
{...args} {...args}
className=""
metadata={metadata} metadata={metadata}
tags={tags} tags={tags}
onUpdate={(m, t) => { onUpdate={(m, t) => {
args.onUpdate(m, t) args.onUpdate(m, t);
setState([m, t]) setState([m, t]);
}} }}
/> />
</Page> </Page>
) );
} };
NoTags.args = { NoTags.args = {
...NoTags.args, ...NoTags.args,
tags: [], tags: [],
@@ -43,13 +38,13 @@ NoTags.args = {
alias: "Random", alias: "Random",
description: "Example Metadata", description: "Example Metadata",
trigger_variables: { trigger_variables: {
'wowo': '!' wowo: "!",
}, },
mode: 'single', mode: "single",
}, },
} };
export const SomeTags: ComponentStory<typeof AutoInfoBox> = NoTags.bind({}) export const SomeTags: ComponentStory<typeof AutoInfoBox> = NoTags.bind({});
SomeTags.args = { SomeTags.args = {
...SomeTags.args, ...SomeTags.args,
tags: [ tags: [
@@ -61,8 +56,8 @@ SomeTags.args = {
alias: "Bathroom Vent", alias: "Bathroom Vent",
description: "Turn the vent when the humidity is high", description: "Turn the vent when the humidity is high",
trigger_variables: { trigger_variables: {
'wowo': '!' wowo: "!",
}, },
mode: 'single', mode: "single",
}, },
} };
@@ -9,7 +9,6 @@ import { TagDB } from "components/AutomationList/TagDB";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
interface Props { interface Props {
className: string;
metadata: AutomationMetadata; metadata: AutomationMetadata;
tags: Array<[string, string]>; tags: Array<[string, string]>;
onUpdate: (m: AutomationMetadata, tags: Array<[string, string]>) => void; onUpdate: (m: AutomationMetadata, tags: Array<[string, string]>) => void;
@@ -20,7 +19,6 @@ export const AutoInfoBox: FC<Props> = ({
metadata, metadata,
tags, tags,
onUpdate, onUpdate,
className,
children, children,
tagDB, tagDB,
}) => { }) => {
@@ -97,7 +95,7 @@ export const AutoInfoBox: FC<Props> = ({
]); ]);
// render // render
return ( return (
<div className={`automation-editor--info-box ${className}`}> <div className="automation-editor--info-box">
<div className="automation-editor--info-box-inner"> <div className="automation-editor--info-box-inner">
<InputText <InputText
label="ID" label="ID"
@@ -29,13 +29,54 @@
display: flex; display: flex;
flex-direction: row; flex-direction: row;
gap: 0.25em; gap: 0.25em;
justify-content: flex-end; justify-content: space-between;
margin-top: 0.25em; margin-top: 0.25em;
} }
.automation-editor--flow-wrapper.changed>.automation-editor--flow-wrapper--toolbar * { .automation-editor--flow-wrapper--toolbar--title {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
gap: 0.25em;
width: 100%;
}
.automation-editor--flow-wrapper--toolbar--title--text .id {
font-size: 0.75em;
max-width: 15em;
padding: 0;
margin: 0;
white-space: break-word;
overflow: hidden;
text-overflow: ellipsis;
padding-bottom: 0.25em;
}
.automation-editor--flow-wrapper--toolbar .automation-editor--flow-wrapper--toolbar--title--text {
min-width: 5em;
}
.automation-editor--flow-wrapper--toolbar .automation-editor--flow-wrapper--toolbar--modes {
min-width: 6em;
}
.automation-editor--flow-wrapper--toolbar .automation-editor--flow-wrapper--toolbar--modes .MuiSelect-select {
padding-left: 0.25em;
padding-right: 0.25em;
padding-top: 1.15em;
padding-bottom: 0.25em;
}
.automation-editor--flow-wrapper--toolbar .automation-editor--flow-wrapper--toolbar--modes .MuiInputLabel-root {
font-size: 0.9em;
left: -0.5em;
}
.automation-editor.changed .automation-editor--flow-wrapper--toolbar--save-btn,
.automation-editor--info-box--buttons.changed .automation-editor--flow-wrapper--toolbar--save-btn {
border-color: var(--mui-success-light); border-color: var(--mui-success-light);
color: var(--mui-success-light) color: var(--mui-success-light);
} }
@@ -61,21 +102,6 @@
position: relative; position: relative;
} }
.automation-editor .automation-editor--info-box--icon {
position: absolute;
left: 0.25em;
bottom: 0em;
z-index: 10;
max-width: 1.5em;
max-height: 1.5em;
}
.automation-editor--info-box.hide>.automation-editor--info-box--icon {
transform: rotate(180deg);
z-index: 2;
left: 0.1em;
}
.automation-editor.loading .mock-list { .automation-editor.loading .mock-list {
position: absolute; position: absolute;
left: 0; left: 0;
@@ -96,4 +122,9 @@
top: 0; top: 0;
left: 0; left: 0;
width: 100%; width: 100%;
}
.automation-editor--info-box--buttons {
display: flex;
gap: 1em;
} }
@@ -45,7 +45,8 @@ Simple.args = {
Use: "Flushing", Use: "Flushing",
}, },
metadata: { metadata: {
id: "random", id:
"random" + String(Date.now()) + String(Date.now()) + String(Date.now()),
alias: "Random", alias: "Random",
description: "Example Metadata", description: "Example Metadata",
trigger_variables: { trigger_variables: {
+108 -19
View File
@@ -3,8 +3,9 @@ import Icon from "@mui/material/Icon";
import { CheckMarkIcon } from "components/Icons"; import { CheckMarkIcon } from "components/Icons";
import { FC, useState } from "react"; import { FC, useState } from "react";
import { AutomationData } from "types/automations"; import { AutomationData } from "types/automations";
import { Modal } from "components/Modal";
import { AutoInfoBox } from "./AutoInfoBox"; import { AutoInfoBox } from "./AutoInfoBox";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import ModeEditOutlineTwoToneIcon from "@mui/icons-material/ModeEditOutlineTwoTone";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Button";
import { useAutomatioEditorState, EditorData } from "./state"; import { useAutomatioEditorState, EditorData } from "./state";
import { MiniFailure } from "types/validators/helper"; import { MiniFailure } from "types/validators/helper";
@@ -12,10 +13,12 @@ import InputYaml from "components/Inputs/InputYaml";
import { TagDB } from "components/AutomationList/TagDB"; import { TagDB } from "components/AutomationList/TagDB";
import Skeleton from "@mui/material/Skeleton"; import Skeleton from "@mui/material/Skeleton";
import LinearProgress from "@mui/material/LinearProgress"; import LinearProgress from "@mui/material/LinearProgress";
import { ArrowBack } from "@mui/icons-material";
import { useCookies } from "react-cookie"; import { useCookies } from "react-cookie";
import { DAGDims } from "components/DAGGraph/elements/types"; import { DAGDims } from "components/DAGGraph/elements/types";
import { DAGAutomationGraph } from "components/DAGGraph"; import { DAGAutomationGraph } from "components/DAGGraph";
import { InputList } from "components/Inputs/InputList";
import { InputTextView } from "components/Inputs/InputTextView";
import { ControlButton } from "react-flow-renderer";
interface Props { interface Props {
automation?: AutomationData; automation?: AutomationData;
@@ -40,7 +43,7 @@ export const AutomationEditor: FC<Props> = ({
save, save,
saveAndUpdate, saveAndUpdate,
} = useAutomatioEditorState(propsAutos, propsOnUpdate); } = useAutomatioEditorState(propsAutos, propsOnUpdate);
const [closeInfo, setCloseInfo] = useState(false); const [infoBoxOpen, setInfoBox] = useState(false);
const [ const [
{ ckFlipped }, { ckFlipped },
setCookies, setCookies,
@@ -71,30 +74,111 @@ export const AutomationEditor: FC<Props> = ({
); );
} }
return ( return (
<div className="automation-editor"> <div className={["automation-editor", state.status].join(" ")}>
{state.status === "saving" && ( {state.status === "saving" && (
<LinearProgress className="linear-loader" /> <LinearProgress className="linear-loader" />
)} )}
<AutoInfoBox <Modal open={infoBoxOpen}>
className={closeInfo ? "hide" : "show"} <AutoInfoBox
metadata={state.data.metadata} metadata={state.data.metadata}
tags={state.data.tags} tags={state.data.tags}
onUpdate={updateMetadata} onUpdate={updateMetadata}
tagDB={tagDB} tagDB={tagDB}
> >
<ButtonIcon <div
className="automation-editor--info-box--icon" className={[
onClick={() => setCloseInfo(!closeInfo)} "automation-editor--info-box--buttons",
title={closeInfo ? "Show Metadata" : "Hide Metadata"} state.status,
color="success" ].join(" ")}
icon={<ArrowBack />} >
/> <Button onClick={() => setInfoBox(false)}>Close</Button>
</AutoInfoBox> <Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save}
disabled={state.status !== "changed"}
>
Save <CheckMarkIcon color="#bf4" />
</Button>
</div>
</AutoInfoBox>
</Modal>
<div <div
className={["automation-editor--flow-wrapper", state.status].join(" ")} className={["automation-editor--flow-wrapper", state.status].join(" ")}
> >
<div className="automation-editor--flow-wrapper--toolbar"> <div className="automation-editor--flow-wrapper--toolbar">
<div className="automation-editor--flow-wrapper--toolbar--title">
<span className="automation-editor--flow-wrapper--toolbar--title--text">
<div className="id">{state.data.metadata.id}</div>
<InputTextView
value={state.data.metadata.alias ?? ""}
placeholder="Name"
onChange={(alias) =>
updateMetadata(
{
...state.data.metadata,
alias,
},
state.data.tags
)
}
/>
</span>
<InputList
fullWidth={false}
label="Mode"
className="automation-editor--flow-wrapper--toolbar--modes"
current={{
id: state.data.metadata.mode,
label: "",
}}
onChange={({ id }) =>
updateMetadata(
{
...state.data.metadata,
mode: id,
},
state.data.tags
)
}
getKey={({ id }) => id}
getDescription={({ label }) => label}
options={[
{
id: "single",
label: "Do not start a new run. Issue a warning.",
},
{
id: "parallel",
label:
"Start a new, independent run in parallel with previous runs.",
},
{
id: "queued",
label:
"Start a new run after all previous runs complete. Runs are guaranteed to execute in the order they were queued.",
},
{
id: "restart",
label: "Start a new run after first stopping previous run.",
},
]}
/>
<InputTextView
className="description"
value={state.data.metadata.description ?? ""}
placeholder="Description"
onChange={(description) =>
updateMetadata(
{
...state.data.metadata,
description,
},
state.data.tags
)
}
/>
</div>
{!dims.flipped && ( {!dims.flipped && (
<Button <Button
className={"automation-editor--flow-wrapper--toolbar--flip-btn"} className={"automation-editor--flow-wrapper--toolbar--flip-btn"}
@@ -120,6 +204,11 @@ export const AutomationEditor: FC<Props> = ({
onTriggerUpdate={updateTrigger} onTriggerUpdate={updateTrigger}
onConditionUpdate={updateCondition} onConditionUpdate={updateCondition}
isFlipped={flipped} isFlipped={flipped}
additionalControls={
<ControlButton onClick={() => setInfoBox(!infoBoxOpen)}>
<ModeEditOutlineTwoToneIcon />
</ControlButton>
}
/> />
</div> </div>
</div> </div>
@@ -101,7 +101,7 @@ export const BadAutmations = make([
condition: [], condition: [],
tags: {}, tags: {},
metadata: { metadata: {
id: "Bad Choose Sequence", id: "Bad Choose Example",
alias: "Bad Choose", alias: "Bad Choose",
description: "Example Metadata", description: "Example Metadata",
trigger_variables: { trigger_variables: {
@@ -112,7 +112,7 @@ export const BadAutmations = make([
trigger: [], trigger: [],
sequence: [ sequence: [
{ {
choose: {}, choose: [],
}, },
] as any, ] as any,
}, },
@@ -20,6 +20,7 @@ export type AutomationListBoxProps = {
onSelectAutomation: (i: number) => void; onSelectAutomation: (i: number) => void;
onRemove: (i: number) => void; onRemove: (i: number) => void;
onAdd: () => void; onAdd: () => void;
onUpdateTags: (id: string, tags: Record<string, string>) => void;
onUpdate: (a: AutomationData, i: number) => void; onUpdate: (a: AutomationData, i: number) => void;
onLoadMore: (p: ListParams) => void; onLoadMore: (p: ListParams) => void;
tagsDB: TagDB; tagsDB: TagDB;
@@ -62,14 +63,15 @@ const useAutomationListBoxState = () => {
export const AutomationListBox: FC<AutomationListBoxProps> = ({ export const AutomationListBox: FC<AutomationListBoxProps> = ({
automations: { automations: {
data: automations, data: automations,
params: autoParams, // params: autoParams,
totalItems: totalAutomations, totalItems: totalAutomations,
}, },
selected, selected,
onSelectAutomation, onSelectAutomation,
onAdd, onAdd,
onRemove, onRemove,
onLoadMore, // onLoadMore,
onUpdateTags,
tagsDB, tagsDB,
onUpdate, onUpdate,
}) => { }) => {
@@ -177,9 +177,10 @@ export const AutomationListBoxItem: FC<{
onSave, onSave,
}) => { }) => {
// state // state
const [{ tags, isModified }, setState] = useState({ const [{ tags, isModified, alias }, setState] = useState({
isModified: false, isModified: false,
tags: Object.entries(auto.tags), tags: Object.entries(auto.tags),
alias: auto.metadata.alias ?? "",
}); });
// effects // effects
@@ -187,14 +188,22 @@ export const AutomationListBoxItem: FC<{
setState({ setState({
isModified: false, isModified: false,
tags: Object.entries(auto.tags), tags: Object.entries(auto.tags),
alias: auto.metadata.alias ?? "",
}); });
}, [auto]); }, [auto]);
// alias // alias
const setAlias = (a: string) =>
setState({
isModified: true,
tags,
alias: a,
});
const setTags = (t: [string, string][]) => const setTags = (t: [string, string][]) =>
setState({ setState({
isModified: true, isModified: true,
tags: t, tags: t,
alias,
}); });
// sub elements // sub elements
let title = "BadAuto<<Missing Metadata>>"; let title = "BadAuto<<Missing Metadata>>";
@@ -215,10 +224,14 @@ export const AutomationListBoxItem: FC<{
onClick={() => onSelectAutomation(autoIndex)} onClick={() => onSelectAutomation(autoIndex)}
> >
<MetadataBox <MetadataBox
metadata={auto.metadata} metadata={{
...auto.metadata,
alias,
}}
tags={tags} tags={tags}
tagsDB={tagsDB} tagsDB={tagsDB}
onUpdate={setTags} onTagUpdate={setTags}
onAliasUpdate={setAlias}
/> />
<div className="automation-list-box--body--item--buttons"> <div className="automation-list-box--body--item--buttons">
{isModified && ( {isModified && (
@@ -229,6 +242,10 @@ export const AutomationListBoxItem: FC<{
onSave({ onSave({
...auto, ...auto,
tags: Object.fromEntries(tags), tags: Object.fromEntries(tags),
metadata: {
...auto.metadata,
alias,
},
}) })
} }
/> />
@@ -7,6 +7,13 @@
.automation-list-box--body--item--title>b { .automation-list-box--body--item--title>b {
font-size: 1em; 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 { .automation-list-box--body--item--title>span, .automation-list-box--body--item--title>b>span {
@@ -80,4 +87,15 @@
.automation-list-box--body--item--tags--item>.text .icon:hover svg { .automation-list-box--body--item--tags--item>.text .icon:hover svg {
fill: var(--mui-common-black); 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;
} }
@@ -4,13 +4,16 @@ import { FC, useState } from "react";
import { AutomationMetadata } from "types/automations"; import { AutomationMetadata } from "types/automations";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { TagDB } from "./TagDB"; import { TagDB } from "./TagDB";
import DeleteIcon from "@mui/icons-material/ClearTwoTone";
import { InputTextView } from "components/Inputs/InputTextView";
export const MetadataBox: FC<{ export const MetadataBox: FC<{
metadata: AutomationMetadata; metadata: AutomationMetadata;
onUpdate: (t: [string, string][]) => void; onAliasUpdate: (t: string) => void;
onTagUpdate: (t: [string, string][]) => void;
tags: [string, string][]; tags: [string, string][];
tagsDB: TagDB; tagsDB: TagDB;
}> = ({ tags, onUpdate, tagsDB, metadata }) => { }> = ({ tags, onTagUpdate, onAliasUpdate, tagsDB, metadata }) => {
// state // state
const [newTag, setNewTag] = useState< const [newTag, setNewTag] = useState<
| { | {
@@ -30,9 +33,12 @@ export const MetadataBox: FC<{
if (metadata) { if (metadata) {
title = ( title = (
<> <>
<b> <b className="text">
{String(metadata.alias ?? "").slice(0, 15)}{" "} <InputTextView
<span>({String(metadata.id).slice(0, 5)})</span> value={metadata.alias ?? ""}
onChange={onAliasUpdate}
/>
<span>({String(metadata.id).slice(0, 10)})</span>
</b> </b>
<span>{String(metadata.description ?? "").slice(0, 25)}</span> <span>{String(metadata.description ?? "").slice(0, 25)}</span>
</> </>
@@ -47,8 +53,14 @@ export const MetadataBox: FC<{
options={[tagOptions, tagsDB.getTagValues(tagName)]} options={[tagOptions, tagsDB.getTagValues(tagName)]}
key={tagIndex} key={tagIndex}
value={[tagName, tagValue]} value={[tagName, tagValue]}
onDelete={() =>
onTagUpdate([
...tags.slice(0, tagIndex),
...tags.slice(tagIndex + 1),
])
}
onChange={([newName, newValue]) => onChange={([newName, newValue]) =>
onUpdate([ onTagUpdate([
...tags.slice(0, tagIndex), ...tags.slice(0, tagIndex),
[newName, newValue], [newName, newValue],
...tags.slice(tagIndex + 1), ...tags.slice(tagIndex + 1),
@@ -56,29 +68,34 @@ export const MetadataBox: FC<{
} }
/> />
))} ))}
{newTag.on && ( {newTag.on ? (
<MetadataBoxTag <MetadataBoxTag
options={[tagOptions, tagsDB.getTagValues(newTag.name)]} options={[tagOptions, tagsDB.getTagValues(newTag.name)]}
key="new" key="new"
value={[newTag.name, newTag.value]} value={[newTag.name, newTag.value]}
initialState={[true, true]} initialState={true}
onChange={([name, value]) => { onChange={([name, value]) => {
if (name.trim() !== "" && value.trim() !== "") { setNewTag({
setNewTag({ on: true,
on: false, name,
}); value,
onUpdate([...tags, [name, value]]); });
} else { }}
setNewTag({ onToggle={(em) => {
on: true, if (!em) {
name, if (newTag.name.trim() !== "" && newTag.value.trim() !== "") {
value, onTagUpdate(tags.concat([[newTag.name, newTag.value]]));
}); setNewTag({
on: false,
});
}
} }
setNewTag({
on: false,
});
}} }}
/> />
)} ) : (
{!newTag.on && (
<span <span
className="automation-list-box--body--item--tags--add" className="automation-list-box--body--item--tags--add"
onClick={() => onClick={() =>
@@ -101,16 +118,29 @@ export const MetadataBoxTag: FC<{
value: [string, string]; value: [string, string];
onChange: (t: [string, string]) => void; onChange: (t: [string, string]) => void;
options: [string[], string[]]; options: [string[], string[]];
initialState?: [boolean, boolean]; initialState?: boolean;
onToggle?: (em: boolean) => void;
onDelete?: () => void;
}> = (props) => { }> = (props) => {
const [[editMode1, editMode2], setEditMode] = useState( const [editMode, setEditMode] = useState(
props.initialState ? props.initialState : [false, false] props.initialState ? props.initialState : false
); );
const toggle1 = () => setEditMode([!editMode1, editMode2]); const toggle = () => {
const toggle2 = () => setEditMode([editMode1, !editMode2]); 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 ( return (
<span className="automation-list-box--body--item--tags--item"> <span className="automation-list-box--body--item--tags--item">
{editMode1 ? ( {props.onDelete && (
<DeleteIcon onClick={props.onDelete} className="delete" />
)}
{editMode ? (
<InputAutoComplete <InputAutoComplete
multiple={false} multiple={false}
className="text" className="text"
@@ -118,17 +148,17 @@ export const MetadataBoxTag: FC<{
options={props.options[0]} options={props.options[0]}
label="" label=""
value={props.value[0]} value={props.value[0]}
onEnter={toggle1} onEnter={toggle}
onChange={(v) => props.onChange([v ?? "", props.value[1]])} onChange={(v) => props.onChange([v ?? "", props.value[1]])}
onlyShowLabel onlyShowLabel
endAdornment={<CheckMarkIcon className="icon" onClick={toggle1} />} endAdornment={<CheckMarkIcon className="icon" onClick={toggle} />}
/> />
) : ( ) : (
<b className="text" onClick={toggle1}> <b className="text" onClick={toggle}>
{props.value[0]}: {props.value[0]}:
</b> </b>
)} )}
{editMode2 ? ( {editMode ? (
<InputAutoComplete <InputAutoComplete
multiple={false} multiple={false}
className="text" className="text"
@@ -136,13 +166,13 @@ export const MetadataBoxTag: FC<{
options={props.options[1]} options={props.options[1]}
label="" label=""
value={props.value[1]} value={props.value[1]}
onEnter={toggle2} onEnter={toggle}
onChange={(v) => props.onChange([props.value[0], v ?? ""])} onChange={(v) => props.onChange([props.value[0], v ?? ""])}
onlyShowLabel onlyShowLabel
endAdornment={<CheckMarkIcon className="icon" onClick={toggle2} />} endAdornment={<CheckMarkIcon className="icon" onClick={toggle} />}
/> />
) : ( ) : (
<span className="text" onClick={toggle2}> <span className="text" onClick={toggle}>
{props.value[1]} {props.value[1]}
</span> </span>
)} )}
@@ -17,28 +17,6 @@
left: 0.25em; left: 0.25em;
} }
.automation-list--root.mobile .automation-editor--info-box {
min-width: 100vw;
min-height: calc(100vh - 5em);
max-width: 100vw;
max-height: calc(100vh - 5em);
padding: 0;
}
.automation-list--root.mobile .automation-editor--info-box-inner {
margin-top: 2.5em;
padding-left: 0.5em;
padding-right: 0.5em;
margin-bottom: 2em;
}
.automation-list--root.mobile .automation-editor--info-box--icon {
left: 0.5em;
bottom: 0em;
background-color: var(--mui-common-black);
transform: rotate(90deg);
}
/* list hide */ /* list hide */
.automation-list--root.mobile .automation-list--list.hide { .automation-list--root.mobile .automation-list--list.hide {
@@ -50,29 +28,11 @@
.automation-list--root.mobile .automation-list--list.hide .automation-list--list-hide { .automation-list--root.mobile .automation-list--list.hide .automation-list--list-hide {
transform: rotate(270deg); transform: rotate(270deg);
position: fixed; position: fixed;
top: 0; top: 0.5em;
z-index: 5; z-index: 5;
} }
/* info box hide */ .automation-list--root.mobile .automation-editor--flow-wrapper>.automation-editor--flow-wrapper--toolbar .input-text-view,
.automation-list--root.mobile .automation-editor--info-box.hide { .automation-list--root.mobile .automation-editor--flow-wrapper>.automation-editor--flow-wrapper--toolbar .id {
width: 100vw; display: none;
min-height: 0;
max-height: 0;
}
.automation-list--root.mobile .automation-editor--info-box.hide .automation-editor--info-box--icon {
transform: rotate(270deg);
position: fixed;
top: 0em;
left: 0.25em;
z-index: 10;
}
.automation-list--root.mobile .automation-editor--flow-wrapper.unchanged>.automation-editor--flow-wrapper--toolbar {
height: 0;
opacity: 0;
overflow: hidden;
} }
+33 -10
View File
@@ -21,6 +21,7 @@ import { ListData, ListParams } from "apiService/types";
interface AutomationListParams { interface AutomationListParams {
automations: ListData<AutomationData>; automations: ListData<AutomationData>;
onUpdate: (i: number, auto: AutomationData) => void; onUpdate: (i: number, auto: AutomationData) => void;
onUpdateTags: (id: string, tags: Record<string, string>) => void;
onAdd: (auto: AutomationData) => void; onAdd: (auto: AutomationData) => void;
onRemove: (i: number) => void; onRemove: (i: number) => void;
onLoadMore: (p: ListParams) => void; onLoadMore: (p: ListParams) => void;
@@ -58,6 +59,7 @@ export const AutomationList: FC<AutomationListParams> = ({
automations, automations,
onLoadMore, onLoadMore,
onUpdate, onUpdate,
onUpdateTags,
onAdd, onAdd,
onRemove, onRemove,
dims, dims,
@@ -96,6 +98,7 @@ export const AutomationList: FC<AutomationListParams> = ({
<AutomationListBox <AutomationListBox
automations={automations} automations={automations}
onUpdate={(a, i) => onUpdate(i, a)} onUpdate={(a, i) => onUpdate(i, a)}
onUpdateTags={onUpdateTags}
onAdd={() => { onAdd={() => {
onAdd(defaultAutomation(String(Date.now()))); onAdd(defaultAutomation(String(Date.now())));
setCurrent(automations.data.length); setCurrent(automations.data.length);
@@ -152,16 +155,32 @@ export const ConnectedAutomationList: FC<ConnectedAutomationListParams> = ({
dims, dims,
}) => { }) => {
const { reloadAutomations } = useHA(); 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 removeAutomation = async (args: any) => {
const resp = await methods.removeAutomation(args); const resp = await methods.removeAutomation(args);
setSaving(true);
await reloadAutomations(); await reloadAutomations();
setSaving(false);
return resp; return resp;
}; };
const updateAutomation = async (args: any) => { const updateAutomation = async (args: any) => {
const resp = await methods.updateAutomation(args); const resp = await methods.updateAutomation(args);
setSaving(true);
await reloadAutomations(); await reloadAutomations();
setSaving(false);
return resp; return resp;
}; };
if (!automations.ready) { if (!automations.ready) {
return ( return (
<div className="automation-list--root loading"> <div className="automation-list--root loading">
@@ -176,15 +195,19 @@ export const ConnectedAutomationList: FC<ConnectedAutomationListParams> = ({
return <span>Error {automations.error}</span>; return <span>Error {automations.error}</span>;
} }
return ( return (
<AutomationList <>
dims={dims} {saving && <LinearProgress />}
automations={automations.data} <AutomationList
onLoadMore={() => {}} dims={dims}
onAdd={(auto) => automations={automations.data}
updateAutomation({ auto, index: automations.data.totalItems + 1 }) onUpdateTags={updateTags}
} onLoadMore={() => {}}
onRemove={(index) => removeAutomation({ index })} onAdd={(auto) =>
onUpdate={(index, auto) => updateAutomation({ index, auto })} updateAutomation({ auto, index: automations.data.totalItems + 1 })
/> }
onRemove={(index) => removeAutomation({ index })}
onUpdate={(index, auto) => updateAutomation({ index, auto })}
/>
</>
); );
}; };
@@ -49,6 +49,7 @@
.condition-node-base.is-edited>.condition-node-base--body { .condition-node-base.is-edited>.condition-node-base--body {
max-height: calc(100%-2px-1em); max-height: calc(100%-2px-1em);
max-width: calc(100vw-2px-1em); max-width: calc(100vw-2px-1em);
min-width: 15em;
border-color: var(--mui-success-main); border-color: var(--mui-success-main);
border-style: solid; border-style: solid;
border-width: 1px; border-width: 1px;
@@ -63,4 +64,44 @@
align-items: center; align-items: center;
padding: 0.5em; padding: 0.5em;
background-color: var(--mui-secondary-contrastText); background-color: var(--mui-secondary-contrastText);
}
.condition-node--time-editor {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 0.25em;
}
.condition-node--time-editor--ba {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
gap: 0.5em;
padding-top: 1.5em;
padding-bottom: 0.25em;
position: relative;
width: fit-content;
max-width: 100%;
overflow: hidden;
}
.condition-node--time-editor--ba button.remove {
padding: 0.25em;
min-width: fit-content;
color: var(--mui-error-light);
border-color: transparent;
}
.condition-node--time-editor--ba button.remove:hover {
border-color: var(--mui-error-light);
border-radius: 20px;
}
.condition-node--time-editor--ba .label {
position: absolute;
top: 0;
left: 0.2em;
} }
@@ -56,7 +56,12 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
} else { } else {
const Editor = getEditor(condition); const Editor = getEditor(condition);
childrenConditions = ( childrenConditions = (
<Editor condition={condition} onChange={updateCondition} ha={ha} /> <Editor
condition={condition}
onChange={updateCondition}
ha={ha}
initialViewMode="edit"
/>
); );
} }
// icons // icons
@@ -1,6 +1,7 @@
import "./ConditionNodeSettings.css"; import "./ConditionNodeSettings.css";
import { ButtonIcon, ButtonIconProps } from "components/Icons/ButtonIcons"; import { FC } from "react";
import CodeOutlinedIcon from "@mui/icons-material/CodeOutlined"; import CodeOutlinedIcon from "@mui/icons-material/CodeOutlined";
import CodeOffOutlinedIcon from "@mui/icons-material/CodeOffOutlined"; import CodeOffOutlinedIcon from "@mui/icons-material/CodeOffOutlined";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined"; import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
@@ -8,7 +9,8 @@ import SaveIcon from "@mui/icons-material/Save";
import EditOffIcon from "@mui/icons-material/EditOff"; import EditOffIcon from "@mui/icons-material/EditOff";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import SettingsApplicationsIcon from "@mui/icons-material/SettingsApplications"; import SettingsApplicationsIcon from "@mui/icons-material/SettingsApplications";
import { FC } from "react";
import { ButtonIcon, ButtonIconProps } from "components/Icons/ButtonIcons";
import { SpeedDial } from "components/SpeedDial"; import { SpeedDial } from "components/SpeedDial";
export type ConditionNodeSettingsProps = { export type ConditionNodeSettingsProps = {
@@ -1,4 +1,4 @@
import { FC } from "react"; import { FC, useState } from "react";
import { import {
AutomationCondition, AutomationCondition,
DeviceCondition, DeviceCondition,
@@ -13,7 +13,10 @@ import {
import InputNumber from "components/Inputs/InputNumber"; import InputNumber from "components/Inputs/InputNumber";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/InputText";
import { InputEntity } from "components/Inputs/InputEntities"; import { InputEntity } from "components/Inputs/InputEntities";
import { ConditionNodeBase } from "./ConditionNodeBase"; import {
ConditionNodeBase,
ConditionNodeBaseViewMode,
} from "./ConditionNodeBase";
import { genUpdateMethods } from "./nestedUpdater"; import { genUpdateMethods } from "./nestedUpdater";
import { InputTime } from "components/Inputs/InputTime"; import { InputTime } from "components/Inputs/InputTime";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/InputYaml";
@@ -21,12 +24,20 @@ import { HAService } from "haService";
import { DeviceEditor } from "components/DeviceEditor"; import { DeviceEditor } from "components/DeviceEditor";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import AddIcon from "@mui/icons-material/Add"; 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 { prettyName } from "utils/formatting";
import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button";
import { RemoveCircle } from "@mui/icons-material";
interface Editor<C extends AutomationCondition> interface Editor<C extends AutomationCondition>
extends FC<{ extends FC<{
condition: C; condition: C;
onChange: (condition: C) => void; onChange: (condition: C) => void;
ha: HAService; ha: HAService;
initialViewMode: ConditionNodeBaseViewMode;
}> {} }> {}
export const getEditor = (condition: AutomationCondition): Editor<any> => { export const getEditor = (condition: AutomationCondition): Editor<any> => {
@@ -168,6 +179,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
export const LogicViewer: Editor<LogicCondition> = ({ export const LogicViewer: Editor<LogicCondition> = ({
condition, condition,
onChange, onChange,
initialViewMode,
}) => { }) => {
return ( return (
<> <>
@@ -178,6 +190,7 @@ export const LogicViewer: Editor<LogicCondition> = ({
condition={c} condition={c}
{...genUpdateMethods(condition, onChange)(i)} {...genUpdateMethods(condition, onChange)(i)}
disableDelete={false} disableDelete={false}
initialViewMode={initialViewMode}
/> />
); );
})} })}
@@ -207,10 +220,17 @@ export const LogicViewer: Editor<LogicCondition> = ({
export const StateEditor: Editor<StateCondition> = ({ export const StateEditor: Editor<StateCondition> = ({
onChange, onChange,
condition, condition,
ha,
}) => { }) => {
const restrictToDomain =
!condition.entity_id || condition.entity_id.length === 0
? undefined
: getEntityDomains(condition.entity_id);
return ( return (
<> <>
<InputEntity <InputEntity
restrictToDomain={restrictToDomain}
value={condition.entity_id} value={condition.entity_id}
multiple multiple
onChange={(entity_id) => onChange={(entity_id) =>
@@ -220,19 +240,24 @@ export const StateEditor: Editor<StateCondition> = ({
}) })
} }
/> />
<InputText <InputAutoComplete
label="Attribute" label="Attribute"
value={condition.attribute ?? ""} value={condition.attribute ?? ""}
options={ha.entities.getAttributes(condition.entity_id)}
multiple={false}
onChange={(attribute) => onChange={(attribute) =>
onChange({ onChange({
...condition, ...condition,
attribute, attribute: attribute ?? undefined,
}) })
} }
/> />
<InputText <InputText
label="State" label="State"
value={String(condition.state)} value={String(condition.state)}
placeholder={ha.entities
.getStates(condition.entity_id, condition.attribute)
.join(" or ")}
onChange={(state) => onChange={(state) =>
onChange({ onChange({
...condition, ...condition,
@@ -254,31 +279,86 @@ export const StateEditor: Editor<StateCondition> = ({
); );
}; };
type TimeEditorShows = "after" | "before" | "weekday";
export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => { export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
const [shows, setShows] = useState<TimeEditorShows[]>(
Object.keys(condition).filter((k) =>
["after", "before", "weekday"].includes(k)
) as any
);
return ( return (
<> <div className="condition-node--time-editor">
<InputTime {shows.map((show) => {
label="After" if (show === "after" || show === "before") {
value={condition.after} return (
onChange={(after) => <div className="condition-node--time-editor--ba" key={show}>
onChange({ <b className="label">{prettyName(show)}</b>
...condition, <InputTimeEntity
after, value={condition[show] ?? ""}
}) onChange={(v) =>
onChange({
...condition,
[show]: v,
})
}
/>
<Button
className="remove"
onClick={() => {
setShows(shows.filter((k) => k !== show));
const upd = { ...condition };
delete upd[show];
onChange({ ...upd });
}}
>
<RemoveCircle />
</Button>
</div>
);
} else {
return (
<div>
<InputAutoComplete
label="Weekday"
value={condition.weekday ?? []}
multiple={true}
getID={(opt) => opt}
getLabel={(opt) => {
return {
mon: "Monday",
tue: "Tuesday",
wed: "Wednesday",
thu: "Thursday",
fri: "Friday",
sat: "Saturday",
sun: "Sunday",
}[opt];
}}
onChange={(weekday: any) =>
onChange({
...condition,
weekday: weekday ?? [],
})
}
options={["mon", "tue", "wed", "thu", "fri", "sat", "sun"]}
/>
</div>
);
} }
/> })}
<InputTime {shows.length < 3 && (
label="Before" <InputList
value={condition.before} className="condition-node--time-editor--new"
onChange={(before) => label="Option"
onChange({ options={["after", "before", "weekday"].filter(
...condition, (k: any) => !shows.includes(k)
before, )}
}) onChange={(k: any) => {
} setShows(shows.concat([k]));
/> }}
<b>Weekday not support for no, use yaml for now</b> {condition.weekday} />
</> )}
</div>
); );
}; };
@@ -307,12 +387,12 @@ export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => {
<> <>
<InputEntity <InputEntity
label="Zone" label="Zone"
value={condition.zone} value={condition.zone ?? []}
multiple={false} multiple
onChange={(zone) => onChange={(zone) =>
onChange({ onChange({
...condition, ...condition,
zone: zone ?? "", zone: zone ?? [],
}) })
} }
restrictToDomain={["zone"]} restrictToDomain={["zone"]}
@@ -329,16 +409,6 @@ export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => {
} }
restrictToDomain={["person", "device_tracker"]} restrictToDomain={["person", "device_tracker"]}
/> />
<InputText
label="State"
value={String(condition.state)}
onChange={(state) =>
onChange({
...condition,
state,
})
}
/>
</> </>
); );
}; };
@@ -9,6 +9,9 @@ export default {
title: "ConditionEditor", title: "ConditionEditor",
component: ConditionEditor, component: ConditionEditor,
parameters: { actions: { argTypesRegex: "^on.*" } }, parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
initialViewMode: "edit",
},
} as ComponentMeta<typeof ConditionEditor>; } as ComponentMeta<typeof ConditionEditor>;
const Template: ComponentStory<typeof ConditionEditor> = ({ const Template: ComponentStory<typeof ConditionEditor> = ({
@@ -79,6 +82,29 @@ LogicCondition.args = {
], ],
} as AutomationCondition, } as AutomationCondition,
}; };
export const TimeCondition = Template.bind({});
TimeCondition.args = {
condition: {
condition: "or",
conditions: [
{
condition: "time",
},
{
condition: "time",
after: "10:00:00",
},
{
condition: "time",
before: "input_datetime.test",
},
{
condition: "time",
weekday: ["fri"],
},
],
} as AutomationCondition,
};
export const MultipleConditions: ComponentStory<typeof ConditionEditor> = ( export const MultipleConditions: ComponentStory<typeof ConditionEditor> = (
args args
@@ -1,10 +1,7 @@
.dag-graphboard {
min-height: 100%;
min-width: 100%;
}
.dag-graphboard.loading { .dag-graphboard.loading {
position: relative; position: relative;
min-height: 100%;
min-width: 100%;
} }
.dag-graphboard.loading span { .dag-graphboard.loading span {
@@ -22,6 +22,7 @@ export const DAGGraphBoardInner: FC<DAGGraphBoardProps> = ({
modalState, modalState,
state, state,
closeModal, closeModal,
additionalControls,
}) => { }) => {
// render unready or errored states // render unready or errored states
if (!state.ready) { if (!state.ready) {
@@ -69,7 +70,9 @@ export const DAGGraphBoardInner: FC<DAGGraphBoardProps> = ({
nodesDraggable={false} nodesDraggable={false}
{...elements} {...elements}
> >
<Controls showInteractive={false} /> <Controls showInteractive={false} showFitView>
{additionalControls}
</Controls>
</ReactFlow> </ReactFlow>
</> </>
); );
@@ -21,6 +21,7 @@ export type DAGGraphBoardProps = {
state: DAGGraphBoardState; state: DAGGraphBoardState;
modalState?: ModalState; modalState?: ModalState;
closeModal: () => void; closeModal: () => void;
additionalControls?: ReactNode;
}; };
export type ModalState< export type ModalState<
@@ -14,7 +14,7 @@ export const DEFAULT_DIMS: DAGDims = {
}, },
distanceFactor: { distanceFactor: {
node: [1.5, 1.5], node: [1.5, 1.5],
collection: [1.25, 1.05], collection: [1.2, 1.1],
}, },
position: { position: {
x: 50, x: 50,
@@ -32,12 +32,13 @@ export const moveAlongRelativeTo = (
? { ? {
x: x:
relatedPos.x + relatedPos.x +
dims.distanceFactor.node[0] * 1.5 * dims[incrementBy].width, dims.distanceFactor[incrementBy][0] * dims[incrementBy].width,
y: offsetPos.y, y: offsetPos.y,
} }
: { : {
y: y:
relatedPos.y + dims.distanceFactor.node[1] * dims[incrementBy].height, relatedPos.y +
dims.distanceFactor[incrementBy][1] * dims[incrementBy].height,
x: offsetPos.x, x: offsetPos.x,
}; };
@@ -45,16 +46,21 @@ export const moveFromTo = (
from: keyof DAGEntities, from: keyof DAGEntities,
to: keyof DAGEntities, to: keyof DAGEntities,
startPoint: XYPosition, startPoint: XYPosition,
dims: DAGDims dims: DAGDims,
byFrom: boolean = false
): XYPosition => { ): XYPosition => {
if (!dims.flipped) { if (!dims.flipped) {
return { return {
x: startPoint.x + dims[from].width * dims.distanceFactor[to][0], x:
startPoint.x +
dims[from].width * dims.distanceFactor[byFrom ? from : to][0],
y: startPoint.y + (dims[from].height - dims[to].height) / 2, y: startPoint.y + (dims[from].height - dims[to].height) / 2,
}; };
} else { } else {
return { return {
y: startPoint.y + dims[from].height * dims.distanceFactor[to][1], y:
startPoint.y +
dims[from].height * dims.distanceFactor[byFrom ? from : to][1],
x: startPoint.x + (dims[from].width - dims[to].width) / 2, x: startPoint.x + (dims[from].width - dims[to].width) / 2,
}; };
} }
@@ -65,6 +71,6 @@ export const offsetBy = (
position: XYPosition, position: XYPosition,
dims: DAGDims dims: DAGDims
): XYPosition => ({ ): XYPosition => ({
x: position.x + dims.distanceFactor[by][0] * dims[by].width, x: position.x + dims.distanceFactor[by][0] * 0.9 * dims[by].width,
y: position.y + dims.distanceFactor[by][1] * dims[by].height, y: position.y + dims.distanceFactor[by][1] * 0.9 * dims[by].height,
}); });
@@ -0,0 +1,135 @@
import { XYPosition } from "react-flow-renderer";
import AddBox from "@mui/icons-material/AddBox";
import { getDescriptionFromAutomationNode } from "utils/formatting";
import { validateNode } from "utils/automations";
import { AutomationCondition } from "types/automations/conditions";
import { AutomationTrigger } from "types/automations/triggers";
import { DAGDims, ElementMaker, ElementMakerProps } from "./types";
import { DAGElementsOutputState } from "./outputState";
import { convertFailuresToSequenceNodeDataProps } from "./util";
import { ButtonNodeMaker } from "../nodes/ButtonNode";
import { CollectionNodeMaker } from "../nodes/CollectionNode";
export const makeTriggerNodes: ElementMaker<AutomationTrigger> = (
nodes,
{ dims, namer, stateUpdater, nodeId, position }
) => {
const outputState = new DAGElementsOutputState(position, dims);
outputState.addNode(
CollectionNodeMaker.makeElement({ id: nodeId, position }, dims, {
...dims.collection,
collectionType: "trigger",
onAddNode: () => stateUpdater.basic.trigger.addNode(null),
nodes: nodes.map((node, index) => {
const failures = validateNode(node, ["trigger"]);
if (failures) {
return {
enabled: node.enabled ?? true,
...stateUpdater.createNodeActions("trigger", index, {}),
...convertFailuresToSequenceNodeDataProps(failures),
};
}
return {
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("trigger", index, {}),
};
}),
})
);
return outputState;
};
export const makeConditionNodes: ElementMaker<AutomationCondition> = (
nodes,
{ nodeId, stateUpdater, position, dims, namer, lastNodeId }
) => {
const outputState = new DAGElementsOutputState(position, dims);
outputState.addNode(
CollectionNodeMaker.makeElement({ id: nodeId, position }, dims, {
...dims.collection,
collectionType: "condition",
hasInput: !!lastNodeId,
onAddNode: () => stateUpdater.basic.condition.addNode(null),
nodes: nodes.map((node, index) => {
const failures = validateNode(node, ["condition"]);
if (failures) {
return {
enabled: node.enabled ?? true,
...stateUpdater.createNodeActions("condition", index, {}),
...convertFailuresToSequenceNodeDataProps(failures),
};
}
return {
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("condition", index, {}),
};
}),
})
);
if (lastNodeId && outputState.lastNodeId) {
outputState.addEdge(lastNodeId, outputState.lastNodeId, { animated: true });
}
return outputState;
};
type MakeAddButtonArgs = {
position: XYPosition;
nodeId: string;
outputState: DAGElementsOutputState;
dims: DAGDims;
onClick: () => void;
};
export const makeAddButton = (args: MakeAddButtonArgs) => {
const addElement = args.outputState.addNode(
ButtonNodeMaker.makeElement(
{
id: `${args.nodeId}-add-new`,
position: args.position,
},
args.dims,
{
text: "Option",
icon: <AddBox />,
onClick: args.onClick,
}
)
);
args.outputState.addEdge(args.nodeId, addElement.id, {
animated: true,
sourceHandle: "side",
});
};
type DrawConditionArgs = {
conditions: AutomationCondition[];
args: ElementMakerProps;
onRemove: () => void;
};
export const drawCondition = ({
conditions,
onRemove,
args,
}: DrawConditionArgs) => {
const conditionState = makeConditionNodes(conditions, args);
(conditionState.data.nodes[0].data as any).title = `Option ${
args.nodeIndex + 1
}`;
(conditionState.data.nodes[0].data as any).onDelete = onRemove;
conditionState.data.edges[0].sourceHandle = `side`;
conditionState.data.edges[0].label = args.nodeIndex > 0 ? "else if" : "if";
conditionState.data.edges[0].style = {
stroke: "var(--mui-info-main)",
};
return conditionState;
};
@@ -468,3 +468,52 @@ ParallelAuto.args = {
], ],
}, },
}; };
export const BadNodes = Template.bind({});
BadNodes.args = {
...BadNodes.args,
automation: {
condition: [
{
event: "triggerme",
},
{
condition: "and",
thisshouldnotbehere: "1",
conditions: "1234",
},
] as any,
trigger: [
{ platform: "homeassistant" },
{ platfom: "bobid" },
{ condition: "and" },
"text?",
] as any,
sequence: [
{
parallel: {
bad: "me",
},
},
{
platform: "event",
},
] as any,
},
};
export const IfElseNode = Template.bind({});
IfElseNode.args = {
...IfElseNode.args,
automation: {
condition: [],
trigger: [],
sequence: [
{
if: [],
else: [],
then: [],
},
],
},
};
+118 -210
View File
@@ -1,29 +1,30 @@
import { DAGDims, ElementMaker, ElementMakerBaseProps } from "./types"; import { DAGDims, ElementMaker, ElementMakerBaseProps } from "./types";
import { AutomationTrigger } from "types/automations/triggers";
import * as distance from "./distance"; import * as distance from "./distance";
import { getDescriptionFromAutomationNode } from "utils/formatting"; import { getDescriptionFromAutomationNode } from "utils/formatting";
import { import {
AutomationActionData, AutomationActionData,
AutomationSequenceNode, AutomationSequenceNode,
} from "types/automations"; } from "types/automations";
import { AutomationCondition } from "types/automations/conditions";
import { CollectionNodeMaker } from "../nodes/CollectionNode";
import { XYPosition } from "react-flow-renderer"; import { XYPosition } from "react-flow-renderer";
import { DAGElementsOutputState } from "./outputState"; import { DAGElementsOutputState } from "./outputState";
import { SequenceNodeMaker } from "../nodes/SequenceNode"; import { SequenceNodeMaker } from "../nodes/SequenceNode";
import { import {
getNodeType, getNodeType,
convertScriptConditionFieldToAutomationConditions, convertScriptConditionFieldToAutomationConditions,
validateNode,
} from "utils/automations"; } from "utils/automations";
import { ButtonNodeMaker } from "../nodes/ButtonNode"; import { ButtonNodeMaker } from "../nodes/ButtonNode";
import { AddIcon } from "components/Icons"; import { AddIcon } from "components/Icons";
import { useDAGElementsState } from "./state"; import { useDAGElementsState } from "./state";
import AddBox from "@mui/icons-material/AddBox";
import { DAGGraphChooseUpdater } from "../updater"; import { DAGGraphChooseUpdater } from "../updater";
import { getSpecialNodeMaker, makeSpecialNodeMaker } from "./specialnodes"; import { getSpecialNodeMaker, makeSpecialNodeMaker } from "./specialnodes";
import { getNodeSubType } from "../../../utils/automations"; import { getNodeSubType } from "../../../utils/automations";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import Add from "@mui/icons-material/Add"; import Add from "@mui/icons-material/Add";
import { SequenceNodeDataProps } from "../nodes/SequenceNode/types";
import { convertFailuresToSequenceNodeDataProps } from "./util";
import { convertChooseActionToOrignal } from "../updater/util";
import * as helpers from "./helpers";
export const useAutomationNodes = ( export const useAutomationNodes = (
automation: AutomationActionData, automation: AutomationActionData,
@@ -35,7 +36,7 @@ export const useAutomationNodes = (
const state = useDAGElementsState(); const state = useDAGElementsState();
const outputState = new DAGElementsOutputState(dims.position, dims); const outputState = new DAGElementsOutputState(dims.position, dims);
outputState.extend( outputState.extend(
makeTriggerNodes(automation.trigger, { helpers.makeTriggerNodes(automation.trigger, {
...args, ...args,
state, state,
dims, dims,
@@ -45,7 +46,7 @@ export const useAutomationNodes = (
}) })
); );
outputState.extend( outputState.extend(
makeConditionNodes(automation.condition, { helpers.makeConditionNodes(automation.condition, {
...args, ...args,
state, state,
dims, dims,
@@ -70,7 +71,8 @@ export const useAutomationNodes = (
"collection", "collection",
"node", "node",
outputState.getLastNodePos(), outputState.getLastNodePos(),
dims dims,
true
), ),
nodeId: `${dims.flipped}-sequence`, nodeId: `${dims.flipped}-sequence`,
nodeIndex: 2, nodeIndex: 2,
@@ -81,50 +83,6 @@ export const useAutomationNodes = (
return outputState.data; return outputState.data;
}; };
export const makeTriggerNodes: ElementMaker<AutomationTrigger> = (
nodes,
{ dims, namer, stateUpdater, nodeId, position }
) => {
const outputState = new DAGElementsOutputState(position, dims);
outputState.addNode(
CollectionNodeMaker.makeElement({ id: nodeId, position }, dims, {
...dims.collection,
collectionType: "trigger",
onAddNode: () => stateUpdater.basic.trigger.addNode(null),
nodes: nodes.map((node, index) => ({
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("trigger", index, {}),
})),
})
);
return outputState;
};
export const makeConditionNodes: ElementMaker<AutomationCondition> = (
nodes,
{ nodeId, stateUpdater, position, dims, namer, lastNodeId }
) => {
const outputState = new DAGElementsOutputState(position, dims);
outputState.addNode(
CollectionNodeMaker.makeElement({ id: nodeId, position }, dims, {
...dims.collection,
collectionType: "condition",
hasInput: !!lastNodeId,
onAddNode: () => stateUpdater.basic.condition.addNode(null),
nodes: nodes.map((node, index) => ({
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("condition", index, {}),
})),
})
);
if (lastNodeId && outputState.lastNodeId) {
outputState.addEdge(lastNodeId, outputState.lastNodeId, { animated: true });
}
return outputState;
};
export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = ( export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
nodes, nodes,
args args
@@ -133,10 +91,25 @@ export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
const outputState = new DAGElementsOutputState(position, dims); const outputState = new DAGElementsOutputState(position, dims);
nodes.forEach((node, nodeIndex) => { nodes.forEach((node, nodeIndex) => {
// the JSON.stringify is hack to make the edges render nicely // the JSON.stringify is hack to make the edges render nicely
const nodeId = `${args.nodeId}-${
args.nodeIndex
}-${nodeIndex}-${JSON.stringify(node)}`;
outputState.incNextPos("node"); outputState.incNextPos("node");
const nodeId = `${args.nodeId}-${args.nodeIndex}-${nodeIndex}`;
let nodeData: SequenceNodeDataProps = {
color: getNodeType(node) === "action" ? "green" : "blue",
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...state.getIsClosedActions(nodeId, node),
...stateUpdater.createNodeActions("sequence", nodeIndex, {
includeAdd: true,
flipped: dims.flipped,
}),
};
const failures = validateNode(node, ["action", "condition"]);
if (failures) {
nodeData = {
...nodeData,
...convertFailuresToSequenceNodeDataProps(failures),
};
}
const element = outputState.addNode( const element = outputState.addNode(
SequenceNodeMaker.makeElement( SequenceNodeMaker.makeElement(
{ {
@@ -144,49 +117,38 @@ export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
position: outputState.nextPos, position: outputState.nextPos,
}, },
dims, dims,
{ nodeData
color: getNodeType(node) === "action" ? "green" : "blue",
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...state.getIsClosedActions(nodeId, node),
...stateUpdater.createNodeActions("sequence", nodeIndex, {
includeAdd: true,
flipped: dims.flipped,
}),
}
), ),
true true
); );
if (nodeIndex === 0 && lastNodeId) { if (nodeIndex === 0 && lastNodeId) {
outputState.addEdge(lastNodeId, element.id); outputState.addEdge(lastNodeId, element.id);
} }
const specialNodeMaker = getSpecialNodeMaker( if (!failures) {
getNodeSubType(node, true) as any const specialNodeMaker = getSpecialNodeMaker(
); getNodeSubType(node, true) as any
if (specialNodeMaker) {
outputState.extend(
specialNodeMaker([node] as any, {
...args,
nodeId,
lastNodeId: element.id,
position: outputState.getLastNodePos(),
nodeIndex,
}),
true
); );
if (specialNodeMaker) {
outputState.extend(
specialNodeMaker([node] as any, {
...args,
nodeId,
lastNodeId: element.id,
position: outputState.getLastNodePos(),
nodeIndex,
}),
true
);
}
} }
outputState.incNextPos("node");
}); });
const addElement = outputState.addNode( const addElement = outputState.addNode(
ButtonNodeMaker.makeElement( ButtonNodeMaker.makeElement(
{ {
id: `${args.nodeId}-add-new`, id: `${args.nodeId}-add-new`,
position: distance.moveAlong( position: outputState.nextPos,
"node",
outputState.getLastNodePos(position),
1,
dims
),
}, },
dims, dims,
{ {
@@ -206,51 +168,19 @@ export const makeSequenceNodes: ElementMaker<AutomationSequenceNode> = (
export const makeChooseeNodes = makeSpecialNodeMaker( export const makeChooseeNodes = makeSpecialNodeMaker(
"choose", "choose",
(node, outputState, args) => { (incmNode, outputState, args) => {
const node = convertChooseActionToOrignal(incmNode);
// offset position // offset position
let offsetPos: XYPosition = distance.offsetBy( let pos: XYPosition = distance.offsetBy("node", args.position, args.dims);
"node",
args.position,
args.dims
);
let lastConditionState: DAGElementsOutputState | null = null; let lastConditionState: DAGElementsOutputState | null = null;
// functions // functions
const drawCondition = (
{ stateUpdater, onRemove }: DAGGraphChooseUpdater,
position: XYPosition,
lastNodeId: string | undefined,
nodeIndex: number,
conditions: AutomationCondition[]
) => {
const conditionState = makeConditionNodes(conditions, {
...args,
stateUpdater,
position,
lastNodeId,
nodeIndex,
nodeId: `${args.nodeId}-choose-${nodeIndex}-condition`,
});
lastConditionState = conditionState;
(conditionState.data.nodes[0].data as any).title = `Option ${
nodeIndex + 1
}`;
(conditionState.data.nodes[0].data as any).onDelete = onRemove;
conditionState.data.edges[0].sourceHandle = `side`;
conditionState.data.edges[0].label = `Option ${nodeIndex + 1}`;
conditionState.data.edges[0].style = {
stroke: "var(--mui-info-main)",
};
outputState.extend(conditionState);
return conditionState;
};
const drawSequence = ( const drawSequence = (
{ stateUpdater }: DAGGraphChooseUpdater, { stateUpdater }: DAGGraphChooseUpdater,
position: XYPosition, position: XYPosition,
lastNodeId: string | undefined, lastNodeId: string | undefined,
nodeIndex: number, nodeIndex: number,
sequence: AutomationSequenceNode[], sequence: AutomationSequenceNode[],
label: "else" | undefined isElse: boolean = false
) => { ) => {
const output = makeSequenceNodes(sequence, { const output = makeSequenceNodes(sequence, {
...args, ...args,
@@ -263,8 +193,8 @@ export const makeChooseeNodes = makeSpecialNodeMaker(
if (lastNodeId && output.data.nodes.length > 0) { if (lastNodeId && output.data.nodes.length > 0) {
outputState.addEdge(lastNodeId, output.data.nodes[0].id, { outputState.addEdge(lastNodeId, output.data.nodes[0].id, {
animated: true, animated: true,
label, label: isElse ? "else" : "then",
sourceHandle: label === "else" ? "side" : undefined, sourceHandle: isElse ? "side" : undefined,
style: { style: {
stroke: "var(--mui-error-main)", stroke: "var(--mui-error-main)",
zIndex: -1, zIndex: -1,
@@ -276,33 +206,36 @@ export const makeChooseeNodes = makeSpecialNodeMaker(
// process options // process options
for (let sIndex = 0; sIndex < node.choose.length; sIndex++) { for (let sIndex = 0; sIndex < node.choose.length; sIndex++) {
const stateUpdater = args.stateUpdater.createChoosNodeUpdater( const { stateUpdater, onRemove } =
args.nodeIndex, args.stateUpdater.createChoosNodeUpdater(args.nodeIndex, sIndex);
sIndex // let pos = offsetPos;
);
let pos = offsetPos;
let lastNodeId = args.lastNodeId; let lastNodeId = args.lastNodeId;
const conditionState = drawCondition( const conditionState = helpers.drawCondition({
stateUpdater, conditions: node.choose[sIndex].conditions,
pos, onRemove,
lastNodeId, args: {
sIndex, ...args,
node.choose[sIndex].conditions stateUpdater,
); position: pos,
pos = distance.moveFromTo("collection", "node", pos, args.dims); lastNodeId,
nodeIndex: sIndex,
nodeId: `${args.nodeId}-choose-${sIndex}-condition`,
},
});
outputState.extend(conditionState);
lastConditionState = conditionState; lastConditionState = conditionState;
lastNodeId = conditionState.lastNodeId; lastNodeId = conditionState.lastNodeId;
const sequence = node.choose[sIndex].sequence; const sequence = node.choose[sIndex].sequence;
const output = drawSequence( const output = drawSequence(
stateUpdater, { stateUpdater, onRemove },
pos, distance.moveFromTo("collection", "node", pos, args.dims),
lastNodeId, lastNodeId,
sIndex, sIndex,
sequence, sequence,
undefined undefined
); );
offsetPos = distance.moveAlongRelativeTo( pos = distance.moveAlongRelativeTo(
offsetPos, pos,
output.bbox[1], output.bbox[1],
args.dims, args.dims,
"collection" "collection"
@@ -310,40 +243,9 @@ export const makeChooseeNodes = makeSpecialNodeMaker(
outputState.extend(output); outputState.extend(output);
} }
// else
const stateUpdater = args.stateUpdater.createChoosNodeUpdater(
args.nodeIndex,
"else"
);
let pos = offsetPos;
let lastNodeId = args.lastNodeId;
const elseOutput = drawSequence(
stateUpdater,
pos,
lastNodeId,
node.choose.length,
node.default ?? [],
"else"
);
offsetPos = distance.moveAlongRelativeTo(
offsetPos,
elseOutput.bbox[1],
args.dims,
"node"
);
outputState.extend(elseOutput);
// add btn // add btn
let addPos = distance.moveAlong(
"node",
elseOutput.data.nodes[0].position,
1 / args.dims.distanceFactor.node[0],
args.dims,
true
);
console.log({ addPos, lastConditionState });
if (lastConditionState !== null) { if (lastConditionState !== null) {
addPos = distance.moveFromTo( pos = distance.moveFromTo(
"collection", "collection",
"node", "node",
(lastConditionState as DAGElementsOutputState).nextPos, (lastConditionState as DAGElementsOutputState).nextPos,
@@ -353,37 +255,42 @@ export const makeChooseeNodes = makeSpecialNodeMaker(
} }
); );
} }
const addElement = outputState.addNode( helpers.makeAddButton({
ButtonNodeMaker.makeElement( outputState,
{ dims: args.dims,
id: `${args.nodeId}-choose-add-new`, nodeId: args.nodeId,
position: addPos, position: pos,
}, onClick: () =>
args.dims, args.stateUpdater.basic.sequence.updateNode(
{ {
text: "Option", ...node,
icon: <AddBox />, choose: [
onClick: () => ...node.choose,
args.stateUpdater.basic.sequence.updateNode(
{ {
...node, conditions: [],
choose: [ sequence: [],
...node.choose,
{
conditions: [],
sequence: [],
},
],
}, },
args.nodeIndex ],
), },
} args.nodeIndex
) ),
);
outputState.addEdge(args.nodeId, addElement.id, {
animated: true,
sourceHandle: "side",
}); });
// else
const stateUpdater = args.stateUpdater.createChoosNodeUpdater(
args.nodeIndex,
"else"
);
let lastNodeId = args.lastNodeId;
const elseOutput = drawSequence(
stateUpdater,
distance.moveAlong("node", pos, 1, args.dims, true),
lastNodeId,
node.choose.length,
node.default ?? [],
true
);
outputState.extend(elseOutput);
} }
); );
@@ -406,7 +313,7 @@ export const makeRepeatNodes = makeSpecialNodeMaker(
// while // while
if ("while" in node.repeat) { if ("while" in node.repeat) {
whileState = makeConditionNodes( whileState = helpers.makeConditionNodes(
convertScriptConditionFieldToAutomationConditions(node.repeat.while), convertScriptConditionFieldToAutomationConditions(node.repeat.while),
{ {
...args, ...args,
@@ -457,7 +364,7 @@ export const makeRepeatNodes = makeSpecialNodeMaker(
); );
// until // until
if ("until" in node.repeat) { if ("until" in node.repeat) {
untilState = makeConditionNodes( untilState = helpers.makeConditionNodes(
convertScriptConditionFieldToAutomationConditions(node.repeat.until), convertScriptConditionFieldToAutomationConditions(node.repeat.until),
{ {
...args, ...args,
@@ -555,18 +462,19 @@ export const makeParallelNodes = makeSpecialNodeMaker(
{ {
icon: <Add />, icon: <Add />,
onClick: () => onClick: () =>
args.stateUpdater.basic.sequence.updateNode( args.openModal({
{ allowedTypes: ["condition", "action"],
...node, node: args.stateUpdater.basic.sequence.defaultNode,
parallel: [ saveBtnCreateText: true,
...node.parallel, update: (n) =>
args.stateUpdater.basic.sequence.updateNode(
{ {
sequence: [], ...node,
parallel: [...node.parallel, n],
}, },
], args.nodeIndex
}, ),
args.nodeIndex }),
),
} }
); );
outputState.addNode(addBtn); outputState.addNode(addBtn);
@@ -105,6 +105,6 @@ export class DAGElementsOutputState {
if (!this.lastNode) { if (!this.lastNode) {
return; return;
} }
this.nextPos = moveAlong(by, this.nextPos, 1, this.dims); this.nextPos = moveAlong(by, this.nextPos, 0.5, this.dims);
} }
} }
@@ -1,3 +1,4 @@
import { AutomationNodeSubtype } from "types/automations";
import { ActionType, ActionTypeMapping } from "types/automations/actions"; import { ActionType, ActionTypeMapping } from "types/automations/actions";
import { DAGElementsOutputState } from "./outputState"; import { DAGElementsOutputState } from "./outputState";
import { ElementMaker, ElementMakerProps } from "./types"; import { ElementMaker, ElementMakerProps } from "./types";
@@ -41,3 +42,6 @@ export const makeSpecialNodeMaker = <
export const getSpecialNodeMaker = <AT extends ActionType>( export const getSpecialNodeMaker = <AT extends ActionType>(
nodeType: AT nodeType: AT
): ElementMaker<AT> | null => SpecialNodeRegistry[nodeType] ?? null; ): ElementMaker<AT> | null => SpecialNodeRegistry[nodeType] ?? null;
export const isSpecialNode = (nodeType: AutomationNodeSubtype) =>
nodeType in SpecialNodeRegistry;
@@ -1,5 +1,7 @@
import { useState } from "react"; import { useState } from "react";
import { AutomationNode } from "types/automations"; import { AutomationNode } from "types/automations";
import { isSpecialNode } from "./specialnodes";
import { getNodeSubType } from "utils/automations";
export type DAGNodeState = Partial<{ export type DAGNodeState = Partial<{
isClosed: boolean; isClosed: boolean;
@@ -27,7 +29,7 @@ export const useDAGElementsState = () => {
}, },
getIsClosedActions(nodeId: string, node: AutomationNode) { getIsClosedActions(nodeId: string, node: AutomationNode) {
if ("choose" in node || "repeat" in node) { if (isSpecialNode(getNodeSubType(node))) {
return { return {
isClosed: this.get(nodeId).isClosed ?? false, isClosed: this.get(nodeId).isClosed ?? false,
setIsClosed: (v: boolean) => this.set(nodeId, "isClosed", v), setIsClosed: (v: boolean) => this.set(nodeId, "isClosed", v),
@@ -0,0 +1,21 @@
import { MiniFailure } from "types/validators/helper";
import { SequenceNodeColor } from "../nodes/SequenceNode/types";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
export const convertFailuresToSequenceNodeDataProps = (
failures: MiniFailure[]
) => {
return {
label: (
<>
<InfoOutlinedIcon />
<div className="daggraph--error">
{failures.map((f, i) => (
<span key={i}>{f.message}</span>
))}
</div>
</>
),
color: "error" as SequenceNodeColor,
};
};
@@ -1,49 +0,0 @@
import { Button } from "components/Inputs/Button";
import InputYaml from "components/Inputs/InputYaml";
import { FC } from "react";
import { DAGGraphBoardProps } from "../board/types";
export const ErroredBoard: FC<
DAGGraphBoardProps & {
error: Error | any;
}
> = (props) => {
// const makeSet = <K extends keyof FailedStateData>(k: K) => (d: FailedStateData[K]) => this.setState({
// ...this.state,
// [k]: d,
// });
// const makeSave = <K extends keyof FailedStateData>(k: K) => () => {
// if (!this.state.hasError) {
// return
// }
// if (k === 'condition') {
// this.props.onConditionUpdate(this.state.condition)
// } else if (k === 'sequence') {
// this.props.onSequenceUpdate(this.state.sequence)
// } else if (k === 'trigger') {
// this.props.onTriggerUpdate(this.state.trigger)
// }
// }
return (
<div className="dag-flow-safe">
<h1>An Error has occured.</h1>
<h1>Failed to Open Autmation!</h1>
Something is likely not configured in your automation properly.
<hr />
<h2>Error:</h2>
{/* <h2>{String(this.state.error)}</h2> */}
<br />
{/* {JSON.stringify(this.state.error, null, 4)} */}
{/* {this.state.errorInfo && this.state.errorInfo.componentStack.split('\n').map((s, i) => <>
<span key={i}>{s}</span><br key={`br-${i}`} />
</>)} */}
<h2>Automation YAML</h2>
{/* <InputYaml label="Trigger" value={this.state.trigger} onChange={makeSet('trigger')} />
<Button onClick={makeSave('trigger')}>Save Triggers</Button>
<InputYaml label="Condition" value={this.state.condition} onChange={makeSet('condition')} />
<Button onClick={makeSave('condition')}>Save Conditions</Button>
<InputYaml label="Action" value={this.state.sequence} onChange={makeSet('sequence')} />
<Button onClick={makeSave('sequence')}>Save Actions</Button> */}
</div>
);
};
+4 -1
View File
@@ -1,4 +1,4 @@
import { FC, useState } from "react"; import { FC, useState, ReactNode } from "react";
import { AutomationSequenceNode } from "types/automations"; import { AutomationSequenceNode } from "types/automations";
import { useHA } from "haService"; import { useHA } from "haService";
import { ModalState } from "./board/types"; import { ModalState } from "./board/types";
@@ -17,7 +17,9 @@ export const DAGAutomationGraph: FC<{
onTriggerUpdate: (t: AutomationTrigger[]) => void; onTriggerUpdate: (t: AutomationTrigger[]) => void;
onConditionUpdate: (c: AutomationCondition[]) => void; onConditionUpdate: (c: AutomationCondition[]) => void;
isFlipped: boolean; isFlipped: boolean;
additionalControls?: ReactNode;
}> = (props) => { }> = (props) => {
console.log({ props });
const { namer } = useHA(); const { namer } = useHA();
const [modalState, setModalState] = const [modalState, setModalState] =
useState<ModalState | undefined>(undefined); useState<ModalState | undefined>(undefined);
@@ -62,6 +64,7 @@ export const DAGAutomationGraph: FC<{
elements: elementData, elements: elementData,
}, },
}} }}
additionalControls={props.additionalControls}
/> />
); );
}; };
@@ -71,11 +71,11 @@ export const CollectionNode: FC<CollectionNodeProps> = ({
<div className="collection-nodes--inner"> <div className="collection-nodes--inner">
{nodes.map((n, i) => ( {nodes.map((n, i) => (
<SequenceNodeElement <SequenceNodeElement
{...n}
{...sequenceNode}
key={i} key={i}
color={color} color={color}
flipped={flipped} flipped={flipped}
{...n}
{...sequenceNode}
/> />
))} ))}
</div> </div>
@@ -6,6 +6,7 @@ import { AutomationActionData } from "types/automations";
export type CollectionNodeChildProps = Partial<SequenceNodeActions> & { export type CollectionNodeChildProps = Partial<SequenceNodeActions> & {
enabled: boolean; enabled: boolean;
label: ReactNode; label: ReactNode;
color?: SequenceNodeColor;
}; };
export type CollectionNodeDataProps = Size & { export type CollectionNodeDataProps = Size & {
nodes: CollectionNodeChildProps[]; nodes: CollectionNodeChildProps[];
@@ -1,6 +1,6 @@
import { ReactNode } from "react"; import { ReactNode } from "react";
export type SequenceNodeColor = "red" | "blue" | "green" | "lblue"; export type SequenceNodeColor = "red" | "blue" | "green" | "lblue" | "error";
export type SequenceNodeOnMove<Direction extends string> = Record< export type SequenceNodeOnMove<Direction extends string> = Record<
Direction, Direction,
() => void () => void
@@ -11,6 +11,8 @@ export const useSequenceNodeColor = (color: SequenceNodeColor): string => {
: color === "lblue" : color === "lblue"
? theme.palette.info.light ? theme.palette.info.light
: color === "red" : color === "red"
? theme.palette.warning.dark
: color === "error"
? theme.palette.error.dark ? theme.palette.error.dark
: "none"; : "none";
}; };
@@ -5,7 +5,10 @@ import {
import { ModalState } from "../board/types"; import { ModalState } from "../board/types";
import { SequenceNodeActions } from "../nodes/SequenceNode/types"; import { SequenceNodeActions } from "../nodes/SequenceNode/types";
import { DAGUpdaterArgs, DAGUpdaterInput } from "./types"; import { DAGUpdaterArgs, DAGUpdaterInput } from "./types";
import { mapAutoActionKeyToNodeType } from "./util"; import {
convertChooseActionToOrignal,
mapAutoActionKeyToNodeType,
} from "./util";
import { import {
ChooseAction, ChooseAction,
RepeatAction, RepeatAction,
@@ -172,7 +175,9 @@ export const createUpdater = (
}; };
}, },
createChoosNodeUpdater(i: number, j: number | "else") { createChoosNodeUpdater(i: number, j: number | "else") {
const node = args.sequence.data[i] as ChooseAction; const node = convertChooseActionToOrignal(
args.sequence.data[i] as ChooseAction
);
if (j === "else") { if (j === "else") {
return { return {
stateUpdater: createUpdater({ stateUpdater: createUpdater({
@@ -1,4 +1,5 @@
import { AutomationActionData, AutomationNodeTypes } from "types/automations"; import { AutomationActionData, AutomationNodeTypes } from "types/automations";
import { ChooseAction, OriginalChooseAction } from "types/automations/actions";
export const mapAutoActionKeyToNodeType = ( export const mapAutoActionKeyToNodeType = (
k: keyof AutomationActionData k: keyof AutomationActionData
@@ -8,3 +9,21 @@ export const mapAutoActionKeyToNodeType = (
: k === "trigger" : k === "trigger"
? ["trigger"] ? ["trigger"]
: ["action", "condition"]; : ["action", "condition"];
export const convertChooseActionToOrignal = (
node: ChooseAction
): OriginalChooseAction => {
if ("if" in node) {
return {
choose: [
{
conditions: node.if,
sequence: node.then,
},
],
default: node.else,
};
} else {
return node;
}
};
+2 -2
View File
@@ -16,10 +16,10 @@ export const InputArea: FC<InputAreaProps> = (props) => {
return ( return (
<InputAutoComplete <InputAutoComplete
{...props} {...props}
validateOption={(v) => areas.validateOptions(v)} label={props.label ?? "Area"}
options={areas.getOptions()}
getID={areas.getID} getID={areas.getID}
getLabel={areas.getLabel} getLabel={areas.getLabel}
options={areas.getOptions()}
onlyShowLabel onlyShowLabel
/> />
); );
+1 -1
View File
@@ -13,7 +13,7 @@ export const InputDevice: FC<InputDeviceProps> = (props) => {
return ( return (
<InputAutoComplete <InputAutoComplete
{...props} {...props}
label={props.label ?? "Device ID"} label={props.label ?? "Device"}
getID={dr.getID} getID={dr.getID}
getLabel={dr.getLabel} getLabel={dr.getLabel}
options={dr.getOptions()} options={dr.getOptions()}
@@ -10,6 +10,8 @@ export type InputEntityProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[]; restrictToDomain?: string[];
restrictedIntegrations?: string[]; restrictedIntegrations?: string[];
preSelectedEntityIds?: string[]; preSelectedEntityIds?: string[];
restrictedDeviceClass?: string[];
restrictMode?: "and" | "or";
}; };
export const InputEntity: FC<InputEntityProps> = (props) => { export const InputEntity: FC<InputEntityProps> = (props) => {
@@ -17,7 +19,9 @@ export const InputEntity: FC<InputEntityProps> = (props) => {
const entities = useHAEntities(); const entities = useHAEntities();
let options = entities.getOptions( let options = entities.getOptions(
props.restrictToDomain, props.restrictToDomain,
props.restrictedIntegrations props.restrictedIntegrations,
props.restrictedDeviceClass,
props.restrictMode ?? "and"
); );
if (props.preSelectedEntityIds) { if (props.preSelectedEntityIds) {
options = options.filter((opt) => options = options.filter((opt) =>
@@ -0,0 +1,15 @@
.MuiMenuItem-root.input-list--menu-item {
display: inherit;
}
.input-list--menu-item .input-list--menu-item--description {
font-size: 0.75em;
max-width: 80vw;
overflow: hidden;
text-overflow: ellipsis;
overflow-wrap: break-word;
}
.MuiSelect-select .input-list--menu-item--description {
display: none;
}
+17 -3
View File
@@ -1,3 +1,5 @@
import "./InputList.css";
import FormHelperText from "@mui/material/FormHelperText"; import FormHelperText from "@mui/material/FormHelperText";
import InputLabel from "@mui/material/InputLabel"; import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem"; import MenuItem from "@mui/material/MenuItem";
@@ -15,11 +17,13 @@ export type Props<T extends string | Object> = {
className?: string; className?: string;
prettyOptionLabels?: boolean; prettyOptionLabels?: boolean;
getKey?: (n: T) => string; getKey?: (n: T) => string;
getDescription?: (n: T) => string;
placeholder?: any; placeholder?: any;
title?: string; title?: string;
helperText?: string; helperText?: string;
endAdornment?: ReactNode; endAdornment?: ReactNode;
disabled?: boolean; disabled?: boolean;
fullWidth?: boolean;
}; };
export function InputList<T extends string | Object>({ export function InputList<T extends string | Object>({
current, current,
@@ -30,11 +34,13 @@ export function InputList<T extends string | Object>({
className, className,
prettyOptionLabels = true, prettyOptionLabels = true,
getKey = String, getKey = String,
getDescription,
placeholder, placeholder,
title, title,
helperText, helperText,
endAdornment, endAdornment,
disabled, disabled,
fullWidth = true,
}: Props<T>) { }: Props<T>) {
const invalidCurrent = const invalidCurrent =
current && !options.map(getKey).includes(getKey(current)); current && !options.map(getKey).includes(getKey(current));
@@ -43,7 +49,7 @@ export function InputList<T extends string | Object>({
className={className} className={className}
variant="filled" variant="filled"
sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }} sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}
fullWidth fullWidth={fullWidth}
disabled={disabled} disabled={disabled}
> >
<InputLabel>{label}</InputLabel> <InputLabel>{label}</InputLabel>
@@ -62,12 +68,20 @@ export function InputList<T extends string | Object>({
label={label} label={label}
variant="filled" variant="filled"
error={invalidCurrent} error={invalidCurrent}
fullWidth fullWidth={fullWidth}
disabled={disabled} disabled={disabled}
> >
{options.map((t, i) => ( {options.map((t, i) => (
<MenuItem key={i} value={getKey(t)}> <MenuItem key={i} value={getKey(t)} className="input-list--menu-item">
{prettyOptionLabels ? prettyName(getKey(t)) : getKey(t)} {prettyOptionLabels ? prettyName(getKey(t)) : getKey(t)}
{!!getDescription && (
<>
<br />
<div className="input-list--menu-item--description">
{getDescription(t)}
</div>
</>
)}
</MenuItem> </MenuItem>
))} ))}
</Select> </Select>
+1 -1
View File
@@ -4,7 +4,7 @@ import TextField from "@mui/material/TextField";
export interface Props { export interface Props {
textBoxFor?: string; textBoxFor?: string;
label: string | JSX.Element; label?: string | JSX.Element;
value: string; value: string;
onChange: (v: string) => void; onChange: (v: string) => void;
onEnter?: () => void; onEnter?: () => void;
@@ -0,0 +1,50 @@
.input-text-view {
max-height: 2em;
}
.input-text-view.view span {
height: 100%;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
word-wrap: break-word;
line-break: loose;
overflow-wrap: break-word;
}
.input-text-view.edit .MuiFilledInput-input {
padding-top: 0.5em;
padding-bottom: 0.5em;
}
.input-text-view.edit .MuiSvgIcon-root {
color: var(--mui-primary-light);
}
.input-text-view.edit .MuiSvgIcon-root:hover {
cursor: pointer;
color: var(--mui-primary-main);
}
.input-text-view.view .input-text-view--placeholder {
color: var(--mui-grey-500);
font-style: italic;
}
.input-text-view.view {
display: flex;
align-items: center;
gap: 0.25em;
cursor: text;
}
.input-text-view.view .input-text-view--edit {
font-size: 0.75em;
}
.input-text-view.view .input-text-view--edit:hover {
transform: rotate(15deg);
cursor: pointer;
}
@@ -0,0 +1,30 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import InputText from "./InputText";
import { InputTextView } from "./InputTextView";
export default {
title: "Inputs/InputTextView",
component: InputTextView,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
value: "example",
},
} as ComponentMeta<typeof InputTextView>;
export const Basic: ComponentStory<typeof InputTextView> = (args) => (
<Page>
<div
style={{
display: "flex",
flexDirection: "column",
gap: "1em",
padding: "1em",
}}
>
<InputTextView {...args} />
<InputText {...args} />
</div>
</Page>
);
@@ -0,0 +1,54 @@
import "./InputTextView.css";
import { FC, useState } from "react";
import CheckCircleOutlineOutlinedIcon from "@mui/icons-material/CheckCircleOutlineOutlined";
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
import TextField from "@mui/material/TextField";
export type InputTextViewProps = {
className?: string;
value: string;
onChange: (t: string) => void;
initialViewMode?: boolean;
placeholder?: string;
};
export const InputTextView: FC<InputTextViewProps> = (props) => {
const [viewMode, setViewMode] = useState(props.initialViewMode ?? true);
const className = [
"input-text-view",
viewMode ? "view" : "edit",
props.className ?? "",
].join(" ");
if (viewMode) {
return (
<div className={className} onClick={() => setViewMode(false)}>
{!!props.value ? (
<span>{props.value}</span>
) : (
<span className="input-text-view--placeholder">
{props.placeholder}
</span>
)}
<ModeEditOutlineOutlinedIcon className="input-text-view--edit" />
</div>
);
} else {
return (
<TextField
className={className}
placeholder={props.placeholder}
variant="filled"
value={props.value}
onChange={(e) => props.onChange(e.target.value)}
InputProps={{
endAdornment: (
<CheckCircleOutlineOutlinedIcon onClick={() => setViewMode(true)} />
),
}}
/>
);
}
};
@@ -6,29 +6,35 @@ import { AutomationTime } from "types/automations/common";
import { InputTime } from "./InputTime"; import { InputTime } from "./InputTime";
export default { export default {
title: 'Inputs/InputTime', title: "Inputs/InputTime",
component: InputTime, component: InputTime,
parameters: { actions: { argTypesRegex: '^on.*' } }, parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof InputTime>; } as ComponentMeta<typeof InputTime>;
const Template: ComponentStory<typeof InputTime> = (args) => {
const Template: ComponentStory<typeof InputTime> = args => {
const [value, setValue] = useState<AutomationTime | undefined>(undefined); const [value, setValue] = useState<AutomationTime | undefined>(undefined);
return <Page> return (
<div style={{ <Page>
padding: '1em' <div
}}> style={{
<InputTime {...args} value={value} onChange={t => { padding: "1em",
setValue(t) }}
args.onChange(t) >
}} /> <InputTime
</div> {...args}
</Page> value={args.restrictEmpty ? "00:00:00" : value}
} onChange={(t) => {
setValue(t);
args.onChange(t);
}}
/>
</div>
</Page>
);
};
export const SimpleText = Template.bind({}) export const SimpleText = Template.bind({});
SimpleText.args = { SimpleText.args = {
label: "Time Stamp", label: "Time Stamp",
value: "10" value: "10",
} };
+11 -8
View File
@@ -19,13 +19,14 @@ const fields: Array<keyof AutomationTimeObject> = [
"seconds", "seconds",
"milliseconds", "milliseconds",
]; ];
export interface Props { export type InputTimeProps = {
label: string; label: string;
value?: AutomationTime;
onChange: (v?: AutomationTimeObject) => void; onChange: (v?: AutomationTimeObject) => void;
className?: string; className?: string;
} value?: AutomationTime;
export const InputTime: FC<Props> = (props) => { restrictEmpty?: boolean;
};
export const InputTime: FC<InputTimeProps> = (props) => {
// state // state
const [disabled, setDisabled] = useState(!props.value); const [disabled, setDisabled] = useState(!props.value);
const [displayValue, setDisplayValue] = useState( const [displayValue, setDisplayValue] = useState(
@@ -140,10 +141,12 @@ export const InputTime: FC<Props> = (props) => {
onChange={(e) => updateOne(name)(e.target.value)} onChange={(e) => updateOne(name)(e.target.value)}
/> />
))} ))}
<ButtonIcon {!props.restrictEmpty && (
onClick={() => setDisabled(!disabled)} <ButtonIcon
icon={disabled ? <EditIcon /> : <CloseIcon />} onClick={() => setDisabled(!disabled)}
/> icon={disabled ? <EditIcon /> : <CloseIcon />}
/>
)}
</div> </div>
</div> </div>
); );
@@ -0,0 +1,21 @@
.input-time-entity {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
gap: 0.5em;
}
.input-time-entity button.MuiButtonBase-root {
border-color: var(--mui-info-light);
background-color: var(--mui-info-main);
color: var(--mui-info-contrastText);
}
.input-time-entity button.MuiButtonBase-root:hover {
background-color: var(--mui-info-light);
}
.input-time-entity .input-autocomplete {
min-width: 10em;
}
@@ -0,0 +1,35 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { InputTimeEntity } from "./InputTimeEntity";
export default {
title: "Inputs/InputTimeEntity",
component: InputTimeEntity,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof InputTimeEntity>;
const Template: ComponentStory<typeof InputTimeEntity> = (args) => {
const [value, setValue] = useState("");
return (
<Page>
<div
style={{
padding: "1em",
}}
>
<InputTimeEntity
{...args}
value={value}
onChange={(t) => {
setValue(t);
args.onChange(t);
}}
/>
</div>
</Page>
);
};
export const SimpleText = Template.bind({});
@@ -0,0 +1,68 @@
import "./InputTimeEntity.css";
import { FC, ReactNode } from "react";
import AccessTimeOutlinedIcon from "@mui/icons-material/AccessTimeOutlined";
import MoreTimeOutlinedIcon from "@mui/icons-material/MoreTimeOutlined";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import {
convertObjectToAutomationTimeString,
isAutomationTimeString24Hours,
} from "utils/time";
import { InputEntity } from "./InputEntities";
import { InputTime } from "./InputTime";
export type InputTimeEntityProps = {
value: string;
onChange: (v: string) => void;
className?: string;
};
export const InputTimeEntity: FC<InputTimeEntityProps> = ({
value,
onChange,
className = "",
}) => {
const is24Hour = isAutomationTimeString24Hours(value);
let editor: ReactNode;
if (is24Hour) {
editor = (
<InputTime
label=""
value={value ?? "00:00:00"}
restrictEmpty
onChange={(t) =>
onChange(t ? convertObjectToAutomationTimeString(t) : "00:00:00")
}
/>
);
} else {
editor = (
<InputEntity
label="Time Entity"
restrictMode="or"
restrictedDeviceClass={["timestamp"]}
restrictToDomain={["input_datetime"]}
value={value}
multiple={false}
onChange={(t) => onChange(t ?? "")}
/>
);
}
return (
<div className={"input-time-entity " + className}>
{editor}{" "}
<ButtonIcon
icon={is24Hour ? <AccessTimeOutlinedIcon /> : <MoreTimeOutlinedIcon />}
onClick={() => {
if (is24Hour) {
onChange("");
} else {
onChange("00:00:00");
}
}}
/>
</div>
);
};
@@ -1,4 +1,3 @@
import InputYaml from "components/Inputs/InputYaml";
import { ParallelAction } from "types/automations/actions"; import { ParallelAction } from "types/automations/actions";
import { OptionManager } from "./OptionManager"; import { OptionManager } from "./OptionManager";
@@ -8,15 +7,7 @@ export const ActionParallelState: OptionManager<ParallelAction> = {
parallel: [], parallel: [],
}), }),
isReady: () => true, isReady: () => true,
Component: ({ state, setState }) => { Component: () => {
return ( return <></>;
<>
<InputYaml
label="Actions"
value={state.parallel ?? []}
onChange={(parallel) => setState({ ...state, parallel })}
/>
</>
);
}, },
}; };
@@ -0,0 +1,59 @@
.trigger-time--help {
margin-top: 0.5em;
display: flex;
flex-direction: row;
gap: 0.5em;
flex-wrap: wrap;
justify-content: flex-start;
align-items: center;
}
.trigger-time--help .text {
word-wrap: break-word;
flex-wrap: wrap;
overflow: hidden;
text-overflow: clip;
cursor: pointer;
padding: 0.5em 0.75em;
max-width: 40em;
}
.trigger-time--help .text a {
color: var(--mui-info-light);
}
.trigger-time--help .text a:hover {
color: var(--mui-info-main);
border-radius: 10px;
text-decoration: underline;
}
.trigger-time--help .trigger-time--mode-selection {
width: 10em;
}
.trigger-time--pattern {
display: flex;
flex-direction: row;
gap: 0.5em;
margin-top: 0.5em;
}
.trigger-time--exact {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.25em;
}
.trigger-time--exact .add {
border-color: var(--mui-info-light);
color: var(--mui-info-contrastText);
background-color: var(--mui-info-main);
}
.trigger-time--exact .add:hover {
border-color: var(--mui-info-light);
color: var(--mui-info-main);
background-color: var(--mui-info-contrastText);
}
@@ -1,25 +1,151 @@
import { OptionManager } from './OptionManager'; import "./TriggerTime.css";
import { AutomationTriggerTime } from 'types/automations/triggers';
import { InputTime } from 'components/Inputs/InputTime';
import { convertObjectToAutomationTimeString } from 'utils/time';
import HelpOutlinedIcon from "@mui/icons-material/HelpOutlined";
import { OptionManager } from "./OptionManager";
import {
AutomationTriggerTime,
AutomationTriggerExactTime,
AutomationTriggerTimePattern,
} from "types/automations/triggers";
import InputText from "components/Inputs/InputText";
import { FC } from "react";
import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button";
import { useState } from "react";
import AddIcon from "@mui/icons-material/Add";
import { InputTimeEntity } from "components/Inputs/InputTimeEntity";
export const TriggerTime: OptionManager<AutomationTriggerTime> = { export const TriggerTime: OptionManager<AutomationTriggerTime> = {
defaultState: () => ({ defaultState: () => ({
"platform": 'time', platform: "time",
"at": "", at: "00:00:00",
}), }),
isReady: () => true, isReady: () => true,
renderOptionList: (state, setState) => { Component: ({ state, setState }) => {
return <> const [showHelp, setHelp] = useState(false);
<InputTime const setTimeType = (t: AutomationTriggerTime["platform"]) => {
label="At" if (t === "time") {
value={state.at} setState({
onChange={_at => setState({ platform: "time",
...state, at: ["00:00:00"],
at: _at ? convertObjectToAutomationTimeString(_at) : "00:00:00", });
})} } else {
setState({
platform: "time_pattern",
});
}
};
return (
<>
<div className="trigger-time--help">
<InputList
className="trigger-time--mode-selection"
label="Mode"
current={state.platform}
onChange={setTimeType}
options={["time", "time_pattern"]}
/>
{state.platform === "time_pattern" && (
<>
<Button onClick={() => setHelp(!showHelp)}>
<HelpOutlinedIcon /> Help
</Button>
</>
)}
{state.platform === "time_pattern" && showHelp && (
<div className="text">
You can prefix the value with a "/" to match whenever the value is
divisible by that number. You can specify "*" to match any value.{" "}
<a
href="https://www.home-assistant.io/docs/automation/trigger/#time-pattern-trigger"
target="_blank" rel="noreferrer"
>
More Info.
</a>
</div>
)}
</div>
{state.platform === "time_pattern" ? (
<TriggerTimePattern state={state as any} setState={setState} />
) : (
<TriggerExactTime state={state as any} setState={setState} />
)}
</>
);
},
};
export const TriggerExactTime: FC<{
state: AutomationTriggerExactTime;
setState: (t: AutomationTriggerExactTime) => void;
}> = ({ state, setState }) => {
const times = Array.isArray(state.at) ? state.at : [state.at];
const update = (t: string, i: number) =>
setState({
...state,
at: [...times.slice(0, i), t, ...times.slice(i + 1)],
});
const add = () =>
setState({
...state,
at: [...times, "00:00:00"],
});
return (
<div className="trigger-time--exact">
{times.map((v, i) => {
return (
<InputTimeEntity
key={i}
className="trigger-time--exact--option"
value={v ?? ""}
onChange={(t) => update(t, i)}
/>
);
})}
<Button onClick={add} className="add">
<AddIcon />
</Button>
</div>
);
};
export const TriggerTimePattern: FC<{
state: AutomationTriggerTimePattern;
setState: (t: AutomationTriggerTimePattern) => void;
}> = ({ state, setState }) => {
return (
<div className="trigger-time--pattern">
<InputText
label="Hours"
value={state.hours ?? ""}
onChange={(hours) =>
setState({
...state,
hours,
})
}
/> />
</> <InputText
} label="Minutes"
} value={state.minutes ?? ""}
onChange={(minutes) =>
setState({
...state,
minutes,
})
}
/>
<InputText
label="Seconds"
value={state.seconds ?? ""}
onChange={(seconds) =>
setState({
...state,
seconds,
})
}
/>
</div>
);
};
@@ -1,27 +0,0 @@
import { OptionManager } from './OptionManager';
import { AutomationTriggerTimePattern } from 'types/automations/triggers';
import InputText from 'components/Inputs/InputText';
export const TriggerTimePattern: OptionManager<AutomationTriggerTimePattern> = {
defaultState: () => ({
"platform": 'time_pattern',
}),
isReady: () => true,
renderOptionList: (state, setState) => {
return <>
<InputText label="Hours" value={state.hours ?? ""} onChange={hours => setState({
...state,
hours
})} />
<InputText label="Minutes" value={state.minutes ?? ""} onChange={minutes => setState({
...state,
minutes
})} />
<InputText label="Seconds" value={state.seconds ?? ""} onChange={seconds => setState({
...state,
seconds
})} />
</>
}
}
@@ -15,7 +15,6 @@ import { TriggerNumericState } from "./TriggerNumericState";
import { TriggerState } from "./TriggerState"; import { TriggerState } from "./TriggerState";
import { TriggerTemplate } from "./TriggerTemplate"; import { TriggerTemplate } from "./TriggerTemplate";
import { TriggerTime } from "./TriggerTime"; import { TriggerTime } from "./TriggerTime";
import { TriggerTimePattern } from "./TriggerTimePattern";
import { TriggerWebhook } from "./TriggerWebhook"; import { TriggerWebhook } from "./TriggerWebhook";
import { TriggerZone } from "./TriggerZone"; import { TriggerZone } from "./TriggerZone";
import { TriggerDevice } from "./TriggerDevice"; import { TriggerDevice } from "./TriggerDevice";
@@ -67,8 +66,6 @@ export const getOptionManager = <T extends AutomationNodeTypes>(
return TriggerTemplate; return TriggerTemplate;
case "time": case "time":
return TriggerTime; return TriggerTime;
case "time_pattern":
return TriggerTimePattern;
case "webhook": case "webhook":
return TriggerWebhook; return TriggerWebhook;
case "zone": case "zone":
+3 -1
View File
@@ -7,6 +7,7 @@ import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Button";
import InputBoolean from "components/Inputs/InputBoolean"; import InputBoolean from "components/Inputs/InputBoolean";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { getNodeSubTypeDescription } from "./utils";
export interface NodeEditorProps { export interface NodeEditorProps {
node: AutomationNode; node: AutomationNode;
@@ -96,7 +97,8 @@ export const NodeEditor: FC<NodeEditorProps> = ({
{state.nodeType !== "condition" ? ( {state.nodeType !== "condition" ? (
<InputList <InputList
label={state.prettyNodeType} label={state.prettyNodeType}
current={state.subType as any} current={state.subType}
getDescription={getNodeSubTypeDescription}
options={state.subTypes} options={state.subTypes}
onChange={state.setSubType} onChange={state.setSubType}
prettyOptionLabels prettyOptionLabels
+17
View File
@@ -0,0 +1,17 @@
import { AutomationNodeSubtype } from "types/automations";
const subtypeDescMap: Partial<Record<AutomationNodeSubtype, string>> = {
choose: "create conditional if/else statements",
parallel: "run multiple nodes at the same time",
stop: "stop the automation with a status code",
wait: "wait based on a condition",
repeat: "repeat a sequence until or while some conditions are met",
device: "device related actions",
service: "call a service",
};
export const getNodeSubTypeDescription = (
nst: AutomationNodeSubtype
): string => {
return subtypeDescMap[nst] ?? "";
};
+23 -6
View File
@@ -2,14 +2,31 @@ import { FC } from "react";
export const SimpleErrorElement: FC<{ error: Error }> = ({ error }) => { export const SimpleErrorElement: FC<{ error: Error }> = ({ error }) => {
return ( return (
<> <div
<b>{error?.name}</b> style={{
padding: "1em",
}}
>
<b>Error Name</b>: {error?.name}
<br /> <br />
<b>{error?.message}</b> <b>Error Message</b>
{error?.message}
<br /> <br />
<span>{error?.stack}</span> <b>Error Stack</b>
<code
style={{
display: "flex",
flexDirection: "column",
padding: "1em",
}}
>
{error?.stack?.split("\n").map((t, i) => (
<span key={i}>{t}</span>
))}
</code>
<br /> <br />
<span>{JSON.stringify(error)}</span> <b>JSON:</b>
</> <code>{JSON.stringify(error)}</code>
</div>
); );
}; };
+3 -37
View File
@@ -85,42 +85,6 @@ export const useHAAreas = () => {
} }
return true; return true;
}, },
validateOptions(
options: string[],
restrictedDomains?: string[],
restrictedIntegrations?: string[]
): null | string[] {
let out = options;
if (restrictedDomains) {
const domains = restrictedDomains.map((x) => x.toLowerCase());
const domainsStr =
domains.length > 1
? `one of "${domains.join(", ")}"`
: `"${domains[0]}"`;
out = out.reduce<string[]>((all = [], areaId) => {
if (!methods.areaHasEntityDomain(areaId, domains)) {
return [...all, `${methods.getLabel(areaId)} is not ${domainsStr}`];
}
return all;
}, []);
} else if (restrictedIntegrations) {
const integrations = restrictedIntegrations.map((x) => x.toLowerCase());
const domainsStr =
integrations.length > 1
? `one of "${integrations.join(", ")}"`
: `"${integrations[0]}"`;
out = out.reduce<string[]>((all = [], areaId) => {
if (!methods.areaHasEntityIntegration(areaId, integrations)) {
return [...all, `${methods.getLabel(areaId)} is not ${domainsStr}`];
}
return all;
}, []);
}
if (out.length > 0) {
return out;
}
return null;
},
getBaseOption(opt: AreaOption): AreaBaseOption { getBaseOption(opt: AreaOption): AreaBaseOption {
if (!areas.ready) { if (!areas.ready) {
throw new Error("Not Ready!"); throw new Error("Not Ready!");
@@ -161,7 +125,9 @@ export const useHAAreas = () => {
getLabel: (opt: AreaOption): string => { getLabel: (opt: AreaOption): string => {
if (typeof opt === "string") { if (typeof opt === "string") {
if (areas.ready) { if (areas.ready) {
return areas.collection.state[opt].name ?? prettyName(opt); return areas.collection.state[opt]
? areas.collection.state[opt].name ?? prettyName(opt)
: prettyName(opt);
} }
return opt; return opt;
} }
+72 -25
View File
@@ -106,35 +106,82 @@ export const useHAEntities = () => {
}, },
getOptions( getOptions(
restrictToDomain?: string[], restrictToDomain?: string[],
restrictedIntegrations?: string[] restrictedIntegrations?: string[],
restrictedDeviceClass?: string[],
mode: "and" | "or" = "and"
): EntityOption[] { ): EntityOption[] {
if (!entities.ready) { if (!entities.ready) {
return []; return [];
} }
let keys = Object.keys(entities.collection.state); const deviceClasses = (restrictedDeviceClass ?? []).map((x) =>
if (restrictToDomain) { x.toLowerCase()
const domains = restrictToDomain.map((x) => x.toLowerCase()); );
keys = keys.filter((key) => const domains = (restrictToDomain ?? []).map((x) => x.toLowerCase());
domains.includes(key.toLowerCase().split(".")[0]) const integrations = (restrictedIntegrations ?? []).map((x) =>
); x.toLowerCase()
} );
if (restrictedIntegrations && entitySource.ready) { return Object.keys(entities.collection.state)
const integrations = restrictedIntegrations.map((x) => x.toLowerCase()); .filter((entityId) => {
keys = keys.filter((key) => { if (mode === "and") {
const integration = ( let keep = true;
entitySource.collection.state[key]?.domain ?? "" if (domains.length > 0) {
).toLowerCase(); keep =
return integrations.includes(integration); keep && domains.includes(entityId.toLowerCase().split(".")[0]);
}); }
} if (entitySource.ready && integrations.length > 0) {
return keys.map((key) => ({ keep =
id: key, keep &&
label: entities.collection.state[key].attributes.friendly_name ?? key, integrations.includes(
domain: key.split(".")[0] ?? "n/a", entitySource.collection.state[entityId]?.domain ?? ""
integration: entitySource.ready );
? (entitySource.collection.state[key] ?? {}).domain ?? "n/a" }
: "...", if (deviceClasses.length > 0) {
})); keep =
keep &&
deviceClasses.includes(
entities.collection.state[
entityId
].attributes.device_class?.toLowerCase() ?? ""
);
}
return keep;
} else {
if (
!entitySource.ready &&
deviceClasses.length === 0 &&
domains.length === 0 &&
integrations.length === 0
) {
return true;
}
let keep = false;
keep =
keep || domains.includes(entityId.toLowerCase().split(".")[0]);
if (entitySource.ready) {
keep =
keep ||
integrations.includes(
entitySource.collection.state[entityId]?.domain ?? ""
);
}
keep =
keep ||
deviceClasses.includes(
entities.collection.state[
entityId
].attributes.device_class?.toLowerCase() ?? ""
);
return keep;
}
})
.map((key) => ({
id: key,
label: entities.collection.state[key].attributes.friendly_name ?? key,
domain: key.split(".")[0] ?? "n/a",
integration: entitySource.ready
? (entitySource.collection.state[key] ?? {}).domain ?? "n/a"
: "...",
}));
}, },
getLabel: (opt: EntityOption): string => { getLabel: (opt: EntityOption): string => {
if (typeof opt === "string") { if (typeof opt === "string") {
+5 -1
View File
@@ -209,10 +209,14 @@ export const useHA = () => {
}, },
getEntityName(entity_id, maxEntities = 1) { getEntityName(entity_id, maxEntities = 1) {
if (Array.isArray(entity_id)) { if (Array.isArray(entity_id)) {
return entity_id const out = entity_id
.slice(0, maxEntities) .slice(0, maxEntities)
.map(entities.getLabel) .map(entities.getLabel)
.join(", "); .join(", ");
if (entity_id.length > maxEntities) {
return out + " and more";
}
return out;
} }
return entities.getLabel(entity_id); return entities.getLabel(entity_id);
}, },
+7 -1
View File
@@ -28,13 +28,19 @@ export type DelayAction = st.Infer<typeof v.DelayAction>;
export type FireEventAction = st.Infer<typeof v.FireEventAction>; export type FireEventAction = st.Infer<typeof v.FireEventAction>;
export type DeviceAction = st.Infer<typeof v.DeviceAction>; export type DeviceAction = st.Infer<typeof v.DeviceAction>;
export type StopAction = st.Infer<typeof v.StopAction>; export type StopAction = st.Infer<typeof v.StopAction>;
export type ChooseAction = AutomationActionNodeBase<{ export type ChooseAction = OriginalChooseAction | IfElseAction;
export type OriginalChooseAction = AutomationActionNodeBase<{
choose: Array<{ choose: Array<{
conditions: AutomationCondition[]; conditions: AutomationCondition[];
sequence: AutomationSequenceNode[]; sequence: AutomationSequenceNode[];
}>; }>;
default?: AutomationSequenceNode[]; default?: AutomationSequenceNode[];
}>; }>;
export type IfElseAction = AutomationActionNodeBase<{
if: AutomationCondition[];
then: AutomationSequenceNode[];
else: AutomationSequenceNode[];
}>;
export type ParallelAction = AutomationActionNodeBase<{ export type ParallelAction = AutomationActionNodeBase<{
parallel: Array< parallel: Array<
| AutomationSequenceNode | AutomationSequenceNode
+46 -20
View File
@@ -1,31 +1,57 @@
import * as st from 'superstruct' import * as st from "superstruct";
import * as v from "types/validators/triggers"; import * as v from "types/validators/triggers";
export type AutomationTriggerEvent = st.Infer<typeof v.AutomationTriggerEvent>; export type AutomationTriggerEvent = st.Infer<typeof v.AutomationTriggerEvent>;
export type AutomationTriggerHA = st.Infer<typeof v.AutomationTriggerHA>; export type AutomationTriggerHA = st.Infer<typeof v.AutomationTriggerHA>;
export type AutomationTriggerMQTT = st.Infer<typeof v.AutomationTriggerMQTT>; export type AutomationTriggerMQTT = st.Infer<typeof v.AutomationTriggerMQTT>;
export type AutomationTriggerNumericState = st.Infer<typeof v.AutomationTriggerNumericState>; export type AutomationTriggerNumericState = st.Infer<
typeof v.AutomationTriggerNumericState
>;
export type AutomationTriggerState = st.Infer<typeof v.AutomationTriggerState>; export type AutomationTriggerState = st.Infer<typeof v.AutomationTriggerState>;
export type AutomationTriggerTag = st.Infer<typeof v.AutomationTriggerTag>; export type AutomationTriggerTag = st.Infer<typeof v.AutomationTriggerTag>;
export type AutomationTriggerTemplate = st.Infer<typeof v.AutomationTriggerTemplate>; export type AutomationTriggerTemplate = st.Infer<
typeof v.AutomationTriggerTemplate
>;
export type AutomationTriggerExactTime = st.Infer<
typeof v.AutomationTriggerExactTime
>;
export type AutomationTriggerTime = st.Infer<typeof v.AutomationTriggerTime>; export type AutomationTriggerTime = st.Infer<typeof v.AutomationTriggerTime>;
export type AutomationTriggerTimePattern = st.Infer<typeof v.AutomationTriggerTimePattern>; export type AutomationTriggerTimePattern = st.Infer<
export type AutomationTriggerWebhook = st.Infer<typeof v.AutomationTriggerWebhook>; typeof v.AutomationTriggerTimePattern
>;
export type AutomationTriggerWebhook = st.Infer<
typeof v.AutomationTriggerWebhook
>;
export type AutomationTriggerZone = st.Infer<typeof v.AutomationTriggerZone>; export type AutomationTriggerZone = st.Infer<typeof v.AutomationTriggerZone>;
export type AutomationTriggerDevice = st.Infer<typeof v.AutomationTriggerDevice>; export type AutomationTriggerDevice = st.Infer<
typeof v.AutomationTriggerDevice
>;
export type ActionTriggerMapping = {
homeassistant: AutomationTriggerHA;
device: AutomationTriggerDevice;
event: AutomationTriggerEvent;
mqtt: AutomationTriggerMQTT;
numeric_state: AutomationTriggerNumericState;
state: AutomationTriggerState;
tag: AutomationTriggerTag;
template: AutomationTriggerTemplate;
time: AutomationTriggerTime;
webhook: AutomationTriggerWebhook;
zone: AutomationTriggerZone;
};
export type TriggerType = keyof ActionTriggerMapping;
export type AutomationTrigger = export type AutomationTrigger =
| AutomationTriggerEvent | AutomationTriggerEvent
| AutomationTriggerHA | AutomationTriggerHA
| AutomationTriggerMQTT | AutomationTriggerMQTT
| AutomationTriggerNumericState | AutomationTriggerNumericState
| AutomationTriggerState | AutomationTriggerState
| AutomationTriggerTag | AutomationTriggerTag
| AutomationTriggerTemplate | AutomationTriggerTemplate
| AutomationTriggerTime | AutomationTriggerTime
| AutomationTriggerTimePattern | AutomationTriggerWebhook
| AutomationTriggerWebhook | AutomationTriggerZone
| AutomationTriggerZone | AutomationTriggerDevice;
| AutomationTriggerDevice
;
export type TriggerType = AutomationTrigger['platform'];
+12 -1
View File
@@ -79,7 +79,7 @@ export const StopAction = st.assign(
}) })
); );
export const ChooseAction = st.intersection([ export const OriginalChooseAction = st.intersection([
AutomationActionNodeBase, AutomationActionNodeBase,
st.type({ st.type({
choose: st.array( choose: st.array(
@@ -92,6 +92,17 @@ export const ChooseAction = st.intersection([
}), }),
]); ]);
export const IfElseAction = st.intersection([
AutomationActionNodeBase,
st.type({
if: st.array(st.object()),
then: st.array(st.object()),
else: st.array(st.object()),
}),
]);
export const ChooseAction = st.union([OriginalChooseAction, IfElseAction]);
export const ParallelAction = st.intersection([ export const ParallelAction = st.intersection([
AutomationActionNodeBase, AutomationActionNodeBase,
st.type({ st.type({
+4 -5
View File
@@ -62,17 +62,16 @@ export const TimeCondition = st.assign(
AutomationConditionNodeBase, AutomationConditionNodeBase,
st.type({ st.type({
condition: st.literal("time"), condition: st.literal("time"),
after: st.optional(AutomationTime), after: st.optional(st.string()),
before: st.optional(AutomationTime), before: st.optional(st.string()),
weekday: st.optional(st.union([DayOfWeek, st.array(DayOfWeek)])), weekday: st.optional(st.array(DayOfWeek)),
}) })
); );
export const ZoneCondition = st.assign( export const ZoneCondition = st.assign(
AutomationConditionNodeBase, AutomationConditionNodeBase,
st.type({ st.type({
condition: st.literal("zone"), condition: st.literal("zone"),
zone: st.string(),
entity_id: EntityId, entity_id: EntityId,
state: st.union([st.array(st.string()), st.string()]), zone: st.union([st.array(st.string()), st.string()]),
}) })
); );
+52 -46
View File
@@ -1,55 +1,61 @@
import * as st from "superstruct"; import * as st from "superstruct";
import { AutomationMetadata } from "./metadata"; import { AutomationMetadata } from "./metadata";
import { AutomationData } from './autmation'; import { AutomationData } from "./autmation";
import { getFailures } from './helper'; import { getFailures } from "./helper";
import { AutomationTimeString } from "./common"; import { AutomationTimeString } from "./common";
import { ParallelAction } from "./actions";
test('superstructure is', () => { test("superstructure is", () => {
const badCheck = st.is({}, AutomationMetadata); const badCheck = st.is({}, AutomationMetadata);
expect(badCheck).toBeFalsy() expect(badCheck).toBeFalsy();
}) });
test('getFailures returns failures', () => { test("getFailures returns failures", () => {
const failures = getFailures({ metadata: {} }, AutomationData); const failures = getFailures({ metadata: {} }, AutomationData);
expect(failures).toHaveLength(6) expect(failures).toHaveLength(6);
}) });
test('getFailures returns null', () => { test("getFailures returns null", () => {
const failures = getFailures({ const failures = getFailures(
id: "test", {
alias: "hey", id: "test",
description: "wow", alias: "hey",
mode: "single", description: "wow",
}, AutomationMetadata); mode: "single",
expect(failures).toBeNull() },
}) AutomationMetadata
);
expect(failures).toBeNull();
});
test('AutomationTimeString is valid', () => { test("AutomationTimeString is valid", () => {
for (const c of [ for (const c of ["10:23", "15:02", "13:00:1", "23:00:23"]) {
'10:23', const failures = getFailures(c, AutomationTimeString);
'15:02', expect(failures).toBeNull();
'13:00:1', }
'23:00:23' });
]) {
const failures = getFailures(c, AutomationTimeString)
expect(failures).toBeNull()
}
})
test("AutomationTimeString is invalid", () => {
for (const c of ["xx:23", "1x:02", "13:0a:1c", "25:00:23", "11"]) {
const failures = getFailures(
{
time: c,
},
st.object({
time: AutomationTimeString,
})
);
expect(failures).toHaveLength(1);
}
});
test('AutomationTimeString is invalid', () => { test("Node Validation for parallel", () => {
for (const c of [ expect(
'xx:23', getFailures(
'1x:02', {
'13:0a:1c', parallel: { bad: "me" },
'25:00:23', },
'11' ParallelAction
]) { )
const failures = getFailures({ ).toHaveLength(1);
"time": c });
}, st.object({
time: AutomationTimeString,
}))
expect(failures).toHaveLength(1)
}
})
+7 -3
View File
@@ -1,6 +1,5 @@
import * as st from "superstruct"; import * as st from "superstruct";
import { import {
AutomationTimeString,
AutomationTime, AutomationTime,
AutomationDeviceState, AutomationDeviceState,
} from "./common"; } from "./common";
@@ -67,10 +66,10 @@ export const AutomationTriggerTemplate = st.type({
for: st.optional(AutomationTime), for: st.optional(AutomationTime),
}); });
export const AutomationTriggerTime = st.type({ export const AutomationTriggerExactTime = st.type({
...AutomationTriggerBase, ...AutomationTriggerBase,
platform: st.literal("time"), platform: st.literal("time"),
at: AutomationTimeString, at: st.union([st.string(), st.array(st.string())]),
}); });
export const AutomationTriggerTimePattern = st.type({ export const AutomationTriggerTimePattern = st.type({
@@ -81,6 +80,11 @@ export const AutomationTriggerTimePattern = st.type({
seconds: st.optional(st.string()), seconds: st.optional(st.string()),
}); });
export const AutomationTriggerTime = st.union([
AutomationTriggerExactTime,
AutomationTriggerTimePattern,
]);
export const AutomationTriggerWebhook = st.type({ export const AutomationTriggerWebhook = st.type({
...AutomationTriggerBase, ...AutomationTriggerBase,
platform: st.literal("webhook"), platform: st.literal("webhook"),
+23
View File
@@ -0,0 +1,23 @@
import { validateNode } from "./automations";
test("validate works on bad conditions", () => {
expect(
validateNode(
{
condition: "and",
thisshouldnotbehere: "1",
conditions: "1234",
} as any,
["condition"]
)
).toHaveLength(1);
expect(
validateNode(
{
event: "triggerme",
},
["condition"]
)
).toHaveLength(2);
});
+27 -5
View File
@@ -70,7 +70,6 @@ export const getSubTypeList = <T extends AutomationNodeTypes>(nodeType: T) => {
"state", "state",
"numeric_state", "numeric_state",
"time", "time",
"time_pattern",
"zone", "zone",
"event", "event",
"homeassistant", "homeassistant",
@@ -122,6 +121,9 @@ export const getNodeSubType = <
if ("condition" in node) { if ("condition" in node) {
return node.condition as any; return node.condition as any;
} else if ("platform" in node) { } else if ("platform" in node) {
if (node.platform === "time_pattern") {
return "time" as any;
}
return node.platform as any; return node.platform as any;
} else if ("service" in node) { } else if ("service" in node) {
return "service" as any; return "service" as any;
@@ -133,7 +135,7 @@ export const getNodeSubType = <
return "event" as any; return "event" as any;
} else if ("device_id" in node) { } else if ("device_id" in node) {
return "device" as any; return "device" as any;
} else if ("choose" in node) { } else if ("choose" in node || "if" in node) {
return "choose" as any; return "choose" as any;
} else if ("delay" in node) { } else if ("delay" in node) {
return "wait" as any; return "wait" as any;
@@ -157,7 +159,6 @@ export const TriggerValidators: Record<TriggerType, any> = {
tag: v.triggers.AutomationTriggerTag, tag: v.triggers.AutomationTriggerTag,
template: v.triggers.AutomationTriggerTemplate, template: v.triggers.AutomationTriggerTemplate,
time: v.triggers.AutomationTriggerTime, time: v.triggers.AutomationTriggerTime,
time_pattern: v.triggers.AutomationTriggerTimePattern,
webhook: v.triggers.AutomationTriggerWebhook, webhook: v.triggers.AutomationTriggerWebhook,
zone: v.triggers.AutomationTriggerZone, zone: v.triggers.AutomationTriggerZone,
}; };
@@ -196,6 +197,18 @@ export const validateNode = (
node: AutomationNode, node: AutomationNode,
allowedNodeTypes: AutomationNodeTypes[] = [] allowedNodeTypes: AutomationNodeTypes[] = []
): MiniFailure[] | null => { ): MiniFailure[] | null => {
if (typeof node !== "object") {
return [
{
message: [
`Expected an object but got type of "${typeof node}" = ${JSON.stringify(
node
)}`,
],
path: "$",
},
];
}
let nodeType = getNodeType(node); let nodeType = getNodeType(node);
let errors: MiniFailure[] = []; let errors: MiniFailure[] = [];
if (allowedNodeTypes.length > 0 && !allowedNodeTypes.includes(nodeType)) { if (allowedNodeTypes.length > 0 && !allowedNodeTypes.includes(nodeType)) {
@@ -203,7 +216,7 @@ export const validateNode = (
message: [ message: [
`Got node of type "${nodeType}" but expected one of {${allowedNodeTypes}}`, `Got node of type "${nodeType}" but expected one of {${allowedNodeTypes}}`,
], ],
path: "", path: "$",
}); });
nodeType = allowedNodeTypes[0]; nodeType = allowedNodeTypes[0];
} }
@@ -214,7 +227,16 @@ export const validateNode = (
errors.push({ message: [`Failed to identifiy subtype`], path: "" }); errors.push({ message: [`Failed to identifiy subtype`], path: "" });
} }
if (nodeSubType) { if (nodeSubType) {
const failures = getFailures(node, AllValidators[nodeType][nodeSubType]); const validator = AllValidators[nodeType][nodeSubType];
if (!validator) {
return errors.concat([
{
message: [`"${nodeSubType}" is not a known type for ${nodeType}`],
path: "$",
},
]);
}
const failures = getFailures(node, validator);
if (failures) { if (failures) {
errors = errors.concat(failures); errors = errors.concat(failures);
} }
+26 -3
View File
@@ -41,7 +41,16 @@ export const getDescriptionFromAutomationNode = <
return node.id ?? ""; return node.id ?? "";
} }
if (node.platform === "time") { if (node.platform === "time") {
return node.at; const out = `At `;
if (Array.isArray(node.at)) {
return out + node.at.join(" or ");
}
return out + node.at;
}
if (node.platform === "time_pattern") {
return `At ${node.hours ?? "*"}:${node.minutes ?? "*"}:${
node.seconds ?? "*"
}`;
} }
if (node.platform === "homeassistant") { if (node.platform === "homeassistant") {
if (node.event === "start") { if (node.event === "start") {
@@ -110,7 +119,7 @@ export const getDescriptionFromAutomationNode = <
} }
return "Numeric State Condition"; return "Numeric State Condition";
case "state": case "state":
return `${namer.getEntityName(node.entity_id)} is '${node.state}'`; return `${namer.getEntityName(node.entity_id, 2)} is '${node.state}'`;
case "template": case "template":
return node.value_template; return node.value_template;
case "device": case "device":
@@ -128,6 +137,20 @@ export const getDescriptionFromAutomationNode = <
? `on ${getDescriptionForWeekDay(node.weekday, "or")}` ? `on ${getDescriptionForWeekDay(node.weekday, "or")}`
: ""; : "";
return [before, after, weekday].filter((x) => x).join(", "); return [before, after, weekday].filter((x) => x).join(", ");
case "zone":
let out = "if ";
if (Array.isArray(node.entity_id) && node.entity_id.length > 2) {
out += "multiple people";
} else {
out += namer.getEntityName(node.entity_id, 2);
}
out += " enter ";
if (Array.isArray(node.zone) && node.zone.length > 2) {
out += "multiple people";
} else {
out += namer.getEntityName(node.zone, 2);
}
return out;
default: default:
return JSON.stringify(node); return JSON.stringify(node);
} }
@@ -162,7 +185,7 @@ export const getDescriptionFromAutomationNode = <
if ("device_id" in node) { if ("device_id" in node) {
return getDescriptionForDeviceType(node as any, namer, false); return getDescriptionForDeviceType(node as any, namer, false);
} }
if ("choose" in node) { if ("choose" in node || "if" in node) {
if (allowJs) { if (allowJs) {
return ( return (
<AltRouteOutlinedIcon <AltRouteOutlinedIcon
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more