Compare commits

..
71 Commits
Author SHA1 Message Date
renovate[bot] f061894430 Update dependency types-PyYAML to v6.0.12.20240311 (#185) 2024-05-02 14:08:40 -04:00
renovate[bot] 7769ba00c3 Update dependency fastapi to v0.109.1 [SECURITY] (#188) 2024-05-02 14:07:19 -04:00
renovate[bot] 18241c2057 Update dependency pydantic to v1.10.13 [SECURITY] (#189) 2024-05-02 09:47:50 -04:00
Ari Sosnovsky 8b516d958c Update README.md 2023-12-20 17:51:32 -05:00
Ari Sosnovsky 6422b8d974 Update README.md 2023-12-20 17:50:31 -05:00
dependabot[bot] ee77edea78 Bump deep-object-diff from 1.1.7 to 1.1.9 in /webapp (#171) 2022-11-16 23:52:14 -05:00
dependabot[bot] 4d667d1432 Bump loader-utils from 1.4.0 to 1.4.2 in /webapp (#170) 2022-11-16 23:51:46 -05:00
renovate[bot]andAri Sosnovsky 3df79c17d6 Update dependency @types/react to v18.0.25 (#167)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Ari Sosnovsky <asosnovsky@users.noreply.github.com>
2022-11-06 19:56:18 -05:00
renovate[bot] 5b920d366e Update dependency @types/react-dom to v18.0.8 (#168)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-06 19:55:45 -05:00
renovate[bot] 201912f471 Update dependency material-ui-confirm to v3.0.6 (#165) 2022-10-11 23:42:58 +03:00
renovate[bot] 117595f63f Update dependency @types/react to v18.0.21 (#164) 2022-10-11 23:38:39 +03:00
ari a5aec24686 fix 2022-09-24 15:15:54 -04:00
ari 8a6415a58b linting fix 2022-09-24 15:15:44 -04:00
ari d7ca62afa7 fixed visual bugs 2022-09-24 15:12:22 -04:00
ari 8fea6f1082 Hidable triggers/conditions 2022-09-24 14:24:03 -04:00
ari 51bac6f0e9 v0.7.6 2022-09-07 12:22:44 -04:00
ari 7020c6aee9 silent 2022-09-07 12:10:25 -04:00
ari 41dc77ff4f silencing invalid errors 2022-09-06 20:53:49 -04:00
ari c5cf8edfd6 update notice 2022-09-06 20:38:18 -04:00
ari 2dca59fa3f update notice 2022-09-06 20:38:07 -04:00
ari df95265af0 update notice 2022-09-06 20:38:00 -04:00
ari 78057939da clean up 2022-09-05 15:11:59 -04:00
ari a4a607768a rename 2022-09-05 15:09:41 -04:00
ari a9b2bdb775 minor refactor 2022-09-05 15:06:28 -04:00
ari eee37346ab v0.7.5 2022-09-02 16:06:34 -04:00
ari 6ee7ce8f70 ignoring non yaml 2022-09-02 15:45:16 -04:00
ari 2dfbc31b5d v0.7.3 2022-09-02 10:36:55 -04:00
ari ab4997494d lint 2022-09-02 10:34:16 -04:00
ari 83b1c85043 correct fix 2022-09-02 10:33:52 -04:00
ari 7526b578ba fixed return values from backend 2022-09-02 10:11:38 -04:00
ari c461640957 fixed storybook 2022-09-02 09:45:32 -04:00
ari fd0a0aa0c4 v0.7.1 2022-09-01 21:23:49 -04:00
ari 3aad35fbce fixed up linting 2022-09-01 17:25:56 -04:00
ari 774ebe482a handling missing ids better + more tranlsations 2022-09-01 17:21:00 -04:00
ari 69a9805c02 added random media player to package 2022-09-01 15:29:37 -04:00
ari 418b9704e7 added desc to dockerfile 2022-09-01 15:29:16 -04:00
ari 6dcbf4d0ed fixed up centering bug 2022-09-01 15:29:16 -04:00
awashingmachineandAri Sosnovsky df2e926711 Adds italian translation (#155)
* Adds italian translation

Adds ita.json

* added to userprofile

Co-authored-by: Ari Sosnovsky <asosnovsky@users.noreply.github.com>
2022-09-01 15:11:25 -04:00
Earion f6df4a0718 Updated French translation (#156)
* Update fra.json

For the record I'm a native french speaker, just wanting to propose my minor contribution

* Update fra.json

small changes
2022-09-01 11:17:34 -04:00
Ari Sosnovsky be5f73bcc7 Update bug_report.md 2022-08-31 22:23:58 -04:00
Ari Sosnovsky 7e9a7061b1 Update bug_report.md 2022-08-31 22:23:49 -04:00
ari 65c0ed1b69 v0.7.0 2022-08-31 22:16:07 -04:00
ari b206c50d80 caching again 2022-08-31 21:58:17 -04:00
ari dacc0730fe using hub 2022-08-31 21:43:06 -04:00
ari b102c6df49 correct grouping 2022-08-31 21:38:35 -04:00
ari d5d8468b78 using dockerhub 2022-08-31 21:37:20 -04:00
ari d6ba4bf3f5 grouping actions 2022-08-31 21:33:05 -04:00
renovate[bot] fff33c79d8 Update dependency @types/react to v18.0.18 (#152)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-31 21:26:13 -04:00
renovate[bot] a8b77261db Update dependency @types/jest to v28.1.8 (#151)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-31 21:26:03 -04:00
ari bb93e1e322 using ghcr 2022-08-31 21:25:41 -04:00
ari 61270c1528 using bullseye 2022-08-31 21:16:52 -04:00
ari 20b4b4870d trying new image 2022-08-31 19:03:57 -04:00
ari fa6e46aad0 added continue-on-error 2022-08-31 18:51:58 -04:00
ari b07babf178 really old 2022-08-31 16:28:12 -04:00
ari a4be507f1e using older action 2022-08-31 16:22:11 -04:00
ari 1bd41bb879 disabling buildx 2022-08-31 16:15:52 -04:00
ari 7b5258402a using fix 2022-08-31 16:15:19 -04:00
ari 5f28a5da16 removed strange centering 2022-08-31 16:07:05 -04:00
ari f60bbe8ddd added no cache flag 2022-08-31 15:57:10 -04:00
ari f58966c735 lint 2022-08-31 15:46:08 -04:00
ari 499752e02f using in-memory db 2022-08-31 15:44:52 -04:00
ari 00c234541d lint 2022-08-31 15:19:59 -04:00
ari 2918191541 nicer white mode 2022-08-31 15:18:48 -04:00
ari d890c1aa64 functioning profiles 2022-08-31 15:15:30 -04:00
ari 8985312dd2 added language support 2022-08-30 22:03:40 -04:00
ari 03a735b281 settings -> dark/light mode 2022-08-30 21:50:43 -04:00
ari 416d88b965 added user profile api 2022-08-29 12:51:24 -04:00
ari 95ac286b53 added user profile 2022-08-29 12:51:24 -04:00
ari caad458b48 added some initial work on intl 2022-08-29 12:51:24 -04:00
ari 157efa04b1 added some initial work for int 2022-08-29 12:51:24 -04:00
Ari Sosnovsky d4b0c02111 v0.6.3 (#148)
* Update CHANGELOG.md

* Update config.yaml
2022-08-27 14:28:17 -04:00
208 changed files with 4245 additions and 2185 deletions

No files matched your search

+10
View File
@@ -36,4 +36,14 @@ If applicable, add screenshots to help explain your problem.
- Version [e.g. 22]
**Additional context**
- Home Assistant Version: [e.g. core-2022.5.4]
- Shortumation Version: [e.g. v0.7.0]
- Homeassistant server type: [e.g. raspberry pi 4 / intel nuc]
Add any other context about the problem here.
**Shortumation Logs**
```log
<--- copy here --->
```
+9 -8
View File
@@ -8,6 +8,9 @@ on:
push:
branches:
- main
concurrency:
group: build-${{ github.event.inputs.version || github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
metadata:
runs-on: ubuntu-latest
@@ -15,12 +18,6 @@ jobs:
outputs:
version: ${{ steps.version.outputs.VERSION }}
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
with:
@@ -76,12 +73,14 @@ jobs:
needs:
- metadata
- build-web
permissions:
packages: write
strategy:
matrix:
arch:
- "aarch64"
- "amd64"
- "armhf" # see https://github.com/asosnovsky/Shortumation/issues/147
- "armhf"
- "armv7"
- "i386"
@@ -89,6 +88,9 @@ jobs:
- name: Check out repository
uses: actions/checkout@v3
# - name: Login to Github Container Registry
# run: echo ${{ github.token }} | docker login ghcr.io -u ${{ github.repository_owner }} --password-stdin
- name: Login to DockerHub
uses: docker/login-action@v2.0.0
with:
@@ -103,7 +105,6 @@ jobs:
- name: ${{ matrix.arch }} / ${{ needs.metadata.outputs.version }}
uses: home-assistant/builder@master
continue-on-error: true
with:
args: |
--${{ matrix.arch }} \
+34 -31
View File
@@ -13,12 +13,16 @@ name: "CodeQL"
on:
push:
branches: [ "main" ]
branches: ["main"]
pull_request:
# The branches below must be a subset of the branches above
branches: [ "main" ]
branches: ["main"]
schedule:
- cron: '26 21 * * 2'
- cron: "26 21 * * 2"
concurrency:
group: codeql-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
analyze:
@@ -32,41 +36,40 @@ jobs:
strategy:
fail-fast: false
matrix:
language: [ 'javascript', 'python' ]
language: ["javascript", "python"]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
steps:
- name: Checkout repository
uses: actions/checkout@v3
- 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.
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# 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.
# 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
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# 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
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
+7 -3
View File
@@ -4,17 +4,21 @@
#
# Source repository: https://github.com/actions/dependency-review-action
# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement
name: 'Dependency Review'
name: "Dependency Review"
on: [pull_request]
permissions:
contents: read
concurrency:
group: deprev-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
dependency-review:
runs-on: ubuntu-latest
steps:
- name: 'Checkout Repository'
- name: "Checkout Repository"
uses: actions/checkout@v3
- name: 'Dependency Review'
- name: "Dependency Review"
uses: actions/dependency-review-action@v2
+3
View File
@@ -6,6 +6,9 @@ on:
pull_request:
branches:
- main
concurrency:
group: test-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
metadata:
runs-on: ubuntu-latest
+32 -134
View File
@@ -1,9 +1,38 @@
# Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge)
## [0.6.2] - Patches
## [0.7.6] Bugfixes
- Attempting to increasing websocket file limit
- Support for all !include directives
- Less deadly error for invalid packages with better logs
- Update notification
## [0.7.4] Bugfixes
- Backend now correctly returns unset alias + description
## [0.7.1] Bugfixes + Italian!
- Added support for automations that do not have an `id`
- Added Italian
- Merged grammar fixes for french
- Fixed up strange centering styling bug
- Replaced more non-multilingual texts with multilingual text
## [0.7.0] Configuration Menu / Light Mode / Lang Support
- Added configuration menu
![image](https://user-images.githubusercontent.com/7451445/187817636-311b5a83-4e08-4b6b-b3b8-2e7086ace136.png)
- Experimental light mode
![image](https://user-images.githubusercontent.com/7451445/187817711-c7a8e23c-b9a4-472b-a348-c1492f3c5d56.png)
- First attempt at a french translation
- No longer using sqllite for automation db
## [0.6.3] - Packages Support & Minor UI improvements
- Full split config support for packages and all advance include directives (i.e. !include_dir_named, !include_dir_merge_list etc)
- Updated metadata box to display origin of the file
- Support for inlined automations!
![image](https://user-images.githubusercontent.com/7451445/187043147-15cea23b-0b64-4484-9c87-747998ea9fe6.png)
## [0.6.1] - v0.6.0 Split Config Support & Better Error handling!
@@ -20,11 +49,6 @@
- Better global error capture
![image](https://user-images.githubusercontent.com/7451445/185441268-9dbde36e-b28b-4a13-bd7f-45ae23834e78.png)
## [0.5.3] - Bug Fixes
- Redirecting `/` to `/web` to resolve container install strangeness reported in https://github.com/asosnovsky/Shortumation/issues/125
- Fixed missing flag that caused the automation to explode in https://github.com/asosnovsky/Shortumation/issues/124
## [0.5.2] - Better Controls
- Add automation trigger
@@ -45,11 +69,6 @@
- Websockets now live-refresh when updates occur
## [0.4.0] - Depedency update
- Core dependency updates
- Python port is now dynamically set
## [0.3.4] - Condition/Trigger Editor Upgrades!
- Many condition editor fixes
@@ -66,19 +85,6 @@
![image](https://user-images.githubusercontent.com/7451445/180238004-4b04f13a-77a2-4c4c-9144-963dbc394bf4.png)
## [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
- Added visual support for
@@ -97,113 +103,5 @@
![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png)
## [0.1.22] - Many Visual improvements
- Deprecated several custom components in favor of mui.com
- Device Editor now has support for 99% of diplay types
- Condition Device is implemented
- Improved naming autogen for trigger & choose
## [0.1.21] - Service Editor
- first version of service editor
- reloading automations on save
## [0.1.20] - UI Bugfixes
- Using MUI elements for input time
- Added delay action / wait_on_triggers action
- Added enabled/disabled flag in node editor
- Optional flip vertical during desktop mode
- Fixed up modal clipping
## [0.1.19] - Vertical mobile mode
- in mobile mode we draw the graphs vertically now
## [0.1.17] - Websockets
- Connected to HA main websocket -- now we retrieve real-time information about
- Device names
- Entity names/ids
- Autocomplete for devices and entities
## [0.1.14] - Material UI + Autocomplete
- Brought some Material UI elements for input and text
- Autocomplete for tags
- Using 'id' as alias for trigger (as it seems to break HA otherwise)
- Not using 'alias' for conditions, always auto-generating it (again, this used to break HA)
- Added missing `data` object to service-actions
## [0.1.13] - YAML
- Better YAML
- Rewrote yaml parser/loader to use pyyaml and safe mode
- Cleaned up description vs alias
## [0.1.12] - Less Intense Error Messages
- Added more node-based errors (this way it's easier to see where validations failed)
- Made the validators less strict in order to capture more edge cases that HA supports
- Nicer auto-generated descriptions for some trigger nodes
## [0.1.10] - More Bug Fixes
- Allowing null or undefined values for metadata fields
- Trigger.platform==time will now have the .at property better supported
## [0.1.9] - Fixed up invalid types for various triggers
- Some triggers had invalid types and were causing a false-positive validation
## [0.1.8] - Support for Malformed Automations
- API will no longer error out on missing values or invalid lists
- Frontend has support for displaying bad automations
## [0.1.6] - Mobile Mode
- Improved mobile mode
- Fixed up arrow styles due to typos
- Added selection color
## [0.1.2] - Docker Hub Images
- Publishing images to docker hub is now stable
## [0.0.15] - Publish to dockerhub
- Publishing images to docker hub
## [0.0.14] - Using vanila ha yaml
- Supporing vanilla out of the box HA yaml as oppose to parsing them (no more $smType)
- Conditions have now a more a explicit node
## [0.0.13] - Better Styling with react-flow
- Fixed up styling (using react-flow)
- cleaned up some button styles
## [0.0.12] - Tags
- Added tag management system for automations
## [0.0.11] - Zoom
- Added lazy saving
## [0.0.10] - Zoom
- Introducing Zoom!
## [0.0.9] - First Working Version
- Instalable verion via github
- Initial POC done
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+3 -1
View File
@@ -2,7 +2,7 @@
ARG BUILD_ARCH
# <--- Main Image -->
FROM python:3.10-slim-buster
FROM python:3.10-slim-bullseye
WORKDIR /app
# <--- Post-Build Args -->
@@ -10,6 +10,7 @@ ARG BUILD_VERSION
# <--- Environment Variables -->
ENV BUILD_VERSION $BUILD_VERSION
ENV BUILD_ARCH $BUILD_ARCH
# <--- System Wide Dependencies -->
ENV LANG C.UTF-8
@@ -45,3 +46,4 @@ ENTRYPOINT [ "/app/bin/run.sh" ]
CMD [ "/app" ]
LABEL org.opencontainers.image.source https://github.com/asosnovsky/Shortumation
LABEL org.opencontainers.image.description "A better way to write automations in home-assistant without having to install and run a seperate automation engine!"
+3
View File
@@ -1,3 +1,6 @@
:no_entry: [DEPRECATED] Due to lack of time on my part, this project is no longer being worked on. :( :no_entry: [DEPRECATED]
----
# <img src="logo.png" height="40x"/> Shortumation ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=platsic)
[![Test](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml) [![Build](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml)
+26 -15
View File
@@ -1,20 +1,31 @@
get_index # unused function (src/api/app.py:43)
list_autos # unused function (src/api/routes/automations.py:13)
insert_auto # unused function (src/api/routes/automations.py:28)
update_auto # unused function (src/api/routes/automations.py:32)
delete_auto # unused function (src/api/routes/automations.py:40)
read_details # unused function (src/api/routes/details.py:11)
get_index # unused function (src/api/app.py:41)
list_autos # unused function (src/api/routes/automations.py:14)
insert_auto # unused function (src/api/routes/automations.py:30)
update_auto # unused function (src/api/routes/automations.py:37)
delete_auto # unused function (src/api/routes/automations.py:49)
read_details # unused function (src/api/routes/details.py:12)
read_profile # unused function (src/api/routes/details.py:24)
save_profile # unused function (src/api/routes/details.py:28)
read_ping # unused function (src/api/routes/ping.py:10)
websocket_endpoint # unused function (src/api/routes/socket.py:13)
params # unused variable (src/api/types.py:16)
total_items # unused variable (src/api/types.py:17)
data # unused variable (src/api/types.py:18)
trigger_variables # unused variable (src/automations/types.py:13)
trigger # unused variable (src/automations/types.py:15)
condition # unused variable (src/automations/types.py:16)
action # unused variable (src/automations/types.py:17)
_.to_json # unused method (src/automations/types.py:45)
_.automation_tags # unused property (src/hass_config/loader.py:17)
alias # unused variable (src/automations/types.py:36)
description # unused variable (src/automations/types.py:37)
trigger_variables # unused variable (src/automations/types.py:38)
mode # unused variable (src/automations/types.py:39)
trigger # unused variable (src/automations/types.py:40)
condition # unused variable (src/automations/types.py:41)
action # unused variable (src/automations/types.py:42)
_.to_json # unused method (src/automations/types.py:70)
error_name # unused variable (src/errors.py:22)
error_message # unused variable (src/errors.py:23)
error_traceback # unused variable (src/errors.py:24)
original_error # unused variable (src/errors.py:25)
_.automation_tags # unused property (src/hass_config/loader.py:28)
json_dumps # unused function (src/json_serializer.py:5)
SecretValue # unused class (src/yaml_serializer/__init__.py:40)
EnvVar # unused class (src/yaml_serializer/__init__.py:78)
theme # unused variable (src/user_profile.py:10)
lang # unused variable (src/user_profile.py:11)
flags # unused variable (src/user_profile.py:12)
SecretValue # unused class (src/yaml_serializer/__init__.py:55)
EnvVar # unused class (src/yaml_serializer/__init__.py:193)
+3 -3
View File
@@ -5,8 +5,8 @@ setuptools.setup(
python_requires=">=3.10",
install_requires=[
"PyYAML==6.0",
"fastapi==0.78.0",
"pydantic==1.9.1",
"fastapi==0.109.1",
"pydantic==1.10.13",
"hypercorn==0.13.2",
"python-decouple==3.6",
"websockets==10.3",
@@ -22,7 +22,7 @@ setuptools.setup(
"pre-commit==2.20.0",
"vulture==2.5",
"types-requests==2.28.4",
"types-PyYAML==6.0.11",
"types-PyYAML==6.0.12.20240311",
"requests==2.28.1",
],
},
+4 -6
View File
@@ -3,13 +3,13 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from src.automations.manager import AutomationManager
from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER
from src.hass_config.loader import HassConfig
from .routes import automations, details, ping, socket
def make_app(automation_mgr: AutomationManager) -> FastAPI:
def make_app(hass_config: HassConfig) -> FastAPI:
app = FastAPI()
has_web_folder = (ROOT_FOLDER / "web").exists()
if has_web_folder:
@@ -33,11 +33,9 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
)
app.include_router(ping.router, prefix="/ping")
app.include_router(
automations.make_automation_router(automation_mgr), prefix=f"{API_PREFIX}/automations"
)
app.include_router(
details.make_details_router(automation_mgr.hass_config), prefix=f"{API_PREFIX}/details"
automations.make_automation_router(hass_config), prefix=f"{API_PREFIX}/automations"
)
app.include_router(details.make_details_router(hass_config), prefix=f"{API_PREFIX}/details")
app.include_router(socket.router, prefix=f"{API_PREFIX}/socket")
@app.get("/")
+12 -2
View File
@@ -5,13 +5,15 @@ from src.automations.errors import FailedDeletion
from src.automations.manager import AutomationManager
from src.automations.types import Automation, ExtenededAutomation
from src.errors import ErrorSet
from src.hass_config.loader import HassConfig
def make_automation_router(automations: AutomationManager) -> APIRouter:
def make_automation_router(hass_config: HassConfig) -> APIRouter:
router = APIRouter()
@router.post("/list")
@router.post("/list", response_model_exclude_unset=True, response_model_exclude_none=True)
def list_autos(body: ListParams) -> ListData[ExtenededAutomation]:
automations = AutomationManager(hass_config)
try:
automations.reload()
return ListData(
@@ -27,18 +29,26 @@ def make_automation_router(automations: AutomationManager) -> APIRouter:
@router.post("/item")
def insert_auto(body: Automation):
if body.id is None:
raise HTTPException(status_code=400, detail={"msg": "must contain an id"})
automations = AutomationManager(hass_config)
automations.create(body)
@router.put("/item")
def update_auto(body: ExtenededAutomation):
if body.id is None:
raise HTTPException(status_code=400, detail={"msg": "must contain an id"})
automations = AutomationManager(hass_config)
automations.update(body)
@router.post("/item/tags")
def update_tags(body: UpdateTags):
automations = AutomationManager(hass_config)
automations.update_tags(body.automation_id, body.tags)
@router.delete("/item")
def delete_auto(body: ExtenededAutomation):
automations = AutomationManager(hass_config)
try:
automations.delete(body)
except FailedDeletion as err:
+12 -4
View File
@@ -3,6 +3,7 @@ from fastapi import APIRouter
from src.automations.loader import extract_automation_refs
from src.env import BUILD_VERSION, HASSIO_TOKEN, HASSIO_WS
from src.hass_config import HassConfig
from src.user_profile import UserProfile
def make_details_router(hass_config: HassConfig) -> APIRouter:
@@ -16,10 +17,17 @@ def make_details_router(hass_config: HassConfig) -> APIRouter:
"hassio_url": HASSIO_WS,
"config": hass_config.get_configuration_path(),
"tags": hass_config.get_automation_tags_path(),
"autos": {
config_key: auto_file
for config_key, auto_file in extract_automation_refs(hass_config)
},
"profile": hass_config.get_profile_path(),
"autos": list(map(repr, extract_automation_refs(hass_config))),
}
@router.get("/profile")
def read_profile():
return UserProfile.from_hass_config(hass_config)
@router.put("/profile")
def save_profile(user_profile: UserProfile):
user_profile.save(hass_config)
return {"saved": hass_config.get_profile_path()}
return router
+1 -2
View File
@@ -1,6 +1,5 @@
from src.api.app import make_app
from src.automations.manager import AutomationManager
from src.hass_config import find_hass_config
hass_config = find_hass_config()
app = make_app(AutomationManager(hass_config))
app = make_app(hass_config)
+26 -110
View File
@@ -1,129 +1,45 @@
import base64
import json
import sqlite3
from contextlib import contextmanager
from pathlib import Path
from typing import Iterable, Iterator
from typing import Iterable
from src.logger import get_logger
from .errors import (
DBDataError,
DBError,
DBNoAutomationFound,
RepeatedAutomationId,
)
from .errors import DBNoAutomationFound, RepeatedAutomationId
from .types import ExtenededAutomation
logger = get_logger(__file__)
automations_tbl = "autos"
def encode_auto(auto: ExtenededAutomation) -> str:
return base64.b64encode(
json.dumps(auto.to_primitive(include_tags=True)).encode("utf-8")
).decode("utf-8")
def encode_obj(auto: dict | list) -> str:
return base64.b64encode(json.dumps(auto).encode("utf-8")).decode("utf-8")
def decode_auto(
auto_str: str, source_file: str, source_file_type: str, configuration_key: str
) -> ExtenededAutomation:
return ExtenededAutomation(
source_file=source_file,
source_file_type=source_file_type,
configuration_key=decode_obj(configuration_key), # type: ignore
**decode_obj(auto_str),
)
def decode_obj(obj_str: str) -> dict | list:
return json.loads(base64.b64decode(obj_str.encode("utf-8")).decode("utf-8"))
class AutomationDBConnection:
def __init__(self, db_file: Path) -> None:
self.db_file = db_file
def __init__(self) -> None:
self.db: dict[str, ExtenededAutomation] = {}
self.missing_id_db: list[ExtenededAutomation] = []
def reset(self):
self.db_file.unlink(missing_ok=True)
self.create_db()
@contextmanager
def get_cur(self) -> Iterator[sqlite3.Cursor]:
conn = sqlite3.connect(self.db_file)
cur = conn.cursor()
try:
yield cur
conn.commit()
except sqlite3.DatabaseError as err:
raise DBError(*err.args) from err
finally:
cur.close()
conn.close()
def create_db(self):
with self.get_cur() as cur:
cur.execute(
f"""
CREATE TABLE IF NOT EXISTS {automations_tbl} (
id TEXT NOT NULL PRIMARY KEY,
alias TEXT,
description TEXT,
mode TEXT NOT NULL,
source_file TEXT NOT NULL,
source_file_type TEXT NOT NULL,
configuration_key BLOB NOT NULL,
rest BLOB NOT NULL
);
"""
)
self.db = {}
self.missing_id_db = []
def insert_automations(self, automations: list[ExtenededAutomation]):
with self.get_cur() as cur:
for automation in automations:
try:
cur.execute(
f"""
INSERT INTO {automations_tbl} VALUES (
"{automation.id}",
"{automation.alias}",
"{automation.description}",
"{automation.mode}",
"{automation.source_file}",
"{automation.source_file_type}",
"{encode_obj(automation.configuration_key)}",
"{encode_auto(automation)}"
);
""",
)
except sqlite3.IntegrityError as err:
raise RepeatedAutomationId(
f"automation id '{automation.id}' in '{automation.source_file}' was already seen before. Please check for duplicate automation ids in your files."
) from err
repeated_automations = []
for automation in automations:
if automation.id is None:
self.missing_id_db.append(automation)
elif self.db.get(automation.id, None) is None:
self.db[automation.id] = automation
else:
repeated_automations.append(
f"automation id '{automation.id}' in '{automation.source_file}' was already seen before. Please check for duplicate automation ids in your files."
)
if len(repeated_automations) > 0:
raise RepeatedAutomationId(repeated_automations)
def get_automation(self, automation_id: str) -> ExtenededAutomation:
with self.get_cur() as cur:
cur.execute(
f'SELECT rest, source_file, source_file_type, configuration_key FROM {automations_tbl} WHERE id = "{automation_id}"' # nosec
)
objs = cur.fetchone()
if objs is None:
raise DBNoAutomationFound(automation_id)
[rest, source_file, source_file_type, configuration_key] = objs
return decode_auto(rest, source_file, source_file_type, configuration_key)
if a := self.db.get(automation_id, None):
return a
raise DBNoAutomationFound(automation_id)
def list_automations(self, offset: int, limit: int) -> Iterable[ExtenededAutomation]:
with self.get_cur() as cur:
for [rest, source_file, source_file_type, configuration_key] in cur.execute(
f"SELECT rest, source_file, source_file_type, configuration_key FROM {automations_tbl} LIMIT {limit} OFFSET {offset}" # nosec
):
yield decode_auto(rest, source_file, source_file_type, configuration_key)
for i, auto in enumerate([*self.missing_id_db, *self.db.values()]):
if i >= offset and i < limit + offset:
yield auto
def count_automations(self) -> int:
with self.get_cur() as cur:
return cur.execute(f"SELECT count(id) FROM {automations_tbl}").fetchone()[0] # nosec
return len(self.db)
+4
View File
@@ -17,6 +17,10 @@ class FailedDeletion(AutomationLoaderException):
pass
class InvalidPackage(AutomationLoaderException):
pass
class DBError(Exception):
pass
+69 -51
View File
@@ -1,4 +1,3 @@
from itertools import chain
from pathlib import Path
from typing import Any, Iterator, Tuple, Union
@@ -16,7 +15,7 @@ from src.yaml_serializer import (
)
from ..hass_config.loader import HassConfig
from .errors import InvalidAutomationFile
from .errors import InvalidAutomationFile, InvalidPackage
from .tags import TagManager
from .types import (
AutomationExtractedIter,
@@ -46,7 +45,9 @@ def load_and_iter_automations(
elif isinstance(ref, InlineAutomation):
yield from load_automation_inline_ref(hass_config.root_path, tag_manager, ref)
else:
raise AssertionError(f"ref has an invalid type of {type(ref)} = {ref}")
raise logger.error(
AssertionError(f"ref has an invalid type of {type(ref)} = {ref}")
)
except InvalidAutomationFile as e:
logger.error(e)
@@ -56,12 +57,17 @@ def extract_automation_refs(
) -> AutomationExtractedIter:
found = False
for ref in chain(
extract_automation_root_refs(hass_config), extract_automation_package_refs(hass_config)
):
for ref in extract_automation_root_refs(hass_config):
found = True
yield ref
try:
for ref in extract_automation_package_refs(hass_config):
found = True
yield ref
except InvalidPackage as err:
logger.fatal(err)
if not found:
yield IncludedAutoamtion([""], IncludedYaml(hass_config.root_path / "automations.yaml"))
@@ -80,7 +86,7 @@ def extract_automation_root_refs(
source_file=hass_config.get_configuration_path(),
)
else:
logger.warning(f"found an invalid type in {key}!")
logger.error(f"found an invalid type in {key}!")
def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtractedIter:
@@ -93,7 +99,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
packages,
)
elif isinstance(packages_config, IncludedYamlDirList):
raise AssertionError("cannot configure packages with 'included_dir_list' directive")
raise InvalidPackage("cannot configure packages with 'included_dir_list' directive")
elif isinstance(packages_config, IncludedYamlDirNamed):
packages = packages_config.to_normalized_json(use_path_as_keys=True)
for package_path, package in packages.items():
@@ -109,7 +115,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
package_set,
) in iter(packages_config):
if not isinstance(package_set, dict):
raise AssertionError(
raise InvalidPackage(
f"expected {pacakge_set_path} to be a dictionary but got {type(package_set)}"
)
yield from extract_automation_inline_package_refs(
@@ -124,7 +130,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
packages_config,
)
else:
raise AssertionError("configurations.homeassistant.packages must be a dictionary!")
raise InvalidPackage("configurations.homeassistant.packages must be a dictionary!")
def extract_automation_inline_package_refs(
@@ -134,44 +140,48 @@ def extract_automation_inline_package_refs(
ignore_package_name=False,
) -> AutomationExtractedIter:
for package_name, package_data in packages_config.items():
if isinstance(package_data, IncludedYaml):
package_mapping = package_data.to_normalized_json()
yield from extract_automation_from_package(
package_data=package_mapping,
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif isinstance(package_data, IncludedYamlDirList):
raise NotImplementedError(package_data)
elif isinstance(package_data, IncludedYamlDirNamed):
for package_key_path in package_data.to_normalized_json(True).keys():
if package_key_path.stem == "automation":
yield IncludedAutoamtion(
configuration_key=[package_name], ref=IncludedYaml(package_key_path)
)
elif isinstance(package_data, IncludedYamlDirMergedNamed):
for data_path, data_set in iter(package_data):
logger.info(f"Loading package={package_name}:{type(package_data)} from {package_data}")
try:
if isinstance(package_data, IncludedYaml):
package_mapping = package_data.to_normalized_json()
yield from extract_automation_from_package(
package_data=package_mapping,
package_name=package_name,
package_data=data_set,
source_file=data_path,
prefix_config_keys=[],
ignore_package_name=True,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif isinstance(package_data, dict):
yield from extract_automation_from_package(
package_data=package_data,
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
else:
raise AssertionError(
f"configurations.homeassistant.packages[{package_name}] must be a dictionary!"
)
elif isinstance(package_data, IncludedYamlDirList):
raise NotImplementedError(package_data)
elif isinstance(package_data, IncludedYamlDirNamed):
for package_key_path in package_data.to_normalized_json(True).keys():
if package_key_path.stem == "automation":
yield IncludedAutoamtion(
configuration_key=[package_name], ref=IncludedYaml(package_key_path)
)
elif isinstance(package_data, IncludedYamlDirMergedNamed):
for data_path, data_set in iter(package_data):
yield from extract_automation_from_package(
package_name=package_name,
package_data=data_set,
source_file=data_path,
prefix_config_keys=[],
ignore_package_name=True,
)
elif isinstance(package_data, dict):
yield from extract_automation_from_package(
package_data=package_data,
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif package_data is not None:
raise InvalidPackage(
f"configurations.homeassistant.packages.{package_name} must be a dictionary but got {type(package_data)}!"
)
except InvalidPackage as err:
logger.error(err)
def extract_automation_from_package(
@@ -236,9 +246,11 @@ def load_automation_inline_ref(
) -> Iterator[ExtenededAutomation]:
for auto in inline_automation.automations:
try:
cleaned_automation = clean_automation(auto)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation(
**clean_automation(auto),
tags=tag_manager.get(auto["id"], {}),
**cleaned_automation,
tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=inline_automation.configuration_key,
source_file=str(inline_automation.source_file.resolve().relative_to(root_path)),
source_file_type="inline",
@@ -286,9 +298,11 @@ def load_automation_path(
if isinstance(automations, dict):
try:
cleaned_automation = clean_automation(automations)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation(
**clean_automation(automations),
tags=tag_manager.get(automations["id"], {}),
**cleaned_automation,
tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="obj",
@@ -305,9 +319,11 @@ def load_automation_path(
return
for automation in automations:
try:
cleaned_automation = clean_automation(automation)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation(
**clean_automation(automation),
tags=tag_manager.get(automation["id"], {}),
**cleaned_automation,
tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="list",
@@ -324,6 +340,8 @@ def load_automation_path(
def clean_automation(auto_raw: dict):
return {
**auto_raw,
"alias": auto_raw.get("alias", "") or "",
"description": auto_raw.get("description", "") or "",
"condition": ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))),
"action": ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))),
"trigger": ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))),
+8 -13
View File
@@ -1,8 +1,6 @@
from pathlib import Path
from tempfile import mktemp
from typing import Optional, Union
from src.errors import ErrorSet
from src.errors import ErrorSet, FormattedError
from src.hass_config.loader import HassConfig
from src.logger import get_logger
from src.yaml_serializer import dump_yaml, load_yaml
@@ -13,11 +11,7 @@ from .errors import (
DBError,
InvalidAutomationFile,
)
from .loader import (
get_base_automation_key,
load_and_iter_automations,
load_automation_path,
)
from .loader import get_base_automation_key, load_and_iter_automations
from .tags import TagManager
from .types import Automation, ExtenededAutomation
@@ -28,12 +22,9 @@ class AutomationManager:
def __init__(
self,
hass_config: HassConfig,
db_path: Optional[Path] = None,
) -> None:
if db_path is None:
db_path = Path(mktemp()) # nosec
self.hass_config = hass_config
self.db = AutomationDBConnection(db_path)
self.db = AutomationDBConnection()
self.tag_path = hass_config.get_automation_tags_path()
self.tag_manager = TagManager()
self.reload_tags()
@@ -66,7 +57,7 @@ class AutomationManager:
if len(batch) >= 0:
self.db.insert_automations(batch)
except DBError as e:
logger.warning(e)
logger.warning(FormattedError.from_error(e))
errors.append(e)
if len(errors) > 0:
raise ErrorSet(*errors)
@@ -93,6 +84,8 @@ class AutomationManager:
)
def update(self, automation: ExtenededAutomation, create_if_not_found: bool = False):
if automation.id is None:
raise AssertionError("automation.id must be defined to update!")
automation_path = self.hass_config.root_path / automation.source_file
if not automation_path.parent.exists():
automation_path.parent.mkdir(parents=True)
@@ -159,6 +152,8 @@ class AutomationManager:
self.tag_manager.save(self.tag_path)
def delete(self, automation: ExtenededAutomation):
if automation.id is None:
raise AssertionError("automation.id must be defined to update!")
automation_path = self.hass_config.root_path / automation.source_file
if automation.source_file_type == "obj":
automation_path.unlink(missing_ok=True)
+9 -3
View File
@@ -15,20 +15,26 @@ class InlineAutomation(NamedTuple):
source_file: Path
automations: list[dict]
def __repr__(self) -> str:
return f"InlineAutomation(configuration_key='{self.configuration_key}', source_file='{self.source_file}')"
class IncludedAutoamtion(NamedTuple):
configuration_key: ConfigurationKey
ref: IncludedYamlDir
def __repr__(self) -> str:
return f"InlineAutomation(configuration_key='{self.configuration_key}', ref='{self.ref}')"
ExtractedAutomation = InlineAutomation | IncludedAutoamtion
AutomationExtractedIter = Iterator[ExtractedAutomation]
class BaseAutomation(BaseModel):
id: str
alias: Optional[str] = None
description: Optional[str] = None
id: Optional[str]
alias: str = ""
description: str = ""
trigger_variables: Optional[dict[str, Union[str, int, bool, float]]] = None
mode: str = "single"
trigger: list[dict] = []
+23 -1
View File
@@ -1,3 +1,7 @@
import traceback
from typing import NamedTuple
class ErrorSet(Exception):
"""An exception collection exception"""
@@ -7,6 +11,24 @@ class ErrorSet(Exception):
def gen_message(self):
if len(self.errors) > 1:
return "Encountered multiple errors:\n >" + "\n >".join(map(repr, self.errors))
return "Encountered multiple errors:\n >" + "\n >".join(
map(FormattedError.from_error, self.errors)
)
else:
return str(self.errors[0].args)
class FormattedError(NamedTuple):
error_name: str
error_message: str
error_traceback: str
original_error: Exception
@classmethod
def from_error(cls, err: Exception):
return cls(
error_name=str(err.__class__.__name__),
error_message=str(err.args),
error_traceback="\n\n".join(traceback.format_tb(err.__traceback__)),
original_error=err,
)
+3
View File
@@ -60,5 +60,8 @@ class HassConfig:
def get_automation_tags_path(self) -> Path:
return self.get_shortumations_path() / "tags.yaml"
def get_profile_path(self) -> Path:
return self.get_shortumations_path() / "profile.yaml"
def get_configuration_path(self) -> Path:
return self.root_path / "configuration.yaml"
+25
View File
@@ -0,0 +1,25 @@
from typing import Dict, Literal
from pydantic import BaseModel, Field
from src.hass_config import HassConfig
from src.yaml_serializer import dump_yaml, load_yaml
class UserProfile(BaseModel):
theme: Literal["dark", "light"] = "dark"
lang: str = "eng"
flags: Dict[str, bool] = Field(default_factory=dict)
@classmethod
def from_hass_config(cls, hass_config: HassConfig):
path = hass_config.get_profile_path()
if path.exists():
with hass_config.get_profile_path().open("r") as fp:
return cls(**load_yaml(fp, hass_config.root_path)) # type: ignore
else:
return cls()
def save(self, hass_config: HassConfig):
with hass_config.get_profile_path().open("w") as fp:
fp.write(dump_yaml(self.dict(), hass_config.root_path))
+10 -3
View File
@@ -1,21 +1,28 @@
from pathlib import Path
from typing import Iterator, NamedTuple, Tuple, Union
from typing import Iterator, NamedTuple, Tuple
from yaml.nodes import Node
from src.logger import get_logger
from .manager import YamlManager
dump_yaml = YamlManager.dump_yaml
load_yaml = YamlManager.load_yaml
logger = get_logger(__file__)
def load_dir_yaml(folder_or_file: Path) -> Iterator[Tuple[Path, dict | list]]:
if folder_or_file.is_dir():
for file in folder_or_file.iterdir():
yield from load_dir_yaml(file)
else:
with folder_or_file.open("r") as fp:
yield folder_or_file, load_yaml(fp, root_path=folder_or_file.parent)
if folder_or_file.suffix.lower() == ".yaml":
with folder_or_file.open("r") as fp:
yield folder_or_file, load_yaml(fp, root_path=folder_or_file.parent)
else:
logger.info(f"Ignoring the file {folder_or_file}")
@YamlManager.as_constructor("!include")
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -1 +1,38 @@
automation: !include ../automations/ui.yaml
media_player:
- platform: template
media_players:
receiver:
friendly_name: Receiver
current_source_template: "{{ states('input_text.selected_source') }}"
value_template: >
{% if is_state("input_boolean.receiver_on", "on") -%}
on
{%- else -%}
off
{%- endif %}
turn_on:
service: switch.turn_on
data_template:
entity_id: switch.receiver_on
turn_off:
service: switch.turn_on
data_template:
entity_id: switch.receiver_off
volume_up:
service: switch.turn_on
data_template:
entity_id: switch.volume_up
volume_down:
service: switch.turn_on
data_template:
entity_id: switch.vol
input_templates:
source 1:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_1
source 2:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_2
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,30 @@
# Loads default set of integrations. Do not remove.
default_config:
# Text to speech
tts:
- platform: google_translate
# automation manual: !include_dir_list ./automations/include_dir_list
# automation ui: !include automations/ui.yaml
# automation: !include automations/base.yaml
# automation cools: !include_dir_merge_list automations/include_dir_merge_list
script: !include scripts.yaml
scene: !include scenes.yaml
automation:
- alias: inline-auto
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
homeassistant:
packages: !include packages.yaml
+16
View File
@@ -0,0 +1,16 @@
ha: !include packages/ha.yaml
sub: !include_dir_merge_named packages/sub
secret_ones:
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
@@ -0,0 +1 @@
automation: !include ../automations/ui.yaml
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,13 @@
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
Whitespace-only changes.
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
media_player: !include_dir_list ../entities/media_players
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
# media_player: !include_dir_list ../entities/media_players
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
media_player:
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
- platform: media
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1,16 @@
- platform: ping
host: 192.168.0.119
name: "Ping Pc Tv"
scan_interval: 10
- platform: ping
host: 192.168.0.181
name: "Ping Living Room Tv"
scan_interval: 10
- platform: ping
host: 192.168.0.100
name: "Ping Printer"
scan_interval: 15
- platform: ping
host: 192.168.0.177
name: "Ping Broadlink"
scan_interval: 15
@@ -0,0 +1 @@
media_player: !include_dir_list ../entities/media_players
+6 -41
View File
@@ -1,27 +1,13 @@
from pathlib import Path
from unittest import TestCase
import yaml
from fastapi.testclient import TestClient
from src.api.app import make_app
from src.automations.types import Automation, ExtenededAutomation
from tests.utils import (
HA_CONFIG2_EXAMPLE,
HA_CONFIG6_EXAMPLE,
HA_CONFIG10_EXAMPLE,
get_example_automation_loader,
)
class BaseTestCase(TestCase):
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader()
self.client = TestClient(make_app(self.automation_loader))
from .util import BaseTestCase
class automation_pagination_tests(BaseTestCase):
@@ -90,20 +76,13 @@ class automation_pagination_tests(BaseTestCase):
class automation_pagination_tests_2(automation_pagination_tests):
source_config_path = HA_CONFIG2_EXAMPLE
test_params = {
"total": 1,
"subtest2_found_items": 0,
"subtest1_found_items": 1,
}
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG2_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_update_tests(BaseTestCase):
test_params = {
@@ -270,7 +249,7 @@ class automation_update_tests(BaseTestCase):
)
autos = resp.json()["data"]
self.assertEqual(resp.json()["totalItems"], self.test_params["total"])
self.assertNotIn("i am new", set([a["id"] for a in autos]))
self.assertNotIn("i am new", set([a.get("id", "") for a in autos]))
resp = self.client.post(
"/automations/item",
json=Automation(
@@ -283,7 +262,7 @@ class automation_update_tests(BaseTestCase):
)
data = resp.json()
self.assertEqual(data["totalItems"], self.test_params["total"] + 1)
self.assertIn("i am new", set([a["id"] for a in data["data"]]))
self.assertIn("i am new", set([a.get("id", "") for a in data["data"]]))
def test_update_some(self):
resp = self.client.post(
@@ -350,6 +329,7 @@ class automation_update_tests(BaseTestCase):
class automation_update_split_config_tests(automation_update_tests):
source_config_path = HA_CONFIG6_EXAMPLE
test_params = {
"total": 12,
"modify_item": 3,
@@ -378,30 +358,15 @@ class automation_update_split_config_tests(automation_update_tests):
},
}
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG6_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_update_split_config_and_inline_config_tests(automation_update_tests):
source_config_path = HA_CONFIG10_EXAMPLE
test_params = {
"total": 4,
"modify_item": 0,
"consitency_tests": {},
}
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG10_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_delete_tests(BaseTestCase):
def test_delete_some(self):
+27
View File
@@ -0,0 +1,27 @@
from tests.unittests.api.util import BaseTestCase
class user_profile_tests(BaseTestCase):
def test_read_empty_profile(self):
resp = self.client.get("/details/profile")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["theme"], "dark")
self.assertEqual(resp.json()["lang"], "eng")
def test_update_profile(self):
resp = self.client.put("/details/profile", json={"theme": "light", "lang": "fra"})
self.assertEqual(resp.status_code, 200)
resp = self.client.get("/details/profile")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["theme"], "light")
self.assertEqual(resp.json()["lang"], "fra")
def test_update_invalid_profile(self):
resp = self.client.put("/details/profile", json={"theme": "creamy", "lang": "fra"})
self.assertEqual(resp.status_code, 422)
resp = self.client.get("/details/profile")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["theme"], "dark")
self.assertEqual(resp.json()["lang"], "eng")
+19
View File
@@ -0,0 +1,19 @@
from unittest import TestCase
from fastapi.testclient import TestClient
from src.api.app import make_app
from tests.utils import HA_CONFIG_EXAMPLE, get_example_automation_loader
class BaseTestCase(TestCase):
source_config_path = HA_CONFIG_EXAMPLE
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(config_to_copy=self.source_config_path)
self.client = TestClient(make_app(self.hass_config))
+3 -14
View File
@@ -1,23 +1,12 @@
from pathlib import Path
from src.automations.errors import DBDataError
from src.automations.errors import DBDataError, RepeatedAutomationId
from src.automations.types import ExtenededAutomation
from .utils import TestWithDB
class db_tests(TestWithDB):
def test_db_creation(self):
with self.db.get_cur() as cur:
cur.execute("SELECT name FROM sqlite_master WHERE type ='table'")
tables = cur.fetchall()
self.assertListEqual(tables, [("autos",)])
self.db.create_db()
with self.db.get_cur() as cur:
cur.execute("SELECT name FROM sqlite_master WHERE type ='table'")
tables = cur.fetchall()
self.assertListEqual(tables, [("autos",)])
def test_insert_automations(self):
originals = [
ExtenededAutomation(
@@ -61,7 +50,7 @@ class db_tests(TestWithDB):
configuration_key=["automation"],
),
]
with self.assertRaises(DBDataError) as err:
with self.assertRaises(RepeatedAutomationId):
self.db.insert_automations(originals)
autos = list(self.db.list_automations(0, 10))
self.assertEqual(len(autos), 0)
self.assertEqual(len(autos), 1)
@@ -21,6 +21,11 @@ from tests.utils import (
HA_CONFIG10_EXAMPLE,
HA_CONFIG11_EXAMPLE,
HA_CONFIG12_EXAMPLE,
HA_CONFIG13_EXAMPLE,
HA_CONFIG14_EXAMPLE,
HA_CONFIG15_EXAMPLE,
HA_CONFIG16_EXAMPLE,
HA_CONFIG17_EXAMPLE,
HA_CONFIG_EXAMPLE,
)
@@ -160,6 +165,11 @@ class loader_tests(TestCase):
(HA_CONFIG10_EXAMPLE, 3),
(HA_CONFIG11_EXAMPLE, 3),
(HA_CONFIG12_EXAMPLE, 4),
(HA_CONFIG13_EXAMPLE, 4),
(HA_CONFIG14_EXAMPLE, 1),
(HA_CONFIG15_EXAMPLE, 1),
(HA_CONFIG16_EXAMPLE, 1),
(HA_CONFIG17_EXAMPLE, 1),
]:
with self.subTest(config_name=ha_path.name, expected=expected):
hass_config = HassConfig(ha_path)
@@ -28,7 +28,6 @@ class manager_tests(TestWithDB):
self.config_path = create_copy_of_example_config(ha_config_example)
self.automation_manager = AutomationManager(
HassConfig(self.config_path),
self.db_file,
)
return self.config_path, self.automation_manager
@@ -54,10 +53,6 @@ class manager_tests(TestWithDB):
{"platform": "zone", "entity_id": "person.thor", "zone": "zone.azguard"}
)
automation_manager.update(automation)
self.assertEqual(
automation_manager.get("sublist3-mlist2").trigger,
[],
)
automation_manager.reload()
self.assertEqual(
automation_manager.get("sublist3-mlist2").trigger,
+1 -12
View File
@@ -1,19 +1,8 @@
from pathlib import Path
from tempfile import mktemp
from unittest import TestCase
from src.automations.db import AutomationDBConnection
def make_temp_db():
return AutomationDBConnection(Path(mktemp() + ".db"))
class TestWithDB(TestCase):
def setUp(self) -> None:
self.db = make_temp_db()
self.db.create_db()
self.db_file = self.db.db_file
def tearDown(self) -> None:
self.db_file.unlink()
self.db = AutomationDBConnection()
@@ -65,6 +65,52 @@ class dumping_yamls_tests(TestCase):
},
)
def test_load_template_in_yaml(self):
yaml_obj = load_yaml(
io.StringIO(
"""
- id: '1652069225859'
alias: 'Lower the volume'
description: ''
mode: single
trigger:
- platform: state
entity_id: input_number.preferred_temperature
condition: []
action:
- service: media_player.volume_set
data_template:
entity_id: media_player.denon_avr_x2500h
volume_level: '{{ ((states(''input_number.volume_video'')|int)+80)/100 }}'
"""
),
Path.cwd(),
)
self.assertIsInstance(yaml_obj, list)
self.assertEqual(len(yaml_obj), 1)
self.assertDictEqual(
dict(yaml_obj[0]),
{
"id": "1652069225859",
"alias": "Lower the volume",
"description": "",
"mode": "single",
"trigger": [
{"platform": "state", "entity_id": "input_number.preferred_temperature"}
],
"condition": [],
"action": [
{
"service": "media_player.volume_set",
"data_template": {
"entity_id": "media_player.denon_avr_x2500h",
"volume_level": "{{ ((states('input_number.volume_video')|int)+80)/100 }}",
},
}
],
},
)
def test_load_stub(self):
yaml_obj = load_yaml(
io.StringIO(
+5
View File
@@ -22,6 +22,11 @@ HA_CONFIG9_EXAMPLE = SAMPLES_FOLDER / "config-9"
HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10"
HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11"
HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12"
HA_CONFIG13_EXAMPLE = SAMPLES_FOLDER / "config-13"
HA_CONFIG14_EXAMPLE = SAMPLES_FOLDER / "config-14"
HA_CONFIG15_EXAMPLE = SAMPLES_FOLDER / "config-15"
HA_CONFIG16_EXAMPLE = SAMPLES_FOLDER / "config-16"
HA_CONFIG17_EXAMPLE = SAMPLES_FOLDER / "config-17"
def get_example_automation_loader(
+2 -2
View File
@@ -1,7 +1,7 @@
name: Shortumation
version: v0.6.2
version: v0.7.6
slug: shortumation
image: asosnovsky/shortumation-{arch}
image: "asosnovsky/shortumation-{arch}"
url: "https://github.com/asosnovsky/Shortumation"
description: "A homeassitant addon which provides better UI for automations & scripts."
arch:
+2
View File
@@ -8,8 +8,10 @@ host_port="$host:$port"
pushd $api_location
echo "--------------------"
echo "BUILD_VERSION = "$BUILD_VERSION
echo "ARCH = "$BUILD_ARCH
echo "HOST = $host_port"
echo "HASSIO_WS = $HASSIO_WS"
echo $(uname -a)
echo $(python --version)
echo "--------------------"
python -m hypercorn src.app:app -b $host_port --config /app/hypercorn.toml
+6 -6
View File
@@ -6,19 +6,19 @@
"dependencies": {
"@emotion/react": "11.9.3",
"@emotion/styled": "11.9.3",
"@mui/icons-material": "5.8.4",
"@mui/material": "5.8.6",
"@mui/icons-material": "5.10.6",
"@mui/material": "5.10.6",
"@mui/styles": "5.8.6",
"@types/jest": "28.1.6",
"@types/jest": "28.1.8",
"@types/node": "17.0.36",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"@types/react": "18.0.25",
"@types/react-dom": "18.0.8",
"@types/ws": "8.5.3",
"@uiw/react-codemirror": "4.10.4",
"autosuggest-highlight": "3.3.4",
"home-assistant-js-websocket": "7.1.0",
"jss": "10.9.2",
"material-ui-confirm": "3.0.4",
"material-ui-confirm": "3.0.6",
"notistack": "2.0.5",
"react": "18.2.0",
"react-cookie": "4.1.1",
+7 -10
View File
@@ -1,14 +1,18 @@
import "./App.css";
import { Routes, Route, BrowserRouter } from "react-router-dom";
import { AutomationRoute } from "routes/automation";
import { useConnectedApiService } from "apiService";
import { useConnectedApiService } from "services/api";
import { ErrorBoundary } from "components/ErrorBoundary";
import { CookiesProvider } from "react-cookie";
import { Page } from "components/Page";
const ConnectedAutomationRoute = () => {
const api = useConnectedApiService();
return <AutomationRoute api={api} />;
return (
<Page api={api}>
<AutomationRoute api={api} />
</Page>
);
};
function App() {
@@ -18,14 +22,7 @@ function App() {
<CookiesProvider>
<BrowserRouter>
<Routes>
<Route
path="*"
element={
<Page>
<ConnectedAutomationRoute />
</Page>
}
/>
<Route path="*" element={<ConnectedAutomationRoute />} />
</Routes>
</BrowserRouter>
</CookiesProvider>
-28
View File
@@ -1,28 +0,0 @@
import { useEffect } from "react";
import { useDefaultApiState, makeReloadAutomations } from "./util";
import { AutomationAPI } from "./automations";
export type ApiService = ReturnType<typeof useAPIService>;
export const useAPIService = (automationAPI: AutomationAPI) => {
// state
const [state, setState] = useDefaultApiState();
const { reload, wrapCall } = makeReloadAutomations(
automationAPI,
state,
setState
);
// initial load of autos
useEffect(() => {
reload();
// eslint-disable-next-line
}, []);
return {
state,
removeAutomation: wrapCall(automationAPI.remove),
updateAutomation: wrapCall(automationAPI.update),
createAutomation: wrapCall(automationAPI.create),
updateTags: wrapCall(automationAPI.updateTags),
};
};
-24
View File
@@ -1,24 +0,0 @@
import { AutomationData } from "types/automations";
import { makeAutomationAPI } from "./automations";
import { makeRemoteAPI } from "./base";
import { useAPIService } from "./core";
import { useMockAPI } from "./mock";
import { useRef } from "react";
const locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i);
const baseURL = new URL(
process.env.NODE_ENV === "development"
? `http://${window.location.hostname}:8000`
: window.location.origin + (!locationPrefixWeb ? "" : locationPrefixWeb[1])
);
export const wsURL = baseURL + "socket";
export const remoteAutoAPI = makeRemoteAPI(baseURL + "automations");
export const useConnectedApiService = () =>
useAPIService(makeAutomationAPI(remoteAutoAPI));
export const useMockApiService = (
initialAutos: AutomationData[],
returnErrors: boolean = false
) =>
useAPIService(
makeAutomationAPI(useMockAPI(initialAutos, useRef, returnErrors))
);
-40
View File
@@ -1,40 +0,0 @@
import { useState } from "react";
import { ApiState } from "./types";
import { AutomationAPI } from "./automations";
export const useDefaultApiState = () =>
useState<ApiState>({
automations: { ready: false },
});
export const makeReloadAutomations = (
automationAPI: AutomationAPI,
state: ApiState,
setState: (s: ApiState) => void
) => {
const reload = async () => {
let params = { offset: 0, limit: 10000 };
if (state.automations.ready && state.automations.ok) {
params = state.automations.data.params;
}
const resp = await automationAPI.list(params);
setState({
...state,
automations: {
ready: true,
...resp,
},
});
};
const wrapCall = <Call extends (a: any) => Promise<any>>(fcn: Call) => {
return async (args: Parameters<Call>[0]) => {
const resp = await fcn(args);
await reload();
return resp as ReturnType<Call>;
};
};
return {
reload,
wrapCall,
};
};
@@ -14,7 +14,7 @@ const { componentMeta, make } = makeStory({
}) => {
const [[metadata, tags], setState] = useState([args.metadata, args.tags]);
const tagDB = useTagDB(
[{ id: metadata.id, tags: Object.fromEntries(tags) }],
metadata.id ? [{ id: metadata.id, tags: Object.fromEntries(tags) }] : [],
(_, t) => setState([metadata, Object.entries(t)])
);
@@ -10,6 +10,7 @@ import { AddIcon, TrashIcon } from "components/Icons";
import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "components/AutomationManager/TagDB";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "services/lang";
export interface AutoInfoBoxProps {
metadata: AutomationMetadata & Partial<AutomationShortumationMetadata>;
@@ -26,6 +27,7 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
tagDB,
}) => {
// state
const langStore = useLang();
const [newTag, setNewTag] = useState<[string, string]>(["", ""]);
const [[errorIndex, error], _setError] = useState<[number | "new", string]>([
-1,
@@ -54,12 +56,12 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
);
const validTagName = (newName: string): string | undefined => {
if (newName.length <= 0) {
return "Name must be at least 1 character long";
return langStore.get("VALIDATION_AUTOMATION_NAME");
}
// eslint-disable-next-line
for (const [name, _] of tags) {
if (name.trim() === newName.trim()) {
return `The tag '${name}' already exists`;
return langStore.get("VALIDATION_TAG_EXISTS", { name });
}
}
};
@@ -101,42 +103,42 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div className="automation-editor--info-box">
<div className="automation-editor--info-box-inner">
<InputText
label="ID"
value={metadata.id}
label={langStore.get("ID")}
value={metadata.id ?? langStore.get("N/A")}
onChange={onUpdateMetadata("id")}
/>
<InputText
label="Name"
label={langStore.get("NAME")}
value={metadata.alias ?? ""}
onChange={onUpdateMetadata("alias")}
/>
<InputText
multiline
label="Description"
label={langStore.get("DESCRIPTION")}
value={metadata.description ?? ""}
onChange={onUpdateMetadata("description")}
/>
<InputList
label="Mode"
label={langStore.get("MODE")}
current={metadata.mode}
onChange={onUpdateMetadata("mode")}
options={["parallel", "single", "queued", "restart"]}
/>
<div className="automation-editor--info-box--tags">
<h1>Tags</h1>
<h1>{langStore.get("TAGS")}</h1>
<div className="automation-editor--info-box--tag-list">
{tags.map(([tagName, tagValue], tagIndex) => (
<div key={tagIndex} className="automation-editor--info-box--tag">
<InputAutoText
value={tagName}
label="Name"
label={langStore.get("NAME")}
onChange={(v) => updateTagName(v, tagIndex)}
options={foundNewTagNames}
error={errorIndex === tagIndex ? error : undefined}
/>
<InputAutoText
value={tagValue}
label="Tag"
label={langStore.get("TAG")}
onChange={(v) => onUpdateTags(v, tagIndex)}
options={tagDB.getTagValues(tagName)}
error={errorIndex === tagIndex ? error : undefined}
@@ -153,14 +155,14 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div className="automation-editor--info-box--tag">
<InputAutoText
value={newTag[0]}
label="Name"
label={langStore.get("NAME")}
onChange={(v) => setNewTag([v, newTag[1]])}
options={foundNewTagNames}
error={errorIndex === "new" ? error : undefined}
/>
<InputAutoText
value={newTag[1]}
label="Tag"
label={langStore.get("TAG")}
onChange={(v) => setNewTag([newTag[0], v])}
options={tagDB.getTagValues(newTag[0])}
error={errorIndex === "new" ? error : undefined}
@@ -1,9 +0,0 @@
.automation-editor--nodes-row .collection-nodes--wrap {
--node-height: 12em !important;
--node-width: 100% !important;
}
.automation-editor--nodes-row .collection-nodes--wrap .collection-nodes {
min-width: 90%;
min-height: 10em;
}
@@ -1,40 +0,0 @@
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { makeStory } from "devUtils";
import { useState } from "react";
import { NodesRow } from ".";
const { make, componentMeta } = makeStory({
Component: NodesRow,
BaseTemplate: (props) => {
const [data, setData] = useState(props.data);
return (
<NodesRow
{...props}
data={data}
onUpdate={(up) => {
setData(up);
props.onUpdate(up);
}}
/>
);
},
meta: {
title: "App/AutomationEditor/NodesRow",
args: {
data: [],
sequenceNodeDims: DEFAULT_DIMS.node,
},
},
});
export default componentMeta;
export const Empty = make({});
export const One = make({
type: "trigger",
data: [
{
platform: "calendar",
event: "test",
},
],
});
@@ -1,42 +0,0 @@
import "./index.css";
import { AutomationNode, AutomationNodeMapping } from "types/automations";
import { useHA } from "haService";
import { CollectionNodeElement } from "components/DAGGraph/nodes/CollectionNode/CollectionNodeElement";
import { getDescriptionFromAutomationNode } from "utils/formatting";
import { Size } from "components/DAGGraph/elements/types";
export type NodesRowProps<
K extends keyof AutomationNodeMapping,
T extends AutomationNode<K>
> = {
type: K;
data: T[];
onUpdate: (d: T[]) => void;
sequenceNodeDims: Size;
};
export function NodesRow<
K extends keyof AutomationNodeMapping,
T extends AutomationNode<K>
>({ type: collectionType, data, sequenceNodeDims }: NodesRowProps<K, T>) {
const { namer } = useHA();
return (
<div className="automation-editor--nodes-row">
<CollectionNodeElement
width={0}
height={0}
nodes={data.map((node) => ({
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
onXClick: () => {},
}))}
onAddNode={() => {}}
collectionType={collectionType}
title="if"
sequenceNode={sequenceNodeDims}
flipped
/>
</div>
);
}
@@ -127,4 +127,13 @@
.automation-editor--info-box--buttons {
display: flex;
gap: 1em;
}
.automation-editor.fullscreen .automation-editor--flow-wrapper--toolbar--title {
display: none;
}
.automation-editor.fullscreen .automation-editor--flow-wrapper--toolbar {
justify-content: flex-end;
margin-top: 0.5em;
}
@@ -1,27 +1,25 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { AutomationEditor } from "./index";
import { useState } from "react";
import { Page } from "components/Page";
import { useTagDB } from "components/AutomationManager/TagDB";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
export default {
title: "App/AutomationEditor",
component: AutomationEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
dims: DEFAULT_DIMS,
},
} as ComponentMeta<typeof AutomationEditor>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof AutomationEditor> = (args) => {
const [state, setState] = useState(args.automation);
return (
<Page>
const { make, componentMeta } = makeStory({
Component: AutomationEditor,
meta: {
title: "App/AutomationEditor",
args: {
dims: DEFAULT_DIMS,
},
},
BaseTemplate: (args) => {
const [state, setState] = useState(args.automation);
return (
<AutomationEditor
{...args}
tagDB={useTagDB(
state ? [{ id: state.id, tags: state.tags }] : [],
state && state.id ? [{ id: state.id, tags: state.tags }] : [],
() => {}
)}
automation={state}
@@ -29,15 +27,15 @@ const Template: ComponentStory<typeof AutomationEditor> = (args) => {
window.setTimeout(() => setState(s), 3000);
}}
/>
</Page>
);
};
);
},
});
export const Loading = Template.bind({});
export default componentMeta;
export const Simple = Template.bind({});
Simple.args = {
...Simple.args,
export const Loading = make({});
export const Simple = make({
automation: {
condition: [],
tags: {
@@ -94,11 +92,9 @@ Simple.args = {
},
],
},
};
});
export const EmptyStart = Template.bind({});
EmptyStart.args = {
...EmptyStart.args,
export const EmptyStart = make({
automation: {
condition: [],
tags: {},
@@ -115,22 +111,18 @@ EmptyStart.args = {
trigger: [],
action: [],
},
};
});
export const BadAutomationInvalidMetadata = Template.bind({});
BadAutomationInvalidMetadata.args = {
...BadAutomationInvalidMetadata.args,
export const BadAutomationInvalidMetadata = make({
automation: {
condition: [],
tags: {},
trigger: [],
action: [],
} as any,
};
});
export const BadAutomationInvalidTriggers = Template.bind({});
BadAutomationInvalidTriggers.args = {
...BadAutomationInvalidTriggers.args,
export const BadAutomationInvalidTriggers = make({
automation: {
condition: [],
tags: {},
@@ -147,11 +139,9 @@ BadAutomationInvalidTriggers.args = {
trigger: ["haha I am a string"] as any,
action: [],
},
};
});
export const BadAutomationInvalidSequence = Template.bind({});
BadAutomationInvalidSequence.args = {
...BadAutomationInvalidSequence.args,
export const BadAutomationInvalidSequence = make({
automation: {
condition: [],
tags: {},
@@ -165,14 +155,12 @@ BadAutomationInvalidSequence.args = {
action: [
{
choose: {},
},
} as any,
],
} as any,
};
});
export const RepeatExample = Template.bind({});
RepeatExample.args = {
...RepeatExample.args,
export const RepeatExample = make({
automation: {
id: "1654976151462",
alias: "Get out of baby room",
@@ -243,4 +231,4 @@ RepeatExample.args = {
],
tags: {},
},
};
});
+102 -56
View File
@@ -2,7 +2,6 @@ import "./index.css";
import "./index.mobile.css";
import { FC, useState } from "react";
import { useCookies } from "react-cookie";
import Skeleton from "@mui/material/Skeleton";
import LinearProgress from "@mui/material/LinearProgress";
@@ -11,7 +10,6 @@ import SpeedDialAction from "@mui/material/SpeedDialAction";
import SpeedDialIcon from "@mui/icons-material/SettingsRounded";
import UndoIcon from "@mui/icons-material/UndoSharp";
import Icon from "@mui/material/Icon";
import EditIcon from "@mui/icons-material/ModeEditOutlineTwoTone";
import DeleteIcon from "@mui/icons-material/DeleteForever";
import { CheckMarkIcon } from "components/Icons";
@@ -31,7 +29,19 @@ import { MiniFailure } from "types/validators/helper";
import { AutoInfoBox } from "./AutoInfoBox";
import { useAutomatioEditorState, EditorData } from "./state";
import { useLang } from "services/lang";
import { useSnackbar } from "notistack";
import { Alert } from "@mui/material";
import { useUserProfile } from "services/api";
import {
ControlButton,
ReactFlowProvider,
useReactFlow,
} from "react-flow-renderer";
import FitInIcon from "@mui/icons-material/FitScreenRounded";
import FullscreenIcon from "@mui/icons-material/FullscreenRounded";
import FullscreenExitIcon from "@mui/icons-material/FullscreenExitRounded";
import { useEffect } from "react";
interface Props {
automation?: AutomationData | BareAutomationData;
dims: DAGDims;
@@ -40,17 +50,31 @@ interface Props {
onDelete: () => void;
tagDB: TagDB;
isNew?: boolean;
readonly: boolean;
issue?: string;
}
export const AutomationEditor: FC<Props> = ({
export const AutomationEditor: FC<Props> = (props) => {
return (
<ReactFlowProvider>
<AutomationEditorInner {...props} />
</ReactFlowProvider>
);
};
export const AutomationEditorInner: FC<Props> = ({
dims,
automation: propsAutos,
onUpdate: propsOnUpdate,
onDelete,
onTrigger,
tagDB,
isNew,
readonly,
issue,
}) => {
// state
const reactFlow = useReactFlow();
const userProfile = useUserProfile();
const langStore = useLang();
const snackbr = useSnackbar();
const {
state,
updateSequence,
@@ -61,17 +85,28 @@ export const AutomationEditor: FC<Props> = ({
save,
saveAndUpdate,
undo,
} = useAutomatioEditorState(propsAutos, propsOnUpdate);
} = useAutomatioEditorState(propsAutos, (auto) => {
if (readonly) {
snackbr.enqueueSnackbar(langStore.get("READONLY_CANNOT_UPDATE"), {
color: "warning",
});
} else {
propsOnUpdate(auto);
}
});
const [infoBoxOpen, setInfoBox] = useState(false);
const [
{ ckFlipped },
setCookies,
// eslint-disable-next-line
_,
] = useCookies(["ckFlipped"]);
const [fullScreenMode, setFullScreenMode] = useState(false);
// alias
const flipped = dims.flipped ? true : ckFlipped === "1";
const setFlipped = (v: boolean) => setCookies("ckFlipped", v ? "1" : "0");
const flipped = userProfile.flags.flipped ?? !dims.flipped;
const useNodesRow = userProfile.flags.useNodesRow !== false;
// effect
useEffect(() => {
if (reactFlow) {
setTimeout(() => {
reactFlow.fitView();
}, 500);
}
}, [flipped, fullScreenMode, reactFlow]);
// render
if (state.status === "loading") {
return (
@@ -93,7 +128,14 @@ export const AutomationEditor: FC<Props> = ({
);
}
return (
<div className={["automation-editor", state.status].join(" ")}>
<div
className={[
"automation-editor",
state.status,
readonly ? "readonly" : "",
fullScreenMode ? "fullscreen" : "",
].join(" ")}
>
{state.status === "saving" && (
<LinearProgress className="linear-loader" />
)}
@@ -110,13 +152,15 @@ export const AutomationEditor: FC<Props> = ({
state.status,
].join(" ")}
>
<Button onClick={() => setInfoBox(false)}>Close</Button>
<Button onClick={() => setInfoBox(false)}>
{langStore.get("CLOSE")}
</Button>
<Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save}
disabled={state.status !== "changed"}
disabled={state.status !== "changed" || readonly}
>
Save <CheckMarkIcon color="#bf4" />
{langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button>
</div>
</AutoInfoBox>
@@ -131,7 +175,7 @@ export const AutomationEditor: FC<Props> = ({
<div className="id">{state.data.id}</div>
<InputTextView
value={state.data.alias ?? ""}
placeholder="Name"
placeholder={langStore.get("NAME")}
onChange={(alias) =>
updateMetadata(
{
@@ -145,7 +189,7 @@ export const AutomationEditor: FC<Props> = ({
</span>
<InputList
fullWidth={false}
label="Mode"
label={langStore.get("MODE")}
className="automation-editor--flow-wrapper--toolbar--modes"
current={{
id: state.data.mode,
@@ -165,28 +209,26 @@ export const AutomationEditor: FC<Props> = ({
options={[
{
id: "single",
label: "Do not start a new run. Issue a warning.",
label: langStore.get("MODE_SIGNLE_LABEL"),
},
{
id: "parallel",
label:
"Start a new, independent run in parallel with previous runs.",
label: langStore.get("MODE_SIGNLE_PARALLEL"),
},
{
id: "queued",
label:
"Start a new run after all previous runs complete. Runs are guaranteed to execute in the order they were queued.",
label: langStore.get("MODE_SIGNLE_QUEUED"),
},
{
id: "restart",
label: "Start a new run after first stopping previous run.",
label: langStore.get("MODE_SIGNLE_RESTART"),
},
]}
/>
<InputTextView
className="description"
value={state.data.description ?? ""}
placeholder="Description"
placeholder={langStore.get("DESCRIPTION")}
onChange={(description) =>
updateMetadata(
{
@@ -198,15 +240,6 @@ export const AutomationEditor: FC<Props> = ({
}
/>
</div>
{!dims.flipped && (
<Button
className={"automation-editor--flow-wrapper--toolbar--flip-btn"}
onClick={() => setFlipped(!flipped)}
>
<Icon>{flipped ? "flip_to_front" : "flip_to_back"}</Icon>
Flip
</Button>
)}
{state.status === "changed" && (
<Button onClick={undo}>
<UndoIcon />
@@ -217,9 +250,14 @@ export const AutomationEditor: FC<Props> = ({
onClick={save}
disabled={state.status !== "changed"}
>
Save <CheckMarkIcon color="#bf4" />
{langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button>
</div>
{readonly && (
<Alert color="warning">
{langStore.get("READONLY_MODE")} - {issue}
</Alert>
)}
<DAGAutomationGraph
action={state.data.action}
trigger={state.data.trigger}
@@ -228,6 +266,17 @@ export const AutomationEditor: FC<Props> = ({
onTriggerUpdate={updateTrigger}
onConditionUpdate={updateCondition}
isFlipped={flipped}
useNodesRow={useNodesRow}
additionalControls={
<>
<ControlButton onClick={() => setFullScreenMode(!fullScreenMode)}>
{fullScreenMode ? <FullscreenExitIcon /> : <FullscreenIcon />}
</ControlButton>
<ControlButton onClick={() => reactFlow.fitView()}>
<FitInIcon />
</ControlButton>
</>
}
/>
<SpeedDial
ariaLabel="options label"
@@ -242,26 +291,26 @@ export const AutomationEditor: FC<Props> = ({
// tooltipOpen
sx={{ pointerEvents: "auto" }}
icon={<RunIcon />}
tooltipTitle={"Trigger"}
tooltipTitle={langStore.get("TRIGGER")}
onClick={onTrigger}
/>
<SpeedDialAction
// tooltipOpen
icon={<DeleteIcon />}
tooltipTitle={"Delete"}
tooltipTitle={langStore.get("DELETE")}
onClick={onDelete}
/>
<SpeedDialAction
// tooltipOpen
icon={<EditIcon />}
tooltipTitle={"Metadata"}
tooltipTitle={langStore.get("METADATA")}
onClick={() => setInfoBox(!infoBoxOpen)}
/>
{state.status === "changed" && (
<SpeedDialAction
// tooltipOpen
icon={<UndoIcon />}
tooltipTitle={"Undo"}
tooltipTitle={langStore.get("UNDO")}
onClick={undo}
/>
)}
@@ -277,6 +326,7 @@ export const ValidationBox: FC<{
data: EditorData;
onSave: (d: EditorData) => void;
}> = (props) => {
const langStore = useLang();
const [{ failures, data }, setState] = useState({
failures: props.failures,
data: props.data,
@@ -305,24 +355,20 @@ export const ValidationBox: FC<{
<div className="automation-editor-failures">
<ul>
{failures.map((f, i) => (
<>
<li key={i}>
<b>{f.path}</b>:
<ul>
{f.message.map((m, j) => (
<li key={j}>{m}</li>
))}
</ul>
</li>
</>
<li key={i}>
<b>{f.path}</b>:
<ul>
{f.message.map((m, j) => (
<li key={j}>{m}</li>
))}
</ul>
</li>
))}
</ul>
<span>
Please correct the automation file manually and then continue!
</span>
<InputYaml label="Raw" value={data} onChange={onSave} />
<span>{langStore.get("VALIDATION_PLEASE_CORRECT_FILE")}</span>
<InputYaml label={langStore.get("RAW")} value={data} onChange={onSave} />
<Button disabled={failures.length > 0} onClick={() => props.onSave(data)}>
Save
{langStore.get("SAVE")}
</Button>
</div>
);
@@ -23,6 +23,7 @@ const { make, componentMeta } = makeStory({
id: "1",
title: "Example",
entityId: "automation.1",
readonly: false,
description: "Amazing automation!",
tags: {},
state: "on",
@@ -38,6 +39,7 @@ const { make, componentMeta } = makeStory({
id: "2",
title: "Example 2",
entityId: "automation.2",
readonly: false,
description: "Cool!",
state: "on",
source_file: "automation.yaml",
@@ -89,6 +91,7 @@ export const Nested = make({
entityId: "automation.1",
description: "",
title: "Automation #1",
readonly: false,
state: "on",
source_file: "automation.yaml",
source_file_type: "list",
@@ -102,6 +105,7 @@ export const Nested = make({
{
id: "2",
entityId: "automation.2",
readonly: false,
description: "another one",
title: "Automation #2",
state: "off",
@@ -117,6 +121,7 @@ export const Nested = make({
{
id: "3",
entityId: "automation.3",
readonly: false,
description: "bad one",
title: "Automation #3",
state: "offing",
@@ -153,6 +158,7 @@ export const Nested = make({
},
data: [
{
readonly: false,
id: "4",
entityId: "automation.4",
description: "Cool thing",
@@ -1,4 +1,5 @@
import { HassEntities } from "home-assistant-js-websocket";
import { LangStore, useLang } from "services/lang";
import { useEffect, useState } from "react";
import { AutomationData, BareAutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults";
@@ -10,7 +11,8 @@ export const useAutomationDB = (
configAutomations: AutomationData[],
tagsDB: TagDB
) => {
const autoMap = genMapping(haEntities, configAutomations, tagsDB);
const langStore = useLang();
const autoMap = genMapping(haEntities, configAutomations, tagsDB, langStore);
const [newAuto, setNewAuto] =
useState<
null | [AutomationManagerAuto, AutomationData | BareAutomationData]
@@ -50,17 +52,18 @@ export const useAutomationDB = (
const auto = defaultAutomation(String(Date.now()));
setNewAuto([
{
readonly: false,
id: auto.id,
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: "unregistered",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: {},
issue: "New Automation",
issue: langStore.get("NEW_AUTOMATION"),
isNew: true,
source_file: "n/a",
source_file_type: "n/a",
configuration_key: ["n/a"],
source_file: langStore.get("N/A"),
source_file_type: langStore.get("N/A"),
configuration_key: [],
},
auto,
]);
@@ -72,15 +75,21 @@ export const useAutomationDB = (
const genMapping = (
haEntities: HassEntities,
configAutomations: AutomationData[],
tagsDB: TagDB
tagsDB: TagDB,
langStore: LangStore
) => {
const configData: Record<string, AutomationData> = configAutomations.reduce(
(all, n) => ({
...all,
[n.id]: n,
}),
{}
);
const configDataNoId: AutomationData[] = [];
const configData: Record<string, AutomationData & { id: string }> =
configAutomations.reduce((all, n) => {
if (n.id) {
return {
...all,
[n.id]: n,
};
}
configDataNoId.push(n);
return all;
}, {});
const automatioinMap: Record<
string,
[AutomationManagerAuto, AutomationData | null]
@@ -88,12 +97,14 @@ const genMapping = (
Object.entries(haEntities)
.filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation."))
.forEach(([entityId, entityData], i) => {
const autoId = entityData.attributes.id ?? `${entityData.state}-${i}`;
const autoId = entityData.attributes.id ?? entityId.split(".")[1];
let title = entityData.attributes.friendly_name ?? "";
let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state)
? undefined
: `recived invalid state "${entityData.state}, this could be because you have a lingering automation that was not cleared by homeassistant, try to reboot HA or manually clear this automation from HA Database."`;
: langStore.get("ISSUES_INVALID_STATE", {
state: entityData.state,
});
let found: AutomationData | null = null;
let source_file = "n/a";
let source_file_type = "n/a";
@@ -107,7 +118,7 @@ const genMapping = (
configuration_key = found.configuration_key ?? configuration_key;
delete configData[autoId];
} else {
issue = "failed to find this automation in '/config' folder";
issue = langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG");
}
automatioinMap[autoId] = [
@@ -122,29 +133,74 @@ const genMapping = (
source_file_type,
configuration_key,
issue,
readonly: found == null,
},
found,
];
});
Object.values(configData).forEach((auto) => {
Object.values(configData).forEach((auto, i) => {
automatioinMap[auto.id] = [
{
id: auto.id,
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: "unregistered",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: tagsDB.getTags(auto.id),
source_file: auto.source_file,
source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key,
issue:
"homeassistant did not load this automation, try to manually reload automations or restart homeassistant.",
issue: langStore.get("ISSUES_NO_LOAD_AUTOMATION"),
readonly: false,
},
auto,
];
});
let failedGeneration: number = 0;
configDataNoId.forEach((auto) => {
let generatedAutoId = `automation_${failedGeneration + 1}`;
if (auto.alias) {
generatedAutoId = auto.alias
.toLowerCase()
.replaceAll(/\W/g, " ")
.trim()
.replaceAll(" ", "_");
} else {
failedGeneration += 1;
}
if (automatioinMap[generatedAutoId]) {
automatioinMap[generatedAutoId] = [
{
...automatioinMap[generatedAutoId][0],
issue: langStore.get("ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT", {
sourceFile: auto.source_file,
}),
readonly: true,
},
auto,
];
} else {
automatioinMap[generatedAutoId] = [
{
id: generatedAutoId,
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: {},
source_file: auto.source_file,
source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key,
issue: langStore.get("ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT", {
sourceFile: auto.source_file,
}),
readonly: true,
},
auto,
];
}
});
return automatioinMap;
};
@@ -10,6 +10,7 @@ import {
} from "./state";
import Alert from "@mui/material/Alert";
import { useConfirm } from "material-ui-confirm";
import { useLang } from "services/lang";
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
onAutomationDelete: (aid: string, eid: string) => void;
@@ -17,13 +18,14 @@ export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
export const AutomationManagerLoaded: FC<
PropsWithChildren<AutomationManagerLoadedProps>
> = ({ children, ...args }) => {
const langStore = useLang();
const state = useAutomationManagerState(args);
const confirm = useConfirm();
const onAutomationDelete = async (aid: string, eid: string) =>
confirm({
title: "Are you sure you want to delete this automation?",
confirmationText: "Delete",
title: langStore.get("CONFIRMATION_DELETE_THIS_AUTOMATION"),
confirmationText: langStore.get("DELETE"),
})
.then(() => {
args.onAutomationDelete(aid, eid);
@@ -48,6 +50,8 @@ export const AutomationManagerLoaded: FC<
{state.currentAutomationId !== null ? (
state.currentAutomation ? (
<AutomationEditor
readonly={state.currentAutomationIsReadOnly}
issue={state.currentAutomationIssue}
dims={{
...DEFAULT_DIMS,
flipped: true,
@@ -76,8 +80,9 @@ export const AutomationManagerLoaded: FC<
) : (
<div>
<Alert color="warning">
Failed to find an automation on disk with id{" "}
{state.currentAutomationId}.
{langStore.get("ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK", {
id: state.currentAutomationId,
})}
</Alert>
</div>
)
@@ -7,6 +7,7 @@ import { useAutomationDB } from "./automationDB";
import { useConfirm } from "material-ui-confirm";
import { AutomationManagerAutoUpdatable } from "../types";
import { useSnackbar } from "notistack";
import { useLang } from "services/lang";
export type UseAutomationManagerStateArgs = {
configAutomations: AutomationData[];
@@ -26,6 +27,7 @@ export const useAutomationManagerState = ({
onAutomationStateChange,
}: UseAutomationManagerStateArgs) => {
// state
const langStore = useLang();
const confirm = useConfirm();
const snackbr = useSnackbar();
const cookies = useAMSCookies();
@@ -35,7 +37,11 @@ export const useAutomationManagerState = ({
.map(({ id, tags = {} }) => ({
id,
tags,
})),
}))
.filter(({ id }) => typeof id === "string") as Array<{
id: string;
tags: Record<string, string>;
}>,
onUpdateTags
);
const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB);
@@ -44,10 +50,9 @@ export const useAutomationManagerState = ({
const stillHaveNewAreYouSure = async () => {
try {
await confirm({
content:
"Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.",
confirmationText: "Switch Automation",
cancellationText: "Cancel",
content: langStore.get("WARNING_SWITCHING_FROM_NONE_SAVE"),
confirmationText: langStore.get("SWITCH_AUTOMATION"),
cancellationText: langStore.get("CANCEL"),
});
return true;
} catch (_) {
@@ -77,6 +82,14 @@ export const useAutomationManagerState = ({
get currentAutomationEntityId(): string | null {
return currentAutomation === null ? null : currentAutomation[0].entityId;
},
get currentAutomationIsReadOnly(): boolean {
return currentAutomation === null ? true : currentAutomation[0].readonly;
},
get currentAutomationIssue(): string | undefined {
return currentAutomation === null
? undefined
: currentAutomation[0].issue;
},
async setSelectedAutomationId(i: string | null, force: boolean = false) {
if (methods.currentAutomationIsNew && !force) {
if (!(await stillHaveNewAreYouSure())) {
@@ -93,7 +106,9 @@ export const useAutomationManagerState = ({
}
}
const auto = automationDB.addNew();
methods.setSelectedAutomationId(auto.id, true);
if (auto.id) {
methods.setSelectedAutomationId(auto.id, true);
}
},
editorUpdateAutomation(auto: AutomationData | BareAutomationData) {
if (methods.currentAutomationIsNew) {
@@ -128,9 +143,10 @@ export const useAutomationManagerState = ({
}
} else {
snackbr.enqueueSnackbar(
`Failed to save automation "${aid}" contents - ${JSON.stringify(
a
)} -- not found in /config`,
langStore.get("ERROR_FAILED_TO_SAVE", {
aid,
contents: JSON.stringify(a),
}),
{ variant: "error" }
);
}
@@ -12,6 +12,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "../TagDB";
import { useLang } from "services/lang";
export type TagsProps = {
automationId: string;
@@ -29,6 +30,7 @@ export type TagModalState =
};
export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
const langStore = useLang();
const [modalState, setModal] = useState<TagModalState>({ open: false });
const tags = tagsDB.getTags(automationId, true);
const onUpdate = (t: Record<string, string>) =>
@@ -44,7 +46,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText
className="name"
options={tagsDB.getTagNames(Object.keys(tags))}
label="Tag Name"
label={langStore.get("TAG_NAME")}
value={modalState.tag[0]}
onChange={(v) =>
setModal({
@@ -56,7 +58,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText
className="value"
options={tagsDB.getTagValues(modalState.tag[0])}
label="Tag Value"
label={langStore.get("TAG_VALUE")}
value={modalState.tag[1]}
onChange={(v) =>
setModal({
@@ -67,7 +69,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
/>
<div className="buttons">
<Button onClick={() => setModal({ open: false })} color="info">
Close
{langStore.get("CLOSE")}
</Button>
<Button
disabled={!validTag}
@@ -80,7 +82,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
}}
color="success"
>
{modalState.isNew ? "Create" : "Save"}
{modalState.isNew ? langStore.get("CREATE") : langStore.get("SAVE")}
</Button>
</div>
</div>
@@ -9,12 +9,16 @@ import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import SelectIcon from "@mui/icons-material/HighlightAltSharp";
import RunIcon from "@mui/icons-material/RunCircleOutlined";
import Tooltip from "@mui/material/Tooltip";
import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import { InputTextView } from "components/Inputs/InputTextView";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { AutomationManagerAuto } from "../types";
import { Tags } from "./Tags";
import { TagDB } from "../TagDB";
import { Chip, Tooltip } from "@mui/material";
import { useLang } from "services/lang";
export type MetadataBoxProps = AutomationManagerAuto & {
onDelete: () => void;
@@ -28,8 +32,12 @@ export type MetadataBoxProps = AutomationManagerAuto & {
};
export const MetadataBox: FC<MetadataBoxProps> = (props) => {
const isValidState = ["on", "off"].includes(props.state);
const langStore = useLang();
const prettyState = ["on", "off"].includes(props.state)
? langStore.get(`AUTOMATION_STATE_${props.state}`)
: props.state;
return (
<div
<Box
className={[
"automation-manager--metadatabox",
props.isSelected ? "selected" : "",
@@ -38,7 +46,13 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
>
<div
className="metadatabox--switch"
title={!isValidState ? "Invalid state" : `Automation is ${props.state}`}
title={
!isValidState
? langStore.get("ERROR_INVALID_AUTOMATION_STATE")
: langStore.get("AUTOMATION_STATE_IS", {
state: prettyState,
})
}
>
<Switch
checked={props.state !== "off"}
@@ -53,28 +67,36 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
<div className="metadatabox--title">
<span className="metadatabox--title--source">
<Tooltip
title={`This automation is located in the file ${props.source_file}. It's currently '${props.state}', it's entity id is '${props.entityId}' and it's automation id is '${props.id}'`}
title={langStore.get("AUTOMATION_METADATA_TOOLTIP_TEXT", {
source_file: props.source_file,
state: prettyState,
entityId: props.entityId,
id: props.id,
})}
>
<Chip
label={`@${props.source_file} (${props.source_file_type}) - ${
props.entityId ?? "n/a"
props.entityId ?? langStore.get("N/A")
}`}
className="text-ellipsis"
/>
</Tooltip>
</span>
<Tooltip title={`ID=${props.id}, EntityID=${props.entityId}`}>
<InputTextView
className="title"
placeholder="Title"
value={props.title}
onChange={props.onTitleUpdate}
disabled={props.isNew}
/>
</Tooltip>
<InputTextView
titleSlug="AUTOMATION_METADATA_TOOLTIP_SIMPLE"
titleParams={{
id: props.id,
entityId: props.entityId,
}}
className="title"
placeholder={langStore.get("TITLE")}
value={props.title}
onChange={props.onTitleUpdate}
disabled={props.isNew}
/>
<InputTextView
className="description"
placeholder="Description"
placeholder={langStore.get("DESCRIPTION")}
value={props.description}
onChange={props.onDescriptionUpdate}
disabled={props.isNew}
@@ -90,24 +112,24 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
</div>
<div className="buttons">
<ButtonIcon
titleSlug="SELECT_AUTOMATION"
className="select"
icon={<SelectIcon />}
onClick={props.onSelect}
title="Select automation"
/>
<ButtonIcon
titleSlug="TRIGGER_AUTOMATION"
className="run"
icon={<RunIcon />}
onClick={props.onRun}
title="Trigger automation"
/>
<ButtonIcon
titleSlug="DELETE_AUTOMATION"
className="delete"
icon={<DeleteForeverIcon />}
onClick={props.onDelete}
title="Delete automation"
/>
</div>
</div>
</Box>
);
};
@@ -6,6 +6,11 @@
position: relative;
height: 100%;
min-width: calc(min(max(25vw, 35em), 50vw));
transition: min-width ease-in-out 500ms,
min-height ease-in-out 500ms,
height ease-in-out 500ms,
width ease-in-out 500ms,
opacity ease-in-out 500ms;
}
.automation-manager--sidebar-box--nav {
@@ -35,10 +40,14 @@
}
.automation-manager--sidebar.hidden {
width: 2.5em;
width: 3em;
min-width: 0;
}
.automation-manager--sidebar.hidden .add-btn {
display: none;
}
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--nav,
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--list,
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--bottom-buttons .add-btn {
@@ -71,6 +71,7 @@ const story = makeStory({
source_file: "automation.yaml",
source_file_type: "list",
configuration_key: ["automation"],
readonly: false,
},
]);
setSelAutoId(id);
@@ -100,6 +101,7 @@ const makeAuto = (
source_file: "automation.yaml",
source_file_type: "list",
configuration_key: ["automation"],
readonly: false,
...data,
};
};
@@ -18,6 +18,7 @@ import {
} from "../types";
import { Button } from "components/Inputs/Buttons/Button";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "services/lang";
export type AutomationManagerSidebarProps = {
tagsDB: TagDB;
@@ -41,6 +42,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
onSelectedAutomationId,
...events
}) => {
const langStore = useLang();
const [searchText, setSearchText] = useState("");
const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>([]);
const [isHidden, setHidden] = useState(false);
@@ -76,9 +78,13 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
].join(" ")}
>
<div className="automation-manager--sidebar-box--nav">
<InputText label="Search" value={searchText} onChange={setSearchText} />
<InputText
label={langStore.get("SEARCH")}
value={searchText}
onChange={setSearchText}
/>
<InputMultiSelect
label="Tags"
label={langStore.get("TAGS")}
selected={selectedTagIdx}
onChange={setSelectedTagIdx}
options={tags}
@@ -109,7 +115,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
color="primary"
className="add-btn"
>
Add
{langStore.get("ADD")}
</Button>
<ButtonIcon
className="hide-btn"
@@ -38,10 +38,11 @@ const automations: AutomationManagerAuto[] = [
description: a.description ?? "",
state: "on",
tags: a.tags,
id: a.id,
id: a.id as string,
isSelected: false,
source_file: "automation.yaml",
source_file_type: "list",
readonly: false,
configuration_key: ["automation"],
}));
@@ -51,7 +52,8 @@ const bigList = bigMockAutoList.map<AutomationManagerAuto>((a) => ({
description: a.description ?? "",
state: "on",
tags: a.tags,
id: a.id,
id: a.id as string,
readonly: false,
isSelected: false,
source_file: "automation.yaml",
source_file_type: "list",
@@ -1,10 +1,10 @@
import { makeStory } from "devUtils";
import { useMockApiService } from "apiService";
import { useMockApiService } from "services/api";
import { AutomationManager } from ".";
import {
MockHAEntitiesProps,
useMockHAEntities,
} from "haService/HAEntities.mock";
} from "services/ha/HAEntities.mock";
import { AutomationData } from "types/automations";
import { createMockAuto } from "utils/mocks";
import { useState } from "react";
@@ -109,7 +109,7 @@ export const MissingAutoInConfig = make({
entity_id: `automation.${auto1.id}`,
attributes: {
id: auto1.id,
friendly_name: auto1.alias,
friendly_name: auto1.alias ?? auto1.id ?? "",
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
@@ -4,8 +4,8 @@ import { FC, useEffect, useRef, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress";
import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "apiService/core";
import { HAEntitiesState } from "haService/HAEntities";
import { ApiService } from "services/api/core";
import { HAEntitiesState } from "services/ha/HAEntities";
import { AutomationManagerLoaded } from "./Loaded";
import { Alert } from "@mui/material";
import { useSnackbar } from "notistack";
@@ -14,7 +14,8 @@ import { getFailures } from "types/validators/helper";
import * as av from "types/validators/autmation";
import { useConfirm } from "material-ui-confirm";
import InputYaml from "components/Inputs/Base/InputYaml";
import { APIResponse } from "apiService/types";
import { APIResponse } from "services/api/types";
import { useLang } from "services/lang";
export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => Promise<any>;
@@ -33,6 +34,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
forceDeleteAutomation: _forceDeleteAutomation,
triggerAutomation: _triggerAutomation,
}) => {
const langStore = useLang();
const snackbr = useSnackbar();
const confirm = useConfirm();
const validationsShown = useRef(false);
@@ -52,9 +54,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
})
.catch((err) => {
console.error(err);
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", String(err)), {
variant: "error",
});
snackbr.enqueueSnackbar(
langStore.get(errorMessage, {
err: String(err),
}),
{
variant: "error",
}
);
setIsSaving(isSaving.filter((k) => k !== name));
});
}
@@ -68,9 +75,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
if (resp.ok) {
refreshAutomations();
} else {
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", resp.error), {
variant: "error",
});
snackbr.enqueueSnackbar(
langStore.get(errorMessage, {
err: resp.error,
}),
{
variant: "error",
}
);
}
}
});
@@ -78,24 +90,26 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
const onAutomationStateChange = (eid: string, on: boolean) =>
wrapPromise(
"changing automation state",
'failed to toggle autonation due to "{{err}}"',
langStore.get("AUTOMATION_MANAGER_STATE_CHANGE"),
"AUTOMATION_MANAGER_STATE_CHANGE_FAIL",
() => _onAutomationStateChange(eid, on)
);
const refreshAutomations = () =>
wrapPromise(
"refreshing automations",
'failed refreshing automations due to "{{err}}"',
langStore.get("AUTOMATION_MANAGER_REFRESH"),
"AUTOMATION_MANAGER_REFRESH_FAIL",
() => _refreshAutomations()
);
const forceDeleteAutomation = (eid: string) =>
wrapPromise("deleting automations", 'failed delete due to "{{err}}"', () =>
_forceDeleteAutomation(eid)
wrapPromise(
langStore.get("AUTOMATION_MANAGER_DELETE"),
"AUTOMATION_MANAGER_DELETE_FAIL",
() => _forceDeleteAutomation(eid)
);
const triggerAutomation = (eid: string) =>
wrapPromise(
"triggering automations",
'failed trigger due to "{{err}}"',
langStore.get("AUTOMATION_MANAGER_TRIGGER"),
"AUTOMATION_MANAGER_TRIGGER_FAIL",
() => _triggerAutomation(eid)
);
@@ -129,7 +143,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
cancellationButtonProps: {
style: { display: "none" },
},
title: "Invalid Automations detected!",
title: langStore.get("ERROR_INVALID_AUTOMATION_DETECTED"),
content: (
<>
<ol className="invalid-automation-modal-list">
@@ -165,6 +179,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
.catch(console.error);
}
}
// eslint-disable-next-line
}, [api.state.automations, confirm]);
// handle bad states
@@ -172,8 +187,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return (
<div className="automation-manager error">
<Alert color="error">
Failed to connect to websocket, please check that your access token is
properly setup
{langStore.get("ERROR_FAILED_CONNECTION_TO_HA")}
</Alert>{" "}
<br />
<code>{JSON.stringify(haEntities.error)}</code>
@@ -205,7 +219,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return (
<div className="automation-manager error">
<Alert color="error">
Failed to load automations from <code>/config</code>
{langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG")}
</Alert>{" "}
<br />
<code>{error}</code>
@@ -237,8 +251,8 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
onAutomationStateChange={onAutomationStateChange}
onAutomationAdd={(auto) =>
wrapApiPromise(
"adding automation",
"Failed to create automation, recieved error: {{err}}!",
langStore.get("AUTOMATION_MANAGER_ADD"),
"AUTOMATION_MANAGER_ADD_FAIL",
() => api.createAutomation(auto) as any
)
}
@@ -258,7 +272,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}
if (!deleteSent) {
snackbr.enqueueSnackbar(
"Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant",
langStore.get("AUTOMATION_MANAGER_DELETE_LIGHT"),
{
variant: "error",
}
@@ -268,15 +282,15 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}}
onAutomationUpdate={(auto) =>
wrapApiPromise(
"updating automation",
"Failed to update automation, recieved error: {{err}}!",
langStore.get("AUTOMATION_MANAGER_UPDATE"),
"AUTOMATION_MANAGER_UPDATE_FAIL",
() => api.updateAutomation(auto) as any
)
}
onUpdateTags={async (aid, t) => {
wrapApiPromise(
"updating tags",
"Failed to update tags, recieved error: {{err}}!",
langStore.get("AUTOMATION_MANAGER_UPDATE_TAGS"),
"AUTOMATION_MANAGER_UPDATE_TAGS_FAIL",
() =>
api.updateTags({
automation_id: aid,
@@ -12,6 +12,7 @@ export type AutomationManagerAuto = AutomationManagerAutoUpdatable & {
source_file: string;
source_file_type: string;
configuration_key: string[];
readonly: boolean;
};
export type AutomationManagerAutoItem = AutomationManagerAuto & {
flags: AutomationManagerItemFlags;
@@ -0,0 +1,94 @@
import Alert from "@mui/material/Alert";
import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "services/api/core";
import { UserProfile } from "services/api/types";
import { InputList } from "components/Inputs/InputList";
import { useLang } from "services/lang";
import { FC, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress";
import InputBoolean from "components/Inputs/Base/InputBoolean";
export type UserProfileProps = {
api: ApiService;
};
export const UserProfileEditor: FC<UserProfileProps> = ({ api }) => {
const [saving, setIsSaving] = useState(false);
const profile = api.state.userProfile;
const lang = useLang();
if (!profile.ready) {
return (
<div className="user-profile">
<Skeleton />
</div>
);
}
if (!profile.ok) {
return (
<div className="user-profile">
<Alert color="error">{JSON.stringify(profile.error)}</Alert>
</div>
);
}
const update =
<K extends keyof UserProfile, D extends UserProfile[K]>(key: K) =>
(data: D) => {
if (profile.ready) {
setIsSaving(true);
api
.setProfile({
...profile.data,
[key]: data,
})
.then(() => {
setIsSaving(false);
});
}
};
const updateFlag =
<K extends keyof UserProfile["flags"], D extends UserProfile["flags"][K]>(
key: K
) =>
(data: D) => {
if (profile.ready) {
setIsSaving(true);
api
.setProfile({
...profile.data,
flags: {
...profile.data.flags,
[key]: data,
},
})
.then(() => {
setIsSaving(false);
});
}
};
return (
<div className="user-profile">
<InputList
label={lang.get("THEME")}
options={["dark", "light"]}
current={profile.data.theme}
onChange={update("theme")}
/>
<InputList
label={lang.get("LANGUAGE")}
options={["eng", "fra", "ita"]}
current={profile.data.lang}
onChange={update("lang")}
/>
<InputBoolean
label={lang.get("FLIPP_GRAPH")}
value={profile.data.flags.flipped ?? false}
onChange={updateFlag("flipped")}
/>
<InputBoolean
label={lang.get("NODES_ROW")}
value={profile.data.flags.useNodesRow ?? true}
onChange={updateFlag("useNodesRow")}
/>
{saving && <LinearProgress />}
</div>
);
};
+50
View File
@@ -0,0 +1,50 @@
.bottom-bar {
width: 100%;
font-size: 0.5em;
display: flex;
align-items: center;
gap: 0.5em;
justify-content: space-between;
}
.bottom-bar>*, .bottom-bar>div>* {
max-height: 1em;
height: 1em;
min-height: 1em;
gap: 0.25em;
}
.bottom-bar #circle {
color: var(--mui-primary-main);
}
.bottom-bar #circle::before {
content: " ";
}
.bottom-bar #circle.error {
color: var(--mui-error-main);
}
.bottom-bar #circle.loaded {
color: var(--mui-success-light);
}
.bottom-bar .settings {
font-size: 0.75em;
padding: 1em 0.5em;
z-index: 10;
}
.bottom-bar .settings svg {
height: 0.5em;
width: 0.5em;
}
.user-profile {
width: 100%;
height: 100%;
min-width: 10em;
min-height: 10em;
}
+42
View File
@@ -0,0 +1,42 @@
import "./index.css";
import { FC, useState } from "react";
import { useHAConnection } from "services/ha/connection";
import { Button } from "components/Inputs/Buttons/Button";
import SettingsSuggestOutlinedIcon from "@mui/icons-material/SettingsSuggestOutlined";
import { useLang } from "services/lang";
import { Modal } from "components/Modal";
import { UserProfileEditor, UserProfileProps } from "./UserProfile";
import { useVersioner } from "services/versioner";
export type BottomBarProps = UserProfileProps;
export const BottomBar: FC<BottomBarProps> = ({ api }) => {
const lang = useLang();
const ha = useHAConnection();
const versionMgr = useVersioner();
const [isOpen, setOpen] = useState(false);
return (
<div className="bottom-bar center row">
<Modal open={isOpen} className="center column">
<UserProfileEditor api={api} />
<Button onClick={() => setOpen(false)}>{lang.get("CLOSE")}</Button>
</Modal>
<span id="connection">
HA{" "}
{ha.status === "loaded"
? lang.get("CONNECTED")
: ha.status === "error"
? lang.get("FAILED")
: lang.get("LOADING")}
<b id="circle" className={ha.status}>
🟢
</b>
</span>
<span>version: {versionMgr.current}</span>
<Button className="settings" onClick={() => setOpen(!isOpen)}>
<SettingsSuggestOutlinedIcon />
{lang.get("USER_PRERENCES")}
</Button>
</div>
);
};
@@ -1,22 +1,17 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { AutomationCondition } from "types/automations/conditions";
import { ConditionNodeBase } from "./ConditionNodeBase";
export default {
title: "ConditionEditor/NodeBase",
component: ConditionNodeBase,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof ConditionNodeBase>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof ConditionNodeBase> = ({
condition,
...args
}) => {
const [data, setData] = useState(condition);
return (
<Page>
const { make, componentMeta } = makeStory({
Component: ConditionNodeBase,
meta: {
title: "ConditionEditor/NodeBase",
},
BaseTemplate: ({ condition, ...args }) => {
const [data, setData] = useState(condition);
return (
<ConditionNodeBase
{...args}
condition={data}
@@ -24,20 +19,20 @@ const Template: ComponentStory<typeof ConditionNodeBase> = ({
setData(data);
}}
/>
</Page>
);
};
);
},
});
export const TemplateViewer = Template.bind({});
TemplateViewer.args = {
export default componentMeta;
export const TemplateViewer = make({
condition: {
condition: "template",
value_template: "states('switch.light_kitchen') == 'on'",
} as AutomationCondition,
};
});
export const MultipleThings = Template.bind({});
MultipleThings.args = {
export const MultipleThings = make({
condition: {
condition: "or",
conditions: [
@@ -62,4 +57,4 @@ MultipleThings.args = {
},
],
} as AutomationCondition,
};
});
@@ -6,12 +6,13 @@ import { FC, useState } from "react";
import { AutomationCondition } from "types/automations/conditions";
import { getSubTypeList } from "utils/automations";
import { getConditionDefaultValues } from "utils/defaults";
import { useHA } from "haService";
import { useHA } from "services/ha";
import InputYaml from "components/Inputs/Base/InputYaml";
import { getViewer } from "./viewRender";
import { getEditor } from "./editorRender";
import useWindowSize from "utils/useWindowSize";
import { ConditionNodeSettings } from "./ConditionNodeSettings";
import { useLang } from "services/lang";
export type ConditionNodeBaseProps = {
condition: AutomationCondition;
@@ -24,6 +25,7 @@ export type ConditionNodeBaseViewMode = "edit" | "yaml" | "view";
export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
// state
const ha = useHA();
const langStore = useLang();
const { isMobile } = useWindowSize();
const [{ isEdited, condition }, setCondition] = useState<{
isEdited: boolean;
@@ -61,6 +63,7 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
onChange={updateCondition}
ha={ha}
initialViewMode="edit"
langStore={langStore}
/>
);
}
@@ -101,6 +104,7 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
},
} as any)
}
prettyOptionLabels={false}
/>
{isMobile && icons}
</div>
@@ -20,7 +20,7 @@ import {
import { genUpdateMethods } from "./nestedUpdater";
import { InputTime } from "components/Inputs/Base/InputTime";
import InputYaml from "components/Inputs/Base/InputYaml";
import { HAService } from "haService";
import { HAService } from "services/ha";
import { DeviceEditor } from "components/DeviceEditor";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import AddIcon from "@mui/icons-material/Add";
@@ -31,6 +31,7 @@ import { prettyName } from "utils/formatting";
import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Buttons/Button";
import { RemoveCircle } from "@mui/icons-material";
import { LangStore } from "services/lang";
interface Editor<C extends AutomationCondition>
extends FC<{
@@ -38,6 +39,7 @@ interface Editor<C extends AutomationCondition>
onChange: (condition: C) => void;
ha: HAService;
initialViewMode: ConditionNodeBaseViewMode;
langStore: LangStore;
}> {}
export const getEditor = (condition: AutomationCondition): Editor<any> => {
@@ -70,11 +72,12 @@ export const getEditor = (condition: AutomationCondition): Editor<any> => {
export const TemplateEditor: Editor<TemplateCondition> = ({
onChange,
condition,
langStore,
}) => {
return (
<>
<InputYaml
label="Template"
label={langStore.get("TEMPLATE")}
value={condition.value_template}
onChange={(value_template) =>
onChange({
@@ -119,6 +122,7 @@ export const DeviceConditionEditor: Editor<DeviceCondition> = ({
export const NumericStateEditor: Editor<NumericCondition> = ({
onChange,
condition,
langStore,
}) => {
return (
<>
@@ -133,7 +137,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
}
/>
<InputText
label="Attribute"
label={langStore.get("ATTRIBUTE")}
value={condition.attribute ?? ""}
onChange={(attribute) =>
onChange({
@@ -143,7 +147,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
}
/>
<InputNumber
label="Above"
label={langStore.get("ABOVE")}
value={condition.above ? Number(condition.above) : undefined}
onChange={(above) =>
onChange({
@@ -153,7 +157,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
}
/>
<InputNumber
label="Below"
label={langStore.get("BELOW")}
value={condition.below ? Number(condition.below) : undefined}
onChange={(below) =>
onChange({
@@ -163,7 +167,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
}
/>
<InputYaml
label="Template"
label={langStore.get("TEMPLATE")}
value={condition.value_template ?? ""}
onChange={(value_template) =>
onChange({
@@ -221,6 +225,7 @@ export const StateEditor: Editor<StateCondition> = ({
onChange,
condition,
ha,
langStore,
}) => {
const restrictToDomain =
!condition.entity_id || condition.entity_id.length === 0
@@ -241,7 +246,7 @@ export const StateEditor: Editor<StateCondition> = ({
}
/>
<InputAutoComplete
label="Attribute"
label={langStore.get("ATTRIBUTE")}
value={condition.attribute ?? ""}
options={ha.entities.getAttributes(condition.entity_id)}
multiple={false}
@@ -253,11 +258,11 @@ export const StateEditor: Editor<StateCondition> = ({
}
/>
<InputText
label="State"
label={langStore.get("STATE")}
value={String(condition.state)}
placeholder={ha.entities
.getStates(condition.entity_id, condition.attribute)
.join(" or ")}
.join(` ${langStore.get("OR").toLowerCase()} `)}
onChange={(state) =>
onChange({
...condition,
@@ -266,7 +271,7 @@ export const StateEditor: Editor<StateCondition> = ({
}
/>
<InputTime
label="For"
label={langStore.get("FOR")}
value={condition.for}
onChange={(_for) =>
onChange({
@@ -280,7 +285,11 @@ export const StateEditor: Editor<StateCondition> = ({
};
type TimeEditorShows = "after" | "before" | "weekday";
export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
export const TimeEditor: Editor<TimeCondition> = ({
onChange,
condition,
langStore,
}) => {
const [shows, setShows] = useState<TimeEditorShows[]>(
Object.keys(condition).filter((k) =>
["after", "before", "weekday"].includes(k)
@@ -321,19 +330,19 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
<b className="label">{prettyName(show)}</b>
<InputAutoComplete
className="condition-node--time-editor--weekday"
label="Weekday"
label={langStore.get("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",
mon: langStore.get("DAY_mon"),
tue: langStore.get("DAY_tue"),
wed: langStore.get("DAY_wed"),
thu: langStore.get("DAY_thu"),
fri: langStore.get("DAY_fri"),
sat: langStore.get("DAY_sat"),
sun: langStore.get("DAY_sun"),
}[opt];
}}
onChange={(weekday: any) =>
@@ -362,7 +371,7 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
{shows.length < 3 && (
<InputList
className="condition-node--time-editor--new"
label="Option"
label={langStore.get("OPTION")}
options={["after", "before", "weekday"].filter(
(k: any) => !shows.includes(k)
)}
@@ -378,11 +387,12 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
export const TriggerEditor: Editor<TriggerCondition> = ({
onChange,
condition,
langStore,
}) => {
return (
<>
<InputText
label="Trigger ID"
label={langStore.get("TRIGGER_ID")}
value={condition.id}
onChange={(id) =>
onChange({
@@ -395,11 +405,15 @@ export const TriggerEditor: Editor<TriggerCondition> = ({
);
};
export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => {
export const ZoneEditor: Editor<ZoneCondition> = ({
onChange,
condition,
langStore,
}) => {
return (
<>
<InputEntity
label="Zone"
label={langStore.get("ZONE")}
value={condition.zone ?? []}
multiple
onChange={(zone) =>
@@ -411,7 +425,7 @@ export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => {
restrictToDomain={["zone"]}
/>
<InputEntity
label="Entity with Location"
label={langStore.get("ENTITY_WITH_LOCATION")}
value={condition.entity_id}
multiple
onChange={(entity_id) =>
@@ -1,26 +1,22 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { MockPage, Page } from "components/Page";
import { useState } from "react";
import { AutomationCondition } from "types/automations/conditions";
import { ConditionEditor } from ".";
import { makeStory } from "devUtils";
export default {
title: "ConditionEditor",
component: ConditionEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
initialViewMode: "edit",
const { make, componentMeta } = makeStory({
Component: ConditionEditor,
meta: {
title: "ConditionEditor",
args: {
initialViewMode: "edit",
},
},
} as ComponentMeta<typeof ConditionEditor>;
const Template: ComponentStory<typeof ConditionEditor> = ({
condition,
...args
}) => {
const [data, setData] = useState(condition);
return (
<Page>
BaseTemplate: ({ condition, ...args }) => {
const [data, setData] = useState(condition);
return (
<ConditionEditor
{...args}
condition={data}
@@ -28,29 +24,28 @@ const Template: ComponentStory<typeof ConditionEditor> = ({
setData(data);
}}
/>
</Page>
);
};
);
},
});
export const TemplateViewer = Template.bind({});
TemplateViewer.args = {
export default componentMeta;
export const TemplateViewer = make({
condition: {
condition: "template",
value_template: "states('switch.light_kitchen') == 'on'",
} as AutomationCondition,
};
});
export const NumericStateViewer = Template.bind({});
NumericStateViewer.args = {
export const NumericStateViewer = make({
condition: {
condition: "numeric_state",
entity_id: "sensor.humidity_kitchen",
above: "10",
} as AutomationCondition,
};
});
export const LogicCondition = Template.bind({});
LogicCondition.args = {
export const LogicCondition = make({
condition: {
condition: "or",
conditions: [
@@ -81,9 +76,8 @@ LogicCondition.args = {
},
],
} as AutomationCondition,
};
export const TimeCondition = Template.bind({});
TimeCondition.args = {
});
export const TimeCondition = make({
condition: {
condition: "or",
conditions: [
@@ -104,7 +98,7 @@ TimeCondition.args = {
},
],
} as AutomationCondition,
};
});
export const MultipleConditions: ComponentStory<typeof ConditionEditor> = (
args
@@ -134,12 +128,12 @@ export const MultipleConditions: ComponentStory<typeof ConditionEditor> = (
],
});
return (
<Page>
<MockPage>
<ConditionEditor
onUpdate={setState}
onDelete={() => {}}
condition={state}
/>
</Page>
</MockPage>
);
};
@@ -0,0 +1,92 @@
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { makeStory } from "devUtils";
import { NodesRow } from ".";
import { createUpdater } from "../updater/index";
const { make, componentMeta } = makeStory({
Component: NodesRow,
BaseTemplate: (props) => {
const updater = createUpdater({
openModal: () => {},
action: {
data: [],
onUpdate: () => {},
},
condition: {
data: [],
onUpdate: () => {},
},
trigger: {
data: [],
onUpdate: () => {},
},
});
return <NodesRow {...props} stateUpdater={updater} />;
},
meta: {
title: "DAGGraph/NodesRow/Single",
args: {
type: "trigger",
data: [],
sequenceNodeDims: DEFAULT_DIMS.node,
},
},
});
export default componentMeta;
export const Empty = make({});
export const One = make({
data: [
{
platform: "calendar",
event: "start",
},
],
});
export const Many = make({
data: [
{
platform: "calendar",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
].map((n, id) => ({
...n,
id: `Trigger ${id}`,
})),
});
@@ -0,0 +1,95 @@
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { makeStory } from "devUtils";
import { createUpdater } from "../updater";
import { TriggerConditionNodeRow } from ".";
const { make, componentMeta } = makeStory({
Component: TriggerConditionNodeRow,
BaseTemplate: (props) => {
const updater = createUpdater({
openModal: () => {},
action: {
data: [],
onUpdate: () => {},
},
condition: {
data: [],
onUpdate: () => {},
},
trigger: {
data: [],
onUpdate: () => {},
},
});
return <TriggerConditionNodeRow {...props} stateUpdater={updater} />;
},
meta: {
title: "DAGGraph/NodesRow/TriggerAndConditions",
args: {
condition: [],
trigger: [],
sequenceNodeDims: DEFAULT_DIMS.node,
},
},
});
export default componentMeta;
export const Empty = make({});
export const One = make({
trigger: [
{
platform: "calendar",
event: "start",
},
],
condition: [
{
condition: "and",
conditions: [],
},
],
});
export const Many = make({
trigger: [
{
platform: "calendar",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
],
});
@@ -0,0 +1,87 @@
/* .nodes-row--outer {
--nodes-row-height: 10em;
min-width: 100%;
width: 100%;
max-width: 100%;
min-height: var(--nodes-row-height);
height: var(--nodes-row-height);
max-height: var(--nodes-row-height);
overflow: auto;
}
.nodes-row--inner {
max-width: calc(100% - 4em);
width: calc(100% - 4em);
min-height: calc(var(--nodes-row-height) - 2em);
max-height: calc(var(--nodes-row-height) - 2em);
gap: 2em;
padding-left: 1em;
padding-right: 1em;
border-style: solid;
border-top-width: 0.125em;
border-left-width: 1px;
border-right-width: 1px;
border-radius: 10px;
border-bottom-color: var(--mui-grey-500);
border-left-color: var(--mui-grey-700);
border-right-color: var(--mui-grey-700);
border-top-color: var(--sequence-node-color);
overflow: auto;
} */
.nodes-row--inner.collection-nodes--wrap {
--node-height: none !important;
--node-width: 100% !important;
margin: 0;
display: flex;
flex: 1;
min-width: 95%;
max-width: 95%;
}
.nodes-row--inner.collection-nodes--wrap .collection-nodes {
min-width: 90%;
min-height: 8em;
max-height: 8em;
overflow: hidden;
}
.trigger-condition-nodes-row {
gap: 0.25em;
}
.fullscreen .trigger-condition-nodes-row .nodes-row--inner {
opacity: 0;
height: 0;
z-index: -10;
}
.nodes-row--inner.collection-nodes--wrap .collection-nodes .collection-nodes--inner {
min-width: inherit;
width: inherit;
max-width: inherit;
padding-bottom: 0 !important;
padding-left: 0 !important;
min-height: 5em;
max-height: 7em;
}
.mobile .trigger-condition-nodes-row {
flex-direction: column;
}
.mobile .nodes-row.collection-nodes--wrap .collection-nodes {
width: 80%;
}
@@ -0,0 +1,85 @@
import "./index.css";
import { AutomationNode, AutomationNodeMapping } from "types/automations";
import { useHA } from "services/ha";
import { CollectionNodeElement } from "components/DAGGraph/nodes/CollectionNode/CollectionNodeElement";
import { Size } from "components/DAGGraph/elements/types";
import { DAGGraphUpdater } from "components/DAGGraph/updater";
import { makeCollectionNodeMakerChildProps } from "components/DAGGraph/elements/helpers";
import { AutomationCondition } from "types/automations/conditions";
import { AutomationTrigger } from "types/automations/triggers";
import { FC } from "react";
export type NodesRowProps<
K extends keyof AutomationNodeMapping,
T extends AutomationNode<K>
> = {
type: K;
data: T[];
stateUpdater: DAGGraphUpdater;
sequenceNodeDims: Size;
};
export function NodesRow<
K extends keyof AutomationNodeMapping,
T extends AutomationNode<K>
>({
type: collectionType,
data,
sequenceNodeDims,
stateUpdater,
}: NodesRowProps<K, T>) {
const { namer } = useHA();
return (
<div className="nodes-row--outer center row">
<CollectionNodeElement
className="nodes-row--inner"
width={0}
height={0}
nodes={data.map((node, i) =>
makeCollectionNodeMakerChildProps(
collectionType,
node,
i,
stateUpdater,
namer
)
)}
onAddNode={() => stateUpdater.basic[collectionType].addNode(null)}
collectionType={collectionType}
sequenceNode={sequenceNodeDims}
flipped
/>
</div>
);
}
export type TriggerConditionNodeRowProps = {
condition: AutomationCondition[];
trigger: AutomationTrigger[];
stateUpdater: DAGGraphUpdater;
sequenceNodeDims: Size;
};
export const TriggerConditionNodeRow: FC<TriggerConditionNodeRowProps> = ({
condition,
trigger,
stateUpdater,
sequenceNodeDims,
}) => {
return (
<div className={["trigger-condition-nodes-row column"].join(" ")}>
<NodesRow
data={trigger}
type="trigger"
stateUpdater={stateUpdater}
sequenceNodeDims={sequenceNodeDims}
/>
<NodesRow
data={condition}
type="condition"
stateUpdater={stateUpdater}
sequenceNodeDims={sequenceNodeDims}
/>
</div>
);
};
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more