Compare commits

..
42 Commits
Author SHA1 Message Date
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
139 changed files with 2706 additions and 1502 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] - Version [e.g. 22]
**Additional context** **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. Add any other context about the problem here.
**Shortumation Logs**
```log
<--- copy here --->
```
+9 -8
View File
@@ -8,6 +8,9 @@ on:
push: push:
branches: branches:
- main - main
concurrency:
group: build-${{ github.event.inputs.version || github.head_ref || github.ref }}
cancel-in-progress: true
jobs: jobs:
metadata: metadata:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -15,12 +18,6 @@ jobs:
outputs: outputs:
version: ${{ steps.version.outputs.VERSION }} version: ${{ steps.version.outputs.VERSION }}
steps: 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 - name: Check out repository
uses: actions/checkout@v3 uses: actions/checkout@v3
with: with:
@@ -76,12 +73,14 @@ jobs:
needs: needs:
- metadata - metadata
- build-web - build-web
permissions:
packages: write
strategy: strategy:
matrix: matrix:
arch: arch:
- "aarch64" - "aarch64"
- "amd64" - "amd64"
- "armhf" # see https://github.com/asosnovsky/Shortumation/issues/147 - "armhf"
- "armv7" - "armv7"
- "i386" - "i386"
@@ -89,6 +88,9 @@ jobs:
- name: Check out repository - name: Check out repository
uses: actions/checkout@v3 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 - name: Login to DockerHub
uses: docker/login-action@v2.0.0 uses: docker/login-action@v2.0.0
with: with:
@@ -103,7 +105,6 @@ jobs:
- name: ${{ matrix.arch }} / ${{ needs.metadata.outputs.version }} - name: ${{ matrix.arch }} / ${{ needs.metadata.outputs.version }}
uses: home-assistant/builder@master uses: home-assistant/builder@master
continue-on-error: true
with: with:
args: | args: |
--${{ matrix.arch }} \ --${{ matrix.arch }} \
+34 -31
View File
@@ -13,12 +13,16 @@ name: "CodeQL"
on: on:
push: push:
branches: [ "main" ] branches: ["main"]
pull_request: pull_request:
# The branches below must be a subset of the branches above # The branches below must be a subset of the branches above
branches: [ "main" ] branches: ["main"]
schedule: schedule:
- cron: '26 21 * * 2' - cron: "26 21 * * 2"
concurrency:
group: codeql-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs: jobs:
analyze: analyze:
@@ -32,41 +36,40 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
language: [ 'javascript', 'python' ] language: ["javascript", "python"]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v3 uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v2 uses: github/codeql-action/init@v2
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file. # 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. # 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. # 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
# 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
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # queries: security-extended,security-and-quality
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# ℹ️ Command-line programs to run using the OS shell. # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # 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. # ℹ️ Command-line programs to run using the OS shell.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# - run: | # If the Autobuild fails above, remove it and uncomment the following three lines.
# echo "Run, Build Application using script" # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis # - run: |
uses: github/codeql-action/analyze@v2 # 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 # 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 # 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] on: [pull_request]
permissions: permissions:
contents: read contents: read
concurrency:
group: deprev-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs: jobs:
dependency-review: dependency-review:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: 'Checkout Repository' - name: "Checkout Repository"
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: 'Dependency Review' - name: "Dependency Review"
uses: actions/dependency-review-action@v2 uses: actions/dependency-review-action@v2
+3
View File
@@ -6,6 +6,9 @@ on:
pull_request: pull_request:
branches: branches:
- main - main
concurrency:
group: test-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs: jobs:
metadata: metadata:
runs-on: ubuntu-latest runs-on: ubuntu-latest
+23 -134
View File
@@ -1,9 +1,29 @@
# Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge) # Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge)
## [0.6.2] - Patches ## [0.7.1] Bugfixes + Italian!
- Attempting to increasing websocket file limit - Added support for automations that do not have an `id`
- Support for all !include directives - 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! ## [0.6.1] - v0.6.0 Split Config Support & Better Error handling!
@@ -20,11 +40,6 @@
- Better global error capture - Better global error capture
![image](https://user-images.githubusercontent.com/7451445/185441268-9dbde36e-b28b-4a13-bd7f-45ae23834e78.png) ![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 ## [0.5.2] - Better Controls
- Add automation trigger - Add automation trigger
@@ -45,11 +60,6 @@
- Websockets now live-refresh when updates occur - 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! ## [0.3.4] - Condition/Trigger Editor Upgrades!
- Many condition editor fixes - Many condition editor fixes
@@ -66,19 +76,6 @@
![image](https://user-images.githubusercontent.com/7451445/180238004-4b04f13a-77a2-4c4c-9144-963dbc394bf4.png) ![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 ## [0.3.0] - Complete Refactor of Graphs
- Added visual support for - Added visual support for
@@ -97,113 +94,5 @@
![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png) ![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png)
## [0.1.22] - Many Visual improvements
- 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/), 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). 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 ARG BUILD_ARCH
# <--- Main Image --> # <--- Main Image -->
FROM python:3.10-slim-buster FROM python:3.10-slim-bullseye
WORKDIR /app WORKDIR /app
# <--- Post-Build Args --> # <--- Post-Build Args -->
@@ -10,6 +10,7 @@ ARG BUILD_VERSION
# <--- Environment Variables --> # <--- Environment Variables -->
ENV BUILD_VERSION $BUILD_VERSION ENV BUILD_VERSION $BUILD_VERSION
ENV BUILD_ARCH $BUILD_ARCH
# <--- System Wide Dependencies --> # <--- System Wide Dependencies -->
ENV LANG C.UTF-8 ENV LANG C.UTF-8
@@ -45,3 +46,4 @@ ENTRYPOINT [ "/app/bin/run.sh" ]
CMD [ "/app" ] CMD [ "/app" ]
LABEL org.opencontainers.image.source https://github.com/asosnovsky/Shortumation 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!"
+25 -15
View File
@@ -1,20 +1,30 @@
get_index # unused function (src/api/app.py:43) get_index # unused function (src/api/app.py:41)
list_autos # unused function (src/api/routes/automations.py:13) list_autos # unused function (src/api/routes/automations.py:14)
insert_auto # unused function (src/api/routes/automations.py:28) insert_auto # unused function (src/api/routes/automations.py:30)
update_auto # unused function (src/api/routes/automations.py:32) update_auto # unused function (src/api/routes/automations.py:35)
delete_auto # unused function (src/api/routes/automations.py:40) delete_auto # unused function (src/api/routes/automations.py:45)
read_details # unused function (src/api/routes/details.py:11) 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) read_ping # unused function (src/api/routes/ping.py:10)
websocket_endpoint # unused function (src/api/routes/socket.py:13) websocket_endpoint # unused function (src/api/routes/socket.py:13)
params # unused variable (src/api/types.py:16) params # unused variable (src/api/types.py:16)
total_items # unused variable (src/api/types.py:17) total_items # unused variable (src/api/types.py:17)
data # unused variable (src/api/types.py:18) alias # unused variable (src/automations/types.py:36)
trigger_variables # unused variable (src/automations/types.py:13) description # unused variable (src/automations/types.py:37)
trigger # unused variable (src/automations/types.py:15) trigger_variables # unused variable (src/automations/types.py:38)
condition # unused variable (src/automations/types.py:16) mode # unused variable (src/automations/types.py:39)
action # unused variable (src/automations/types.py:17) trigger # unused variable (src/automations/types.py:40)
_.to_json # unused method (src/automations/types.py:45) condition # unused variable (src/automations/types.py:41)
_.automation_tags # unused property (src/hass_config/loader.py:17) 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) json_dumps # unused function (src/json_serializer.py:5)
SecretValue # unused class (src/yaml_serializer/__init__.py:40) theme # unused variable (src/user_profile.py:10)
EnvVar # unused class (src/yaml_serializer/__init__.py:78) lang # unused variable (src/user_profile.py:11)
SecretValue # unused class (src/yaml_serializer/__init__.py:48)
EnvVar # unused class (src/yaml_serializer/__init__.py:186)
+4 -6
View File
@@ -3,13 +3,13 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from src.automations.manager import AutomationManager
from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER
from src.hass_config.loader import HassConfig
from .routes import automations, details, ping, socket from .routes import automations, details, ping, socket
def make_app(automation_mgr: AutomationManager) -> FastAPI: def make_app(hass_config: HassConfig) -> FastAPI:
app = FastAPI() app = FastAPI()
has_web_folder = (ROOT_FOLDER / "web").exists() has_web_folder = (ROOT_FOLDER / "web").exists()
if has_web_folder: 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(ping.router, prefix="/ping")
app.include_router( app.include_router(
automations.make_automation_router(automation_mgr), prefix=f"{API_PREFIX}/automations" automations.make_automation_router(hass_config), prefix=f"{API_PREFIX}/automations"
)
app.include_router(
details.make_details_router(automation_mgr.hass_config), prefix=f"{API_PREFIX}/details"
) )
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.include_router(socket.router, prefix=f"{API_PREFIX}/socket")
@app.get("/") @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.manager import AutomationManager
from src.automations.types import Automation, ExtenededAutomation from src.automations.types import Automation, ExtenededAutomation
from src.errors import ErrorSet 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 = APIRouter()
@router.post("/list") @router.post("/list", response_model_exclude_unset=True, response_model_exclude_none=True)
def list_autos(body: ListParams) -> ListData[ExtenededAutomation]: def list_autos(body: ListParams) -> ListData[ExtenededAutomation]:
automations = AutomationManager(hass_config)
try: try:
automations.reload() automations.reload()
return ListData( return ListData(
@@ -27,18 +29,26 @@ def make_automation_router(automations: AutomationManager) -> APIRouter:
@router.post("/item") @router.post("/item")
def insert_auto(body: Automation): 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) automations.create(body)
@router.put("/item") @router.put("/item")
def update_auto(body: ExtenededAutomation): 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) automations.update(body)
@router.post("/item/tags") @router.post("/item/tags")
def update_tags(body: UpdateTags): def update_tags(body: UpdateTags):
automations = AutomationManager(hass_config)
automations.update_tags(body.automation_id, body.tags) automations.update_tags(body.automation_id, body.tags)
@router.delete("/item") @router.delete("/item")
def delete_auto(body: ExtenededAutomation): def delete_auto(body: ExtenededAutomation):
automations = AutomationManager(hass_config)
try: try:
automations.delete(body) automations.delete(body)
except FailedDeletion as err: 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.automations.loader import extract_automation_refs
from src.env import BUILD_VERSION, HASSIO_TOKEN, HASSIO_WS from src.env import BUILD_VERSION, HASSIO_TOKEN, HASSIO_WS
from src.hass_config import HassConfig from src.hass_config import HassConfig
from src.user_profile import UserProfile
def make_details_router(hass_config: HassConfig) -> APIRouter: def make_details_router(hass_config: HassConfig) -> APIRouter:
@@ -16,10 +17,17 @@ def make_details_router(hass_config: HassConfig) -> APIRouter:
"hassio_url": HASSIO_WS, "hassio_url": HASSIO_WS,
"config": hass_config.get_configuration_path(), "config": hass_config.get_configuration_path(),
"tags": hass_config.get_automation_tags_path(), "tags": hass_config.get_automation_tags_path(),
"autos": { "profile": hass_config.get_profile_path(),
config_key: auto_file "autos": list(map(repr, extract_automation_refs(hass_config))),
for config_key, auto_file in 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 return router
+1 -2
View File
@@ -1,6 +1,5 @@
from src.api.app import make_app from src.api.app import make_app
from src.automations.manager import AutomationManager
from src.hass_config import find_hass_config from src.hass_config import find_hass_config
hass_config = 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 from typing import Iterable
import json
import sqlite3
from contextlib import contextmanager
from pathlib import Path
from typing import Iterable, Iterator
from src.logger import get_logger from src.logger import get_logger
from .errors import ( from .errors import DBNoAutomationFound, RepeatedAutomationId
DBDataError,
DBError,
DBNoAutomationFound,
RepeatedAutomationId,
)
from .types import ExtenededAutomation from .types import ExtenededAutomation
logger = get_logger(__file__) 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: class AutomationDBConnection:
def __init__(self, db_file: Path) -> None: def __init__(self) -> None:
self.db_file = db_file self.db: dict[str, ExtenededAutomation] = {}
self.missing_id_db: list[ExtenededAutomation] = []
def reset(self): def reset(self):
self.db_file.unlink(missing_ok=True) self.db = {}
self.create_db() self.missing_id_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
);
"""
)
def insert_automations(self, automations: list[ExtenededAutomation]): def insert_automations(self, automations: list[ExtenededAutomation]):
with self.get_cur() as cur: repeated_automations = []
for automation in automations: for automation in automations:
try: if automation.id is None:
cur.execute( self.missing_id_db.append(automation)
f""" elif self.db.get(automation.id, None) is None:
INSERT INTO {automations_tbl} VALUES ( self.db[automation.id] = automation
"{automation.id}", else:
"{automation.alias}", repeated_automations.append(
"{automation.description}", f"automation id '{automation.id}' in '{automation.source_file}' was already seen before. Please check for duplicate automation ids in your files."
"{automation.mode}", )
"{automation.source_file}", if len(repeated_automations) > 0:
"{automation.source_file_type}", raise RepeatedAutomationId(repeated_automations)
"{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
def get_automation(self, automation_id: str) -> ExtenededAutomation: def get_automation(self, automation_id: str) -> ExtenededAutomation:
with self.get_cur() as cur: if a := self.db.get(automation_id, None):
cur.execute( return a
f'SELECT rest, source_file, source_file_type, configuration_key FROM {automations_tbl} WHERE id = "{automation_id}"' # nosec raise DBNoAutomationFound(automation_id)
)
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)
def list_automations(self, offset: int, limit: int) -> Iterable[ExtenededAutomation]: def list_automations(self, offset: int, limit: int) -> Iterable[ExtenededAutomation]:
with self.get_cur() as cur: for i, auto in enumerate([*self.missing_id_db, *self.db.values()]):
for [rest, source_file, source_file_type, configuration_key] in cur.execute( if i >= offset and i < limit + offset:
f"SELECT rest, source_file, source_file_type, configuration_key FROM {automations_tbl} LIMIT {limit} OFFSET {offset}" # nosec yield auto
):
yield decode_auto(rest, source_file, source_file_type, configuration_key)
def count_automations(self) -> int: def count_automations(self) -> int:
with self.get_cur() as cur: return len(self.db)
return cur.execute(f"SELECT count(id) FROM {automations_tbl}").fetchone()[0] # nosec
+12 -6
View File
@@ -236,9 +236,11 @@ def load_automation_inline_ref(
) -> Iterator[ExtenededAutomation]: ) -> Iterator[ExtenededAutomation]:
for auto in inline_automation.automations: for auto in inline_automation.automations:
try: try:
cleaned_automation = clean_automation(auto)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(auto), **cleaned_automation,
tags=tag_manager.get(auto["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=inline_automation.configuration_key, configuration_key=inline_automation.configuration_key,
source_file=str(inline_automation.source_file.resolve().relative_to(root_path)), source_file=str(inline_automation.source_file.resolve().relative_to(root_path)),
source_file_type="inline", source_file_type="inline",
@@ -286,9 +288,11 @@ def load_automation_path(
if isinstance(automations, dict): if isinstance(automations, dict):
try: try:
cleaned_automation = clean_automation(automations)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(automations), **cleaned_automation,
tags=tag_manager.get(automations["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key, configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)), source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="obj", source_file_type="obj",
@@ -305,9 +309,11 @@ def load_automation_path(
return return
for automation in automations: for automation in automations:
try: try:
cleaned_automation = clean_automation(automation)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(automation), **cleaned_automation,
tags=tag_manager.get(automation["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key, configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)), source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="list", source_file_type="list",
+8 -13
View File
@@ -1,8 +1,6 @@
from pathlib import Path
from tempfile import mktemp
from typing import Optional, Union 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.hass_config.loader import HassConfig
from src.logger import get_logger from src.logger import get_logger
from src.yaml_serializer import dump_yaml, load_yaml from src.yaml_serializer import dump_yaml, load_yaml
@@ -13,11 +11,7 @@ from .errors import (
DBError, DBError,
InvalidAutomationFile, InvalidAutomationFile,
) )
from .loader import ( from .loader import get_base_automation_key, load_and_iter_automations
get_base_automation_key,
load_and_iter_automations,
load_automation_path,
)
from .tags import TagManager from .tags import TagManager
from .types import Automation, ExtenededAutomation from .types import Automation, ExtenededAutomation
@@ -28,12 +22,9 @@ class AutomationManager:
def __init__( def __init__(
self, self,
hass_config: HassConfig, hass_config: HassConfig,
db_path: Optional[Path] = None,
) -> None: ) -> None:
if db_path is None:
db_path = Path(mktemp()) # nosec
self.hass_config = hass_config self.hass_config = hass_config
self.db = AutomationDBConnection(db_path) self.db = AutomationDBConnection()
self.tag_path = hass_config.get_automation_tags_path() self.tag_path = hass_config.get_automation_tags_path()
self.tag_manager = TagManager() self.tag_manager = TagManager()
self.reload_tags() self.reload_tags()
@@ -66,7 +57,7 @@ class AutomationManager:
if len(batch) >= 0: if len(batch) >= 0:
self.db.insert_automations(batch) self.db.insert_automations(batch)
except DBError as e: except DBError as e:
logger.warning(e) logger.warning(FormattedError.from_error(e))
errors.append(e) errors.append(e)
if len(errors) > 0: if len(errors) > 0:
raise ErrorSet(*errors) raise ErrorSet(*errors)
@@ -93,6 +84,8 @@ class AutomationManager:
) )
def update(self, automation: ExtenededAutomation, create_if_not_found: bool = False): 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 automation_path = self.hass_config.root_path / automation.source_file
if not automation_path.parent.exists(): if not automation_path.parent.exists():
automation_path.parent.mkdir(parents=True) automation_path.parent.mkdir(parents=True)
@@ -159,6 +152,8 @@ class AutomationManager:
self.tag_manager.save(self.tag_path) self.tag_manager.save(self.tag_path)
def delete(self, automation: ExtenededAutomation): 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 automation_path = self.hass_config.root_path / automation.source_file
if automation.source_file_type == "obj": if automation.source_file_type == "obj":
automation_path.unlink(missing_ok=True) automation_path.unlink(missing_ok=True)
+25 -7
View File
@@ -15,18 +15,24 @@ class InlineAutomation(NamedTuple):
source_file: Path source_file: Path
automations: list[dict] automations: list[dict]
def __repr__(self) -> str:
return f"InlineAutomation(configuration_key='{self.configuration_key}', source_file='{self.source_file}')"
class IncludedAutoamtion(NamedTuple): class IncludedAutoamtion(NamedTuple):
configuration_key: ConfigurationKey configuration_key: ConfigurationKey
ref: IncludedYamlDir ref: IncludedYamlDir
def __repr__(self) -> str:
return f"InlineAutomation(configuration_key='{self.configuration_key}', ref='{self.ref}')"
ExtractedAutomation = InlineAutomation | IncludedAutoamtion ExtractedAutomation = InlineAutomation | IncludedAutoamtion
AutomationExtractedIter = Iterator[ExtractedAutomation] AutomationExtractedIter = Iterator[ExtractedAutomation]
class BaseAutomation(BaseModel): class BaseAutomation(BaseModel):
id: str id: Optional[str]
alias: Optional[str] = None alias: Optional[str] = None
description: Optional[str] = None description: Optional[str] = None
trigger_variables: Optional[dict[str, Union[str, int, bool, float]]] = None trigger_variables: Optional[dict[str, Union[str, int, bool, float]]] = None
@@ -35,27 +41,39 @@ class BaseAutomation(BaseModel):
condition: list[dict] = [] condition: list[dict] = []
action: list[dict] = [] action: list[dict] = []
def to_primitive(self): def to_primitive(self, exclude_unset=True, exclude_none=True, **kwrgs):
return self.dict(exclude_unset=True, exclude_none=True) return BaseModel.dict(self, exclude_unset=exclude_unset, exclude_none=exclude_none, **kwrgs)
def dict(self, **kwrgs):
kwrgs["exclude_unset"] = True
kwrgs["exclude_none"] = True
return self.to_primitive(
**kwrgs,
)
class Automation(BaseAutomation): class Automation(BaseAutomation):
tags: dict[str, str] = Field(default_factory=dict) tags: dict[str, str] = Field(default_factory=dict)
def to_primitive(self, include_tags: bool = False): def to_primitive(self, include_tags: bool = False, **kwrgs):
out = super().to_primitive() out = super().to_primitive(**kwrgs)
if not include_tags and out.get("tags", None) is not None: if not include_tags and out.get("tags", None) is not None:
del out["tags"] del out["tags"]
if include_tags and out.get("tags", None) is None:
out["tags"] = {}
return out return out
def dict(self, **kwrgs):
return BaseAutomation.dict(self, **kwrgs, include_tags=True)
class ExtenededAutomation(Automation): class ExtenededAutomation(Automation):
source_file: str source_file: str
source_file_type: Literal["list", "obj", "inline"] source_file_type: Literal["list", "obj", "inline"]
configuration_key: ConfigurationKey configuration_key: ConfigurationKey
def to_primitive(self, include_tags: bool = False): def to_primitive(self, include_tags: bool = False, **kwrgs):
out = super().to_primitive(include_tags=include_tags) out = super().to_primitive(include_tags=include_tags, **kwrgs)
del out["source_file"] del out["source_file"]
del out["source_file_type"] del out["source_file_type"]
del out["configuration_key"] del out["configuration_key"]
+23 -1
View File
@@ -1,3 +1,7 @@
import traceback
from typing import NamedTuple
class ErrorSet(Exception): class ErrorSet(Exception):
"""An exception collection exception""" """An exception collection exception"""
@@ -7,6 +11,24 @@ class ErrorSet(Exception):
def gen_message(self): def gen_message(self):
if len(self.errors) > 1: 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: else:
return str(self.errors[0].args) 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: def get_automation_tags_path(self) -> Path:
return self.get_shortumations_path() / "tags.yaml" 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: def get_configuration_path(self) -> Path:
return self.root_path / "configuration.yaml" return self.root_path / "configuration.yaml"
+24
View File
@@ -0,0 +1,24 @@
from typing import Literal
from pydantic import BaseModel
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"
@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))
@@ -1 +1,38 @@
automation: !include ../automations/ui.yaml 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,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,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
+4 -39
View File
@@ -1,27 +1,13 @@
from pathlib import Path
from unittest import TestCase
import yaml import yaml
from fastapi.testclient import TestClient
from src.api.app import make_app
from src.automations.types import Automation, ExtenededAutomation from src.automations.types import Automation, ExtenededAutomation
from tests.utils import ( from tests.utils import (
HA_CONFIG2_EXAMPLE, HA_CONFIG2_EXAMPLE,
HA_CONFIG6_EXAMPLE, HA_CONFIG6_EXAMPLE,
HA_CONFIG10_EXAMPLE, HA_CONFIG10_EXAMPLE,
get_example_automation_loader,
) )
from .util import BaseTestCase
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))
class automation_pagination_tests(BaseTestCase): class automation_pagination_tests(BaseTestCase):
@@ -90,20 +76,13 @@ class automation_pagination_tests(BaseTestCase):
class automation_pagination_tests_2(automation_pagination_tests): class automation_pagination_tests_2(automation_pagination_tests):
source_config_path = HA_CONFIG2_EXAMPLE
test_params = { test_params = {
"total": 1, "total": 1,
"subtest2_found_items": 0, "subtest2_found_items": 0,
"subtest1_found_items": 1, "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): class automation_update_tests(BaseTestCase):
test_params = { test_params = {
@@ -350,6 +329,7 @@ class automation_update_tests(BaseTestCase):
class automation_update_split_config_tests(automation_update_tests): class automation_update_split_config_tests(automation_update_tests):
source_config_path = HA_CONFIG6_EXAMPLE
test_params = { test_params = {
"total": 12, "total": 12,
"modify_item": 3, "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): class automation_update_split_config_and_inline_config_tests(automation_update_tests):
source_config_path = HA_CONFIG10_EXAMPLE
test_params = { test_params = {
"total": 4, "total": 4,
"modify_item": 0, "modify_item": 0,
"consitency_tests": {}, "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): class automation_delete_tests(BaseTestCase):
def test_delete_some(self): 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 pathlib import Path
from src.automations.errors import DBDataError from src.automations.errors import DBDataError, RepeatedAutomationId
from src.automations.types import ExtenededAutomation from src.automations.types import ExtenededAutomation
from .utils import TestWithDB from .utils import TestWithDB
class db_tests(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): def test_insert_automations(self):
originals = [ originals = [
ExtenededAutomation( ExtenededAutomation(
@@ -61,7 +50,7 @@ class db_tests(TestWithDB):
configuration_key=["automation"], configuration_key=["automation"],
), ),
] ]
with self.assertRaises(DBDataError) as err: with self.assertRaises(RepeatedAutomationId):
self.db.insert_automations(originals) self.db.insert_automations(originals)
autos = list(self.db.list_automations(0, 10)) autos = list(self.db.list_automations(0, 10))
self.assertEqual(len(autos), 0) self.assertEqual(len(autos), 1)
@@ -21,6 +21,7 @@ from tests.utils import (
HA_CONFIG10_EXAMPLE, HA_CONFIG10_EXAMPLE,
HA_CONFIG11_EXAMPLE, HA_CONFIG11_EXAMPLE,
HA_CONFIG12_EXAMPLE, HA_CONFIG12_EXAMPLE,
HA_CONFIG13_EXAMPLE,
HA_CONFIG_EXAMPLE, HA_CONFIG_EXAMPLE,
) )
@@ -160,6 +161,7 @@ class loader_tests(TestCase):
(HA_CONFIG10_EXAMPLE, 3), (HA_CONFIG10_EXAMPLE, 3),
(HA_CONFIG11_EXAMPLE, 3), (HA_CONFIG11_EXAMPLE, 3),
(HA_CONFIG12_EXAMPLE, 4), (HA_CONFIG12_EXAMPLE, 4),
(HA_CONFIG13_EXAMPLE, 4),
]: ]:
with self.subTest(config_name=ha_path.name, expected=expected): with self.subTest(config_name=ha_path.name, expected=expected):
hass_config = HassConfig(ha_path) 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.config_path = create_copy_of_example_config(ha_config_example)
self.automation_manager = AutomationManager( self.automation_manager = AutomationManager(
HassConfig(self.config_path), HassConfig(self.config_path),
self.db_file,
) )
return self.config_path, self.automation_manager return self.config_path, self.automation_manager
@@ -54,10 +53,6 @@ class manager_tests(TestWithDB):
{"platform": "zone", "entity_id": "person.thor", "zone": "zone.azguard"} {"platform": "zone", "entity_id": "person.thor", "zone": "zone.azguard"}
) )
automation_manager.update(automation) automation_manager.update(automation)
self.assertEqual(
automation_manager.get("sublist3-mlist2").trigger,
[],
)
automation_manager.reload() automation_manager.reload()
self.assertEqual( self.assertEqual(
automation_manager.get("sublist3-mlist2").trigger, 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 unittest import TestCase
from src.automations.db import AutomationDBConnection from src.automations.db import AutomationDBConnection
def make_temp_db():
return AutomationDBConnection(Path(mktemp() + ".db"))
class TestWithDB(TestCase): class TestWithDB(TestCase):
def setUp(self) -> None: def setUp(self) -> None:
self.db = make_temp_db() self.db = AutomationDBConnection()
self.db.create_db()
self.db_file = self.db.db_file
def tearDown(self) -> None:
self.db_file.unlink()
@@ -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): def test_load_stub(self):
yaml_obj = load_yaml( yaml_obj = load_yaml(
io.StringIO( io.StringIO(
+1
View File
@@ -22,6 +22,7 @@ HA_CONFIG9_EXAMPLE = SAMPLES_FOLDER / "config-9"
HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10" HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10"
HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11" HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11"
HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12" HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12"
HA_CONFIG13_EXAMPLE = SAMPLES_FOLDER / "config-13"
def get_example_automation_loader( def get_example_automation_loader(
+2 -2
View File
@@ -1,7 +1,7 @@
name: Shortumation name: Shortumation
version: v0.6.2 version: v0.7.1
slug: shortumation slug: shortumation
image: asosnovsky/shortumation-{arch} image: "asosnovsky/shortumation-{arch}"
url: "https://github.com/asosnovsky/Shortumation" url: "https://github.com/asosnovsky/Shortumation"
description: "A homeassitant addon which provides better UI for automations & scripts." description: "A homeassitant addon which provides better UI for automations & scripts."
arch: arch:
+2
View File
@@ -8,8 +8,10 @@ host_port="$host:$port"
pushd $api_location pushd $api_location
echo "--------------------" echo "--------------------"
echo "BUILD_VERSION = "$BUILD_VERSION echo "BUILD_VERSION = "$BUILD_VERSION
echo "ARCH = "$BUILD_ARCH
echo "HOST = $host_port" echo "HOST = $host_port"
echo "HASSIO_WS = $HASSIO_WS" echo "HASSIO_WS = $HASSIO_WS"
echo $(uname -a)
echo $(python --version) echo $(python --version)
echo "--------------------" echo "--------------------"
python -m hypercorn src.app:app -b $host_port --config /app/hypercorn.toml python -m hypercorn src.app:app -b $host_port --config /app/hypercorn.toml
+2 -2
View File
@@ -9,9 +9,9 @@
"@mui/icons-material": "5.8.4", "@mui/icons-material": "5.8.4",
"@mui/material": "5.8.6", "@mui/material": "5.8.6",
"@mui/styles": "5.8.6", "@mui/styles": "5.8.6",
"@types/jest": "28.1.6", "@types/jest": "28.1.8",
"@types/node": "17.0.36", "@types/node": "17.0.36",
"@types/react": "18.0.15", "@types/react": "18.0.18",
"@types/react-dom": "18.0.6", "@types/react-dom": "18.0.6",
"@types/ws": "8.5.3", "@types/ws": "8.5.3",
"@uiw/react-codemirror": "4.10.4", "@uiw/react-codemirror": "4.10.4",
+6 -9
View File
@@ -8,7 +8,11 @@ import { Page } from "components/Page";
const ConnectedAutomationRoute = () => { const ConnectedAutomationRoute = () => {
const api = useConnectedApiService(); const api = useConnectedApiService();
return <AutomationRoute api={api} />; return (
<Page api={api}>
<AutomationRoute api={api} />
</Page>
);
}; };
function App() { function App() {
@@ -18,14 +22,7 @@ function App() {
<CookiesProvider> <CookiesProvider>
<BrowserRouter> <BrowserRouter>
<Routes> <Routes>
<Route <Route path="*" element={<ConnectedAutomationRoute />} />
path="*"
element={
<Page>
<ConnectedAutomationRoute />
</Page>
}
/>
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>
</CookiesProvider> </CookiesProvider>
+1 -7
View File
@@ -34,15 +34,9 @@ export const makeRemoteAPI = (baseURL: string): API => ({
return response; return response;
} catch (err) { } catch (err) {
console.error(err); console.error(err);
let error = String(err);
if (err instanceof Error) {
error += ` ${err.stack}`;
}
return { return {
ok: false, ok: false,
error, error: `Server error: ${method} ${path}`,
}; };
} }
}, },
+39 -12
View File
@@ -1,28 +1,55 @@
import { useEffect } from "react"; import { useEffect } from "react";
import { useDefaultApiState, makeReloadAutomations } from "./util"; import {
useDefaultApiState,
makeReloadAutomations,
makeProfileManager,
} from "./util";
import { AutomationAPI } from "./automations"; import { AutomationAPI } from "./automations";
import { UserProfileAPI } from "./profile";
export type ApiService = ReturnType<typeof useAPIService>; export type ApiService = ReturnType<typeof useAPIService>;
export const useAPIService = (automationAPI: AutomationAPI) => { export const useAPIService = (
automationAPI: AutomationAPI,
userProfileAPI: UserProfileAPI
) => {
// state // state
const [state, setState] = useDefaultApiState(); const [state, setState] = useDefaultApiState();
const { reload, wrapCall } = makeReloadAutomations( const autoManager = makeReloadAutomations(automationAPI, state, setState);
automationAPI, const userProfileManager = makeProfileManager(
userProfileAPI,
state, state,
setState setState
); );
// initial load of autos // initial load of autos
useEffect(() => { useEffect(() => {
reload(); if (state.automations.ready === undefined) {
// eslint-disable-next-line autoManager.reload();
}, []); }
}, [state.automations.ready, autoManager]);
// initial load of profile
useEffect(() => {
if (state.userProfile.ready === undefined) {
userProfileManager.reload();
}
}, [state.userProfile.ready, userProfileManager]);
return { return {
state, state: {
removeAutomation: wrapCall(automationAPI.remove), ...state,
updateAutomation: wrapCall(automationAPI.update), get theme(): "dark" | "light" {
createAutomation: wrapCall(automationAPI.create), if (state.userProfile.ready && state.userProfile.ok) {
updateTags: wrapCall(automationAPI.updateTags), if (["dark", "light"].includes(state.userProfile.data.theme)) {
return state.userProfile.data.theme as any;
}
}
return "dark";
},
},
removeAutomation: autoManager.wrapCall(automationAPI.remove),
updateAutomation: autoManager.wrapCall(automationAPI.update),
createAutomation: autoManager.wrapCall(automationAPI.create),
updateTags: autoManager.wrapCall(automationAPI.updateTags),
setProfile: userProfileManager.update,
}; };
}; };
+15 -4
View File
@@ -2,8 +2,10 @@ import { AutomationData } from "types/automations";
import { makeAutomationAPI } from "./automations"; import { makeAutomationAPI } from "./automations";
import { makeRemoteAPI } from "./base"; import { makeRemoteAPI } from "./base";
import { useAPIService } from "./core"; import { useAPIService } from "./core";
import { useMockAPI } from "./mock"; import { useAutoMockAPI, useProfileMockAPI } from "./mock";
import { useRef } from "react"; import { createContext, useContext, useRef } from "react";
import { makeProfileAPI } from "./profile";
import { ApiState } from "./types";
const locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i); const locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i);
const baseURL = new URL( const baseURL = new URL(
@@ -13,12 +15,21 @@ const baseURL = new URL(
); );
export const wsURL = baseURL + "socket"; export const wsURL = baseURL + "socket";
export const remoteAutoAPI = makeRemoteAPI(baseURL + "automations"); export const remoteAutoAPI = makeRemoteAPI(baseURL + "automations");
export const detailsAPI = makeRemoteAPI(baseURL + "details");
export const useConnectedApiService = () => export const useConnectedApiService = () =>
useAPIService(makeAutomationAPI(remoteAutoAPI)); useAPIService(makeAutomationAPI(remoteAutoAPI), makeProfileAPI(detailsAPI));
export const useMockApiService = ( export const useMockApiService = (
initialAutos: AutomationData[], initialAutos: AutomationData[],
returnErrors: boolean = false returnErrors: boolean = false
) => ) =>
useAPIService( useAPIService(
makeAutomationAPI(useMockAPI(initialAutos, useRef, returnErrors)) makeAutomationAPI(useAutoMockAPI(initialAutos, useRef, returnErrors)),
makeProfileAPI(useProfileMockAPI())
); );
const ApiStateContext = createContext<ApiState>({
automations: { ready: false },
userProfile: { ready: false },
});
export const ApiStateProvider = ApiStateContext.Provider;
export const useApiState = () => useContext(ApiStateContext);
+9 -7
View File
@@ -1,4 +1,4 @@
import { useMockAPI } from "./mock"; import { useAutoMockAPI } from "./mock";
import { makeAutomationAPI } from "./automations"; import { makeAutomationAPI } from "./automations";
import { createMockAuto } from "../utils/mocks"; import { createMockAuto } from "../utils/mocks";
import { AutomationData } from "types/automations"; import { AutomationData } from "types/automations";
@@ -6,7 +6,7 @@ import { AutomationData } from "types/automations";
const fakeUseRef = (a: any) => ({ current: a }); const fakeUseRef = (a: any) => ({ current: a });
test("mock api uses initial autos for initial population -- empty", async () => { test("mock api uses initial autos for initial population -- empty", async () => {
const mockApi = makeAutomationAPI(useMockAPI([], fakeUseRef as any)); const mockApi = makeAutomationAPI(useAutoMockAPI([], fakeUseRef as any));
const data = await mockApi.list({ limit: 10, offset: 0 }); const data = await mockApi.list({ limit: 10, offset: 0 });
expect(data.ok).toBe(true); expect(data.ok).toBe(true);
expect((data as any).data.data).toHaveLength(0); expect((data as any).data.data).toHaveLength(0);
@@ -15,7 +15,9 @@ test("mock api uses initial autos for initial population -- empty", async () =>
test("mock api uses initial autos for initial population -- some data", async () => { test("mock api uses initial autos for initial population -- some data", async () => {
const initials = [createMockAuto(), createMockAuto()]; const initials = [createMockAuto(), createMockAuto()];
const mockApi = makeAutomationAPI(useMockAPI(initials, fakeUseRef as any)); const mockApi = makeAutomationAPI(
useAutoMockAPI(initials, fakeUseRef as any)
);
const data = await mockApi.list({ limit: 10, offset: 0 }); const data = await mockApi.list({ limit: 10, offset: 0 });
expect(data.ok).toBe(true); expect(data.ok).toBe(true);
expect((data as any).data.data).toHaveLength(2); expect((data as any).data.data).toHaveLength(2);
@@ -23,7 +25,7 @@ test("mock api uses initial autos for initial population -- some data", async ()
}); });
test("populate mock api with some data", async () => { test("populate mock api with some data", async () => {
const mockApi = makeAutomationAPI(useMockAPI([], fakeUseRef as any)); const mockApi = makeAutomationAPI(useAutoMockAPI([], fakeUseRef as any));
await mockApi.create(createMockAuto()); await mockApi.create(createMockAuto());
let data = await mockApi.list({ limit: 10, offset: 0 }); let data = await mockApi.list({ limit: 10, offset: 0 });
expect(data.ok).toBe(true); expect(data.ok).toBe(true);
@@ -37,7 +39,7 @@ test("populate mock api with some data", async () => {
test("delete/update data from mock api", async () => { test("delete/update data from mock api", async () => {
const mockApi = makeAutomationAPI( const mockApi = makeAutomationAPI(
useMockAPI( useAutoMockAPI(
[ [
createMockAuto(), createMockAuto(),
createMockAuto(), createMockAuto(),
@@ -61,7 +63,7 @@ test("delete/update data from mock api", async () => {
test("update tags from mock api", async () => { test("update tags from mock api", async () => {
const mockApi = makeAutomationAPI( const mockApi = makeAutomationAPI(
useMockAPI( useAutoMockAPI(
[ [
createMockAuto(), createMockAuto(),
createMockAuto(), createMockAuto(),
@@ -74,7 +76,7 @@ test("update tags from mock api", async () => {
); );
let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data
.data as AutomationData[]; .data as AutomationData[];
const autoId = data[0].id; const autoId = data[0].id as string;
expect(data[0].tags).toStrictEqual({}); expect(data[0].tags).toStrictEqual({});
mockApi.updateTags({ mockApi.updateTags({
automation_id: autoId, automation_id: autoId,
+39 -1
View File
@@ -1,13 +1,15 @@
import { useRef } from "react"; import { useRef } from "react";
import { AutomationData, BareAutomationData } from "types/automations"; import { AutomationData, BareAutomationData } from "types/automations";
import { API } from "./base"; import { API } from "./base";
import { UserProfile } from "./types";
import { import {
AUTOMTAION_LIST, AUTOMTAION_LIST,
AUTOMTAION_ITEM, AUTOMTAION_ITEM,
AUTOMTAION_ITEM_TAGS, AUTOMTAION_ITEM_TAGS,
USER_PROFILE_ROOT,
} from "./paths"; } from "./paths";
export const useMockAPI = ( export const useAutoMockAPI = (
initialAutos: AutomationData[] = [], initialAutos: AutomationData[] = [],
makeRef = useRef, makeRef = useRef,
returnErrors: boolean = false returnErrors: boolean = false
@@ -105,3 +107,39 @@ export const useMockAPI = (
}, },
}; };
}; };
export const useProfileMockAPI = (
initialProfile: UserProfile = {
lang: "eng",
theme: "dark",
},
makeRef = useRef,
returnErrors: boolean = false
): API => {
const profileRef = makeRef(initialProfile);
return {
async makeCall({ path, method = "POST", data = {} }) {
if (returnErrors) {
return {
ok: false,
error: "Test Error",
};
}
if (path === USER_PROFILE_ROOT) {
if (method === "GET") {
return {
ok: true,
data: JSON.parse(JSON.stringify(profileRef.current)),
} as any;
} else if (method === "PUT") {
profileRef.current = data as any;
return { saved: "" };
}
}
return {
ok: false,
error: "PATH NOT FOUND " + method + ": " + path,
};
},
};
};
+2
View File
@@ -2,3 +2,5 @@ export const AUTOMTAION_ROOT = "/" as const;
export const AUTOMTAION_LIST = `${AUTOMTAION_ROOT}list` as const; export const AUTOMTAION_LIST = `${AUTOMTAION_ROOT}list` as const;
export const AUTOMTAION_ITEM = `${AUTOMTAION_ROOT}item` as const; export const AUTOMTAION_ITEM = `${AUTOMTAION_ROOT}item` as const;
export const AUTOMTAION_ITEM_TAGS = `${AUTOMTAION_ITEM}/tags` as const; export const AUTOMTAION_ITEM_TAGS = `${AUTOMTAION_ITEM}/tags` as const;
export const USER_PROFILE_ROOT = "/profile" as const;
+22
View File
@@ -0,0 +1,22 @@
import { API } from "./base";
import { UserProfile } from "./types";
import { USER_PROFILE_ROOT } from "./paths";
export const makeProfileAPI = (api: API) => ({
async get() {
const data = await api.makeCall<UserProfile>({
method: "GET",
path: USER_PROFILE_ROOT,
});
return data;
},
async update(data: UserProfile) {
return await api.makeCall({
method: "PUT",
path: USER_PROFILE_ROOT,
data,
});
},
});
export type UserProfileAPI = ReturnType<typeof makeProfileAPI>;
+9 -2
View File
@@ -19,7 +19,8 @@ export type APIResponse<D> =
ok: false; ok: false;
error: string; error: string;
}; };
export type Errorable<D> = export type Waitable<D> =
| { ready: undefined }
| ({ ready: true } & APIResponse<D>) | ({ ready: true } & APIResponse<D>)
| { | {
ready: false; ready: false;
@@ -31,5 +32,11 @@ export interface ListData<D> {
} }
export interface ApiState { export interface ApiState {
automations: Errorable<ListData<AutomationData>>; automations: Waitable<ListData<AutomationData>>;
userProfile: Waitable<UserProfile>;
} }
export type UserProfile = {
theme: string;
lang: string;
};
+51 -1
View File
@@ -1,10 +1,13 @@
import { useState } from "react"; import { useState } from "react";
import { ApiState } from "./types"; import { ApiState } from "./types";
import { AutomationAPI } from "./automations"; import { AutomationAPI } from "./automations";
import { UserProfileAPI } from "./profile";
import { UserProfile } from "apiService/types";
export const useDefaultApiState = () => export const useDefaultApiState = () =>
useState<ApiState>({ useState<ApiState>({
automations: { ready: false }, automations: { ready: undefined },
userProfile: { ready: undefined },
}); });
export const makeReloadAutomations = ( export const makeReloadAutomations = (
@@ -38,3 +41,50 @@ export const makeReloadAutomations = (
wrapCall, wrapCall,
}; };
}; };
export const makeProfileManager = (
userProfileAPI: UserProfileAPI,
state: ApiState,
setState: (s: ApiState) => void
) => {
const reload = () =>
userProfileAPI
.get()
.then((data) => {
setState({
...state,
userProfile: {
ready: true,
...data,
},
});
})
.catch((error) =>
setState({
...state,
userProfile: {
ready: true,
ok: false,
error: JSON.stringify(error),
},
})
);
return {
reload,
update: (data: UserProfile) =>
userProfileAPI
.update(data)
.then(() => reload())
.catch((err) =>
setState({
...state,
userProfile: {
ok: false,
error: String(err),
ready: true,
},
})
),
};
};
@@ -14,7 +14,7 @@ const { componentMeta, make } = makeStory({
}) => { }) => {
const [[metadata, tags], setState] = useState([args.metadata, args.tags]); const [[metadata, tags], setState] = useState([args.metadata, args.tags]);
const tagDB = useTagDB( 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)]) (_, t) => setState([metadata, Object.entries(t)])
); );
@@ -10,6 +10,7 @@ import { AddIcon, TrashIcon } from "components/Icons";
import InputAutoText from "components/Inputs/InputAutoText"; import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "components/AutomationManager/TagDB"; import { TagDB } from "components/AutomationManager/TagDB";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
export interface AutoInfoBoxProps { export interface AutoInfoBoxProps {
metadata: AutomationMetadata & Partial<AutomationShortumationMetadata>; metadata: AutomationMetadata & Partial<AutomationShortumationMetadata>;
@@ -26,6 +27,7 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
tagDB, tagDB,
}) => { }) => {
// state // state
const langStore = useLang();
const [newTag, setNewTag] = useState<[string, string]>(["", ""]); const [newTag, setNewTag] = useState<[string, string]>(["", ""]);
const [[errorIndex, error], _setError] = useState<[number | "new", string]>([ const [[errorIndex, error], _setError] = useState<[number | "new", string]>([
-1, -1,
@@ -54,12 +56,12 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
); );
const validTagName = (newName: string): string | undefined => { const validTagName = (newName: string): string | undefined => {
if (newName.length <= 0) { if (newName.length <= 0) {
return "Name must be at least 1 character long"; return langStore.get("VALIDATION_AUTOMATION_NAME");
} }
// eslint-disable-next-line // eslint-disable-next-line
for (const [name, _] of tags) { for (const [name, _] of tags) {
if (name.trim() === newName.trim()) { 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">
<div className="automation-editor--info-box-inner"> <div className="automation-editor--info-box-inner">
<InputText <InputText
label="ID" label={langStore.get("ID")}
value={metadata.id} value={metadata.id ?? langStore.get("N/A")}
onChange={onUpdateMetadata("id")} onChange={onUpdateMetadata("id")}
/> />
<InputText <InputText
label="Name" label={langStore.get("NAME")}
value={metadata.alias ?? ""} value={metadata.alias ?? ""}
onChange={onUpdateMetadata("alias")} onChange={onUpdateMetadata("alias")}
/> />
<InputText <InputText
multiline multiline
label="Description" label={langStore.get("DESCRIPTION")}
value={metadata.description ?? ""} value={metadata.description ?? ""}
onChange={onUpdateMetadata("description")} onChange={onUpdateMetadata("description")}
/> />
<InputList <InputList
label="Mode" label={langStore.get("MODE")}
current={metadata.mode} current={metadata.mode}
onChange={onUpdateMetadata("mode")} onChange={onUpdateMetadata("mode")}
options={["parallel", "single", "queued", "restart"]} options={["parallel", "single", "queued", "restart"]}
/> />
<div className="automation-editor--info-box--tags"> <div className="automation-editor--info-box--tags">
<h1>Tags</h1> <h1>{langStore.get("TAGS")}</h1>
<div className="automation-editor--info-box--tag-list"> <div className="automation-editor--info-box--tag-list">
{tags.map(([tagName, tagValue], tagIndex) => ( {tags.map(([tagName, tagValue], tagIndex) => (
<div key={tagIndex} className="automation-editor--info-box--tag"> <div key={tagIndex} className="automation-editor--info-box--tag">
<InputAutoText <InputAutoText
value={tagName} value={tagName}
label="Name" label={langStore.get("NAME")}
onChange={(v) => updateTagName(v, tagIndex)} onChange={(v) => updateTagName(v, tagIndex)}
options={foundNewTagNames} options={foundNewTagNames}
error={errorIndex === tagIndex ? error : undefined} error={errorIndex === tagIndex ? error : undefined}
/> />
<InputAutoText <InputAutoText
value={tagValue} value={tagValue}
label="Tag" label={langStore.get("TAG")}
onChange={(v) => onUpdateTags(v, tagIndex)} onChange={(v) => onUpdateTags(v, tagIndex)}
options={tagDB.getTagValues(tagName)} options={tagDB.getTagValues(tagName)}
error={errorIndex === tagIndex ? error : undefined} error={errorIndex === tagIndex ? error : undefined}
@@ -153,14 +155,14 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div className="automation-editor--info-box--tag"> <div className="automation-editor--info-box--tag">
<InputAutoText <InputAutoText
value={newTag[0]} value={newTag[0]}
label="Name" label={langStore.get("NAME")}
onChange={(v) => setNewTag([v, newTag[1]])} onChange={(v) => setNewTag([v, newTag[1]])}
options={foundNewTagNames} options={foundNewTagNames}
error={errorIndex === "new" ? error : undefined} error={errorIndex === "new" ? error : undefined}
/> />
<InputAutoText <InputAutoText
value={newTag[1]} value={newTag[1]}
label="Tag" label={langStore.get("TAG")}
onChange={(v) => setNewTag([newTag[0], v])} onChange={(v) => setNewTag([newTag[0], v])}
options={tagDB.getTagValues(newTag[0])} options={tagDB.getTagValues(newTag[0])}
error={errorIndex === "new" ? error : undefined} error={errorIndex === "new" ? error : undefined}
@@ -1,27 +1,25 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { AutomationEditor } from "./index"; import { AutomationEditor } from "./index";
import { useState } from "react"; import { useState } from "react";
import { Page } from "components/Page";
import { useTagDB } from "components/AutomationManager/TagDB"; import { useTagDB } from "components/AutomationManager/TagDB";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants"; import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
export default { import { makeStory } from "devUtils";
title: "App/AutomationEditor",
component: AutomationEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
dims: DEFAULT_DIMS,
},
} as ComponentMeta<typeof AutomationEditor>;
const Template: ComponentStory<typeof AutomationEditor> = (args) => { const { make, componentMeta } = makeStory({
const [state, setState] = useState(args.automation); Component: AutomationEditor,
return ( meta: {
<Page> title: "App/AutomationEditor",
args: {
dims: DEFAULT_DIMS,
},
},
BaseTemplate: (args) => {
const [state, setState] = useState(args.automation);
return (
<AutomationEditor <AutomationEditor
{...args} {...args}
tagDB={useTagDB( tagDB={useTagDB(
state ? [{ id: state.id, tags: state.tags }] : [], state && state.id ? [{ id: state.id, tags: state.tags }] : [],
() => {} () => {}
)} )}
automation={state} automation={state}
@@ -29,15 +27,15 @@ const Template: ComponentStory<typeof AutomationEditor> = (args) => {
window.setTimeout(() => setState(s), 3000); window.setTimeout(() => setState(s), 3000);
}} }}
/> />
</Page> );
); },
}; });
export const Loading = Template.bind({}); export default componentMeta;
export const Simple = Template.bind({}); export const Loading = make({});
Simple.args = {
...Simple.args, export const Simple = make({
automation: { automation: {
condition: [], condition: [],
tags: { tags: {
@@ -94,11 +92,9 @@ Simple.args = {
}, },
], ],
}, },
}; });
export const EmptyStart = Template.bind({}); export const EmptyStart = make({
EmptyStart.args = {
...EmptyStart.args,
automation: { automation: {
condition: [], condition: [],
tags: {}, tags: {},
@@ -115,22 +111,18 @@ EmptyStart.args = {
trigger: [], trigger: [],
action: [], action: [],
}, },
}; });
export const BadAutomationInvalidMetadata = Template.bind({}); export const BadAutomationInvalidMetadata = make({
BadAutomationInvalidMetadata.args = {
...BadAutomationInvalidMetadata.args,
automation: { automation: {
condition: [], condition: [],
tags: {}, tags: {},
trigger: [], trigger: [],
action: [], action: [],
} as any, } as any,
}; });
export const BadAutomationInvalidTriggers = Template.bind({}); export const BadAutomationInvalidTriggers = make({
BadAutomationInvalidTriggers.args = {
...BadAutomationInvalidTriggers.args,
automation: { automation: {
condition: [], condition: [],
tags: {}, tags: {},
@@ -147,11 +139,9 @@ BadAutomationInvalidTriggers.args = {
trigger: ["haha I am a string"] as any, trigger: ["haha I am a string"] as any,
action: [], action: [],
}, },
}; });
export const BadAutomationInvalidSequence = Template.bind({}); export const BadAutomationInvalidSequence = make({
BadAutomationInvalidSequence.args = {
...BadAutomationInvalidSequence.args,
automation: { automation: {
condition: [], condition: [],
tags: {}, tags: {},
@@ -165,14 +155,12 @@ BadAutomationInvalidSequence.args = {
action: [ action: [
{ {
choose: {}, choose: {},
}, } as any,
], ],
} as any, } as any,
}; });
export const RepeatExample = Template.bind({}); export const RepeatExample = make({
RepeatExample.args = {
...RepeatExample.args,
automation: { automation: {
id: "1654976151462", id: "1654976151462",
alias: "Get out of baby room", alias: "Get out of baby room",
@@ -243,4 +231,4 @@ RepeatExample.args = {
], ],
tags: {}, tags: {},
}, },
}; });
@@ -31,6 +31,9 @@ import { MiniFailure } from "types/validators/helper";
import { AutoInfoBox } from "./AutoInfoBox"; import { AutoInfoBox } from "./AutoInfoBox";
import { useAutomatioEditorState, EditorData } from "./state"; import { useAutomatioEditorState, EditorData } from "./state";
import { useLang } from "lang";
import { useSnackbar } from "notistack";
import { Alert } from "@mui/material";
interface Props { interface Props {
automation?: AutomationData | BareAutomationData; automation?: AutomationData | BareAutomationData;
@@ -40,6 +43,8 @@ interface Props {
onDelete: () => void; onDelete: () => void;
tagDB: TagDB; tagDB: TagDB;
isNew?: boolean; isNew?: boolean;
readonly: boolean;
issue?: string;
} }
export const AutomationEditor: FC<Props> = ({ export const AutomationEditor: FC<Props> = ({
dims, dims,
@@ -48,9 +53,12 @@ export const AutomationEditor: FC<Props> = ({
onDelete, onDelete,
onTrigger, onTrigger,
tagDB, tagDB,
isNew, readonly,
issue,
}) => { }) => {
// state // state
const langStore = useLang();
const snackbr = useSnackbar();
const { const {
state, state,
updateSequence, updateSequence,
@@ -61,7 +69,15 @@ export const AutomationEditor: FC<Props> = ({
save, save,
saveAndUpdate, saveAndUpdate,
undo, 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 [infoBoxOpen, setInfoBox] = useState(false);
const [ const [
{ ckFlipped }, { ckFlipped },
@@ -93,7 +109,13 @@ export const AutomationEditor: FC<Props> = ({
); );
} }
return ( return (
<div className={["automation-editor", state.status].join(" ")}> <div
className={[
"automation-editor",
state.status,
readonly ? "readonly" : "",
].join(" ")}
>
{state.status === "saving" && ( {state.status === "saving" && (
<LinearProgress className="linear-loader" /> <LinearProgress className="linear-loader" />
)} )}
@@ -110,13 +132,15 @@ export const AutomationEditor: FC<Props> = ({
state.status, state.status,
].join(" ")} ].join(" ")}
> >
<Button onClick={() => setInfoBox(false)}>Close</Button> <Button onClick={() => setInfoBox(false)}>
{langStore.get("CLOSE")}
</Button>
<Button <Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"} className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save} onClick={save}
disabled={state.status !== "changed"} disabled={state.status !== "changed" || readonly}
> >
Save <CheckMarkIcon color="#bf4" /> {langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button> </Button>
</div> </div>
</AutoInfoBox> </AutoInfoBox>
@@ -131,7 +155,7 @@ export const AutomationEditor: FC<Props> = ({
<div className="id">{state.data.id}</div> <div className="id">{state.data.id}</div>
<InputTextView <InputTextView
value={state.data.alias ?? ""} value={state.data.alias ?? ""}
placeholder="Name" placeholder={langStore.get("NAME")}
onChange={(alias) => onChange={(alias) =>
updateMetadata( updateMetadata(
{ {
@@ -145,7 +169,7 @@ export const AutomationEditor: FC<Props> = ({
</span> </span>
<InputList <InputList
fullWidth={false} fullWidth={false}
label="Mode" label={langStore.get("MODE")}
className="automation-editor--flow-wrapper--toolbar--modes" className="automation-editor--flow-wrapper--toolbar--modes"
current={{ current={{
id: state.data.mode, id: state.data.mode,
@@ -165,28 +189,26 @@ export const AutomationEditor: FC<Props> = ({
options={[ options={[
{ {
id: "single", id: "single",
label: "Do not start a new run. Issue a warning.", label: langStore.get("MODE_SIGNLE_LABEL"),
}, },
{ {
id: "parallel", id: "parallel",
label: label: langStore.get("MODE_SIGNLE_PARALLEL"),
"Start a new, independent run in parallel with previous runs.",
}, },
{ {
id: "queued", id: "queued",
label: label: langStore.get("MODE_SIGNLE_QUEUED"),
"Start a new run after all previous runs complete. Runs are guaranteed to execute in the order they were queued.",
}, },
{ {
id: "restart", id: "restart",
label: "Start a new run after first stopping previous run.", label: langStore.get("MODE_SIGNLE_RESTART"),
}, },
]} ]}
/> />
<InputTextView <InputTextView
className="description" className="description"
value={state.data.description ?? ""} value={state.data.description ?? ""}
placeholder="Description" placeholder={langStore.get("DESCRIPTION")}
onChange={(description) => onChange={(description) =>
updateMetadata( updateMetadata(
{ {
@@ -204,7 +226,7 @@ export const AutomationEditor: FC<Props> = ({
onClick={() => setFlipped(!flipped)} onClick={() => setFlipped(!flipped)}
> >
<Icon>{flipped ? "flip_to_front" : "flip_to_back"}</Icon> <Icon>{flipped ? "flip_to_front" : "flip_to_back"}</Icon>
Flip {langStore.get("FLIPP")}
</Button> </Button>
)} )}
{state.status === "changed" && ( {state.status === "changed" && (
@@ -217,9 +239,14 @@ export const AutomationEditor: FC<Props> = ({
onClick={save} onClick={save}
disabled={state.status !== "changed"} disabled={state.status !== "changed"}
> >
Save <CheckMarkIcon color="#bf4" /> {langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button> </Button>
</div> </div>
{readonly && (
<Alert color="warning">
{langStore.get("READONLY_MODE")} - {issue}
</Alert>
)}
<DAGAutomationGraph <DAGAutomationGraph
action={state.data.action} action={state.data.action}
trigger={state.data.trigger} trigger={state.data.trigger}
@@ -242,26 +269,26 @@ export const AutomationEditor: FC<Props> = ({
// tooltipOpen // tooltipOpen
sx={{ pointerEvents: "auto" }} sx={{ pointerEvents: "auto" }}
icon={<RunIcon />} icon={<RunIcon />}
tooltipTitle={"Trigger"} tooltipTitle={langStore.get("TRIGGER")}
onClick={onTrigger} onClick={onTrigger}
/> />
<SpeedDialAction <SpeedDialAction
// tooltipOpen // tooltipOpen
icon={<DeleteIcon />} icon={<DeleteIcon />}
tooltipTitle={"Delete"} tooltipTitle={langStore.get("DELETE")}
onClick={onDelete} onClick={onDelete}
/> />
<SpeedDialAction <SpeedDialAction
// tooltipOpen // tooltipOpen
icon={<EditIcon />} icon={<EditIcon />}
tooltipTitle={"Metadata"} tooltipTitle={langStore.get("METADATA")}
onClick={() => setInfoBox(!infoBoxOpen)} onClick={() => setInfoBox(!infoBoxOpen)}
/> />
{state.status === "changed" && ( {state.status === "changed" && (
<SpeedDialAction <SpeedDialAction
// tooltipOpen // tooltipOpen
icon={<UndoIcon />} icon={<UndoIcon />}
tooltipTitle={"Undo"} tooltipTitle={langStore.get("UNDO")}
onClick={undo} onClick={undo}
/> />
)} )}
@@ -277,6 +304,7 @@ export const ValidationBox: FC<{
data: EditorData; data: EditorData;
onSave: (d: EditorData) => void; onSave: (d: EditorData) => void;
}> = (props) => { }> = (props) => {
const langStore = useLang();
const [{ failures, data }, setState] = useState({ const [{ failures, data }, setState] = useState({
failures: props.failures, failures: props.failures,
data: props.data, data: props.data,
@@ -305,24 +333,20 @@ export const ValidationBox: FC<{
<div className="automation-editor-failures"> <div className="automation-editor-failures">
<ul> <ul>
{failures.map((f, i) => ( {failures.map((f, i) => (
<> <li key={i}>
<li key={i}> <b>{f.path}</b>:
<b>{f.path}</b>: <ul>
<ul> {f.message.map((m, j) => (
{f.message.map((m, j) => ( <li key={j}>{m}</li>
<li key={j}>{m}</li> ))}
))} </ul>
</ul> </li>
</li>
</>
))} ))}
</ul> </ul>
<span> <span>{langStore.get("VALIDATION_PLEASE_CORRECT_FILE")}</span>
Please correct the automation file manually and then continue! <InputYaml label={langStore.get("RAW")} value={data} onChange={onSave} />
</span>
<InputYaml label="Raw" value={data} onChange={onSave} />
<Button disabled={failures.length > 0} onClick={() => props.onSave(data)}> <Button disabled={failures.length > 0} onClick={() => props.onSave(data)}>
Save {langStore.get("SAVE")}
</Button> </Button>
</div> </div>
); );
@@ -23,6 +23,7 @@ const { make, componentMeta } = makeStory({
id: "1", id: "1",
title: "Example", title: "Example",
entityId: "automation.1", entityId: "automation.1",
readonly: false,
description: "Amazing automation!", description: "Amazing automation!",
tags: {}, tags: {},
state: "on", state: "on",
@@ -38,6 +39,7 @@ const { make, componentMeta } = makeStory({
id: "2", id: "2",
title: "Example 2", title: "Example 2",
entityId: "automation.2", entityId: "automation.2",
readonly: false,
description: "Cool!", description: "Cool!",
state: "on", state: "on",
source_file: "automation.yaml", source_file: "automation.yaml",
@@ -89,6 +91,7 @@ export const Nested = make({
entityId: "automation.1", entityId: "automation.1",
description: "", description: "",
title: "Automation #1", title: "Automation #1",
readonly: false,
state: "on", state: "on",
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
@@ -102,6 +105,7 @@ export const Nested = make({
{ {
id: "2", id: "2",
entityId: "automation.2", entityId: "automation.2",
readonly: false,
description: "another one", description: "another one",
title: "Automation #2", title: "Automation #2",
state: "off", state: "off",
@@ -117,6 +121,7 @@ export const Nested = make({
{ {
id: "3", id: "3",
entityId: "automation.3", entityId: "automation.3",
readonly: false,
description: "bad one", description: "bad one",
title: "Automation #3", title: "Automation #3",
state: "offing", state: "offing",
@@ -153,6 +158,7 @@ export const Nested = make({
}, },
data: [ data: [
{ {
readonly: false,
id: "4", id: "4",
entityId: "automation.4", entityId: "automation.4",
description: "Cool thing", description: "Cool thing",
@@ -1,4 +1,5 @@
import { HassEntities } from "home-assistant-js-websocket"; import { HassEntities } from "home-assistant-js-websocket";
import { LangStore, useLang } from "lang";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { AutomationData, BareAutomationData } from "types/automations"; import { AutomationData, BareAutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults"; import { defaultAutomation } from "utils/defaults";
@@ -10,7 +11,8 @@ export const useAutomationDB = (
configAutomations: AutomationData[], configAutomations: AutomationData[],
tagsDB: TagDB tagsDB: TagDB
) => { ) => {
const autoMap = genMapping(haEntities, configAutomations, tagsDB); const langStore = useLang();
const autoMap = genMapping(haEntities, configAutomations, tagsDB, langStore);
const [newAuto, setNewAuto] = const [newAuto, setNewAuto] =
useState< useState<
null | [AutomationManagerAuto, AutomationData | BareAutomationData] null | [AutomationManagerAuto, AutomationData | BareAutomationData]
@@ -50,17 +52,18 @@ export const useAutomationDB = (
const auto = defaultAutomation(String(Date.now())); const auto = defaultAutomation(String(Date.now()));
setNewAuto([ setNewAuto([
{ {
readonly: false,
id: auto.id, id: auto.id,
entityId: "", entityId: "",
title: auto.alias ?? "", title: auto.alias ?? "",
description: auto.description ?? "", description: auto.description ?? "",
state: "unregistered", state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: {}, tags: {},
issue: "New Automation", issue: langStore.get("NEW_AUTOMATION"),
isNew: true, isNew: true,
source_file: "n/a", source_file: langStore.get("N/A"),
source_file_type: "n/a", source_file_type: langStore.get("N/A"),
configuration_key: ["n/a"], configuration_key: [],
}, },
auto, auto,
]); ]);
@@ -72,15 +75,21 @@ export const useAutomationDB = (
const genMapping = ( const genMapping = (
haEntities: HassEntities, haEntities: HassEntities,
configAutomations: AutomationData[], configAutomations: AutomationData[],
tagsDB: TagDB tagsDB: TagDB,
langStore: LangStore
) => { ) => {
const configData: Record<string, AutomationData> = configAutomations.reduce( const configDataNoId: AutomationData[] = [];
(all, n) => ({ const configData: Record<string, AutomationData & { id: string }> =
...all, configAutomations.reduce((all, n) => {
[n.id]: n, if (n.id) {
}), return {
{} ...all,
); [n.id]: n,
};
}
configDataNoId.push(n);
return all;
}, {});
const automatioinMap: Record< const automatioinMap: Record<
string, string,
[AutomationManagerAuto, AutomationData | null] [AutomationManagerAuto, AutomationData | null]
@@ -88,12 +97,14 @@ const genMapping = (
Object.entries(haEntities) Object.entries(haEntities)
.filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation.")) .filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation."))
.forEach(([entityId, entityData], i) => { .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 title = entityData.attributes.friendly_name ?? "";
let description = ""; let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state) let issue: string | undefined = ["on", "off"].includes(entityData.state)
? undefined ? 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 found: AutomationData | null = null;
let source_file = "n/a"; let source_file = "n/a";
let source_file_type = "n/a"; let source_file_type = "n/a";
@@ -107,7 +118,7 @@ const genMapping = (
configuration_key = found.configuration_key ?? configuration_key; configuration_key = found.configuration_key ?? configuration_key;
delete configData[autoId]; delete configData[autoId];
} else { } else {
issue = "failed to find this automation in '/config' folder"; issue = langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG");
} }
automatioinMap[autoId] = [ automatioinMap[autoId] = [
@@ -122,29 +133,74 @@ const genMapping = (
source_file_type, source_file_type,
configuration_key, configuration_key,
issue, issue,
readonly: found == null,
}, },
found, found,
]; ];
}); });
Object.values(configData).forEach((auto) => { Object.values(configData).forEach((auto, i) => {
automatioinMap[auto.id] = [ automatioinMap[auto.id] = [
{ {
id: auto.id, id: auto.id,
entityId: "", entityId: "",
title: auto.alias ?? "", title: auto.alias ?? "",
description: auto.description ?? "", description: auto.description ?? "",
state: "unregistered", state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: tagsDB.getTags(auto.id), tags: tagsDB.getTags(auto.id),
source_file: auto.source_file, source_file: auto.source_file,
source_file_type: auto.source_file_type, source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key, configuration_key: auto.configuration_key,
issue: issue: langStore.get("ISSUES_NO_LOAD_AUTOMATION"),
"homeassistant did not load this automation, try to manually reload automations or restart homeassistant.", readonly: false,
}, },
auto, 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; return automatioinMap;
}; };
@@ -10,6 +10,7 @@ import {
} from "./state"; } from "./state";
import Alert from "@mui/material/Alert"; import Alert from "@mui/material/Alert";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { useLang } from "lang";
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & { export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
onAutomationDelete: (aid: string, eid: string) => void; onAutomationDelete: (aid: string, eid: string) => void;
@@ -17,13 +18,14 @@ export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
export const AutomationManagerLoaded: FC< export const AutomationManagerLoaded: FC<
PropsWithChildren<AutomationManagerLoadedProps> PropsWithChildren<AutomationManagerLoadedProps>
> = ({ children, ...args }) => { > = ({ children, ...args }) => {
const langStore = useLang();
const state = useAutomationManagerState(args); const state = useAutomationManagerState(args);
const confirm = useConfirm(); const confirm = useConfirm();
const onAutomationDelete = async (aid: string, eid: string) => const onAutomationDelete = async (aid: string, eid: string) =>
confirm({ confirm({
title: "Are you sure you want to delete this automation?", title: langStore.get("CONFIRMATION_DELETE_THIS_AUTOMATION"),
confirmationText: "Delete", confirmationText: langStore.get("DELETE"),
}) })
.then(() => { .then(() => {
args.onAutomationDelete(aid, eid); args.onAutomationDelete(aid, eid);
@@ -48,6 +50,8 @@ export const AutomationManagerLoaded: FC<
{state.currentAutomationId !== null ? ( {state.currentAutomationId !== null ? (
state.currentAutomation ? ( state.currentAutomation ? (
<AutomationEditor <AutomationEditor
readonly={state.currentAutomationIsReadOnly}
issue={state.currentAutomationIssue}
dims={{ dims={{
...DEFAULT_DIMS, ...DEFAULT_DIMS,
flipped: true, flipped: true,
@@ -76,8 +80,9 @@ export const AutomationManagerLoaded: FC<
) : ( ) : (
<div> <div>
<Alert color="warning"> <Alert color="warning">
Failed to find an automation on disk with id{" "} {langStore.get("ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK", {
{state.currentAutomationId}. id: state.currentAutomationId,
})}
</Alert> </Alert>
</div> </div>
) )
@@ -7,6 +7,7 @@ import { useAutomationDB } from "./automationDB";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { AutomationManagerAutoUpdatable } from "../types"; import { AutomationManagerAutoUpdatable } from "../types";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { useLang } from "lang";
export type UseAutomationManagerStateArgs = { export type UseAutomationManagerStateArgs = {
configAutomations: AutomationData[]; configAutomations: AutomationData[];
@@ -26,6 +27,7 @@ export const useAutomationManagerState = ({
onAutomationStateChange, onAutomationStateChange,
}: UseAutomationManagerStateArgs) => { }: UseAutomationManagerStateArgs) => {
// state // state
const langStore = useLang();
const confirm = useConfirm(); const confirm = useConfirm();
const snackbr = useSnackbar(); const snackbr = useSnackbar();
const cookies = useAMSCookies(); const cookies = useAMSCookies();
@@ -35,7 +37,11 @@ export const useAutomationManagerState = ({
.map(({ id, tags = {} }) => ({ .map(({ id, tags = {} }) => ({
id, id,
tags, tags,
})), }))
.filter(({ id }) => typeof id === "string") as Array<{
id: string;
tags: Record<string, string>;
}>,
onUpdateTags onUpdateTags
); );
const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB); const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB);
@@ -44,10 +50,9 @@ export const useAutomationManagerState = ({
const stillHaveNewAreYouSure = async () => { const stillHaveNewAreYouSure = async () => {
try { try {
await confirm({ await confirm({
content: content: langStore.get("WARNING_SWITCHING_FROM_NONE_SAVE"),
"Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.", confirmationText: langStore.get("SWITCH_AUTOMATION"),
confirmationText: "Switch Automation", cancellationText: langStore.get("CANCEL"),
cancellationText: "Cancel",
}); });
return true; return true;
} catch (_) { } catch (_) {
@@ -77,6 +82,14 @@ export const useAutomationManagerState = ({
get currentAutomationEntityId(): string | null { get currentAutomationEntityId(): string | null {
return currentAutomation === null ? null : currentAutomation[0].entityId; 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) { async setSelectedAutomationId(i: string | null, force: boolean = false) {
if (methods.currentAutomationIsNew && !force) { if (methods.currentAutomationIsNew && !force) {
if (!(await stillHaveNewAreYouSure())) { if (!(await stillHaveNewAreYouSure())) {
@@ -93,7 +106,9 @@ export const useAutomationManagerState = ({
} }
} }
const auto = automationDB.addNew(); const auto = automationDB.addNew();
methods.setSelectedAutomationId(auto.id, true); if (auto.id) {
methods.setSelectedAutomationId(auto.id, true);
}
}, },
editorUpdateAutomation(auto: AutomationData | BareAutomationData) { editorUpdateAutomation(auto: AutomationData | BareAutomationData) {
if (methods.currentAutomationIsNew) { if (methods.currentAutomationIsNew) {
@@ -128,9 +143,10 @@ export const useAutomationManagerState = ({
} }
} else { } else {
snackbr.enqueueSnackbar( snackbr.enqueueSnackbar(
`Failed to save automation "${aid}" contents - ${JSON.stringify( langStore.get("ERROR_FAILED_TO_SAVE", {
a aid,
)} -- not found in /config`, contents: JSON.stringify(a),
}),
{ variant: "error" } { variant: "error" }
); );
} }
@@ -12,6 +12,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import InputAutoText from "components/Inputs/InputAutoText"; import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "../TagDB"; import { TagDB } from "../TagDB";
import { useLang } from "lang";
export type TagsProps = { export type TagsProps = {
automationId: string; automationId: string;
@@ -29,6 +30,7 @@ export type TagModalState =
}; };
export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => { export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
const langStore = useLang();
const [modalState, setModal] = useState<TagModalState>({ open: false }); const [modalState, setModal] = useState<TagModalState>({ open: false });
const tags = tagsDB.getTags(automationId, true); const tags = tagsDB.getTags(automationId, true);
const onUpdate = (t: Record<string, string>) => const onUpdate = (t: Record<string, string>) =>
@@ -44,7 +46,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText <InputAutoText
className="name" className="name"
options={tagsDB.getTagNames(Object.keys(tags))} options={tagsDB.getTagNames(Object.keys(tags))}
label="Tag Name" label={langStore.get("TAG_NAME")}
value={modalState.tag[0]} value={modalState.tag[0]}
onChange={(v) => onChange={(v) =>
setModal({ setModal({
@@ -56,7 +58,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText <InputAutoText
className="value" className="value"
options={tagsDB.getTagValues(modalState.tag[0])} options={tagsDB.getTagValues(modalState.tag[0])}
label="Tag Value" label={langStore.get("TAG_VALUE")}
value={modalState.tag[1]} value={modalState.tag[1]}
onChange={(v) => onChange={(v) =>
setModal({ setModal({
@@ -67,7 +69,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
/> />
<div className="buttons"> <div className="buttons">
<Button onClick={() => setModal({ open: false })} color="info"> <Button onClick={() => setModal({ open: false })} color="info">
Close {langStore.get("CLOSE")}
</Button> </Button>
<Button <Button
disabled={!validTag} disabled={!validTag}
@@ -80,7 +82,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
}} }}
color="success" color="success"
> >
{modalState.isNew ? "Create" : "Save"} {modalState.isNew ? langStore.get("CREATE") : langStore.get("SAVE")}
</Button> </Button>
</div> </div>
</div> </div>
@@ -9,12 +9,16 @@ import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import SelectIcon from "@mui/icons-material/HighlightAltSharp"; import SelectIcon from "@mui/icons-material/HighlightAltSharp";
import RunIcon from "@mui/icons-material/RunCircleOutlined"; 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 { InputTextView } from "components/Inputs/InputTextView";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { AutomationManagerAuto } from "../types"; import { AutomationManagerAuto } from "../types";
import { Tags } from "./Tags"; import { Tags } from "./Tags";
import { TagDB } from "../TagDB"; import { TagDB } from "../TagDB";
import { Chip, Tooltip } from "@mui/material"; import { useLang } from "lang";
export type MetadataBoxProps = AutomationManagerAuto & { export type MetadataBoxProps = AutomationManagerAuto & {
onDelete: () => void; onDelete: () => void;
@@ -28,8 +32,12 @@ export type MetadataBoxProps = AutomationManagerAuto & {
}; };
export const MetadataBox: FC<MetadataBoxProps> = (props) => { export const MetadataBox: FC<MetadataBoxProps> = (props) => {
const isValidState = ["on", "off"].includes(props.state); 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 ( return (
<div <Box
className={[ className={[
"automation-manager--metadatabox", "automation-manager--metadatabox",
props.isSelected ? "selected" : "", props.isSelected ? "selected" : "",
@@ -38,7 +46,13 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
> >
<div <div
className="metadatabox--switch" 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 <Switch
checked={props.state !== "off"} checked={props.state !== "off"}
@@ -53,28 +67,36 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
<div className="metadatabox--title"> <div className="metadatabox--title">
<span className="metadatabox--title--source"> <span className="metadatabox--title--source">
<Tooltip <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 <Chip
label={`@${props.source_file} (${props.source_file_type}) - ${ label={`@${props.source_file} (${props.source_file_type}) - ${
props.entityId ?? "n/a" props.entityId ?? langStore.get("N/A")
}`} }`}
className="text-ellipsis" className="text-ellipsis"
/> />
</Tooltip> </Tooltip>
</span> </span>
<Tooltip title={`ID=${props.id}, EntityID=${props.entityId}`}> <InputTextView
<InputTextView titleSlug="AUTOMATION_METADATA_TOOLTIP_SIMPLE"
className="title" titleParams={{
placeholder="Title" id: props.id,
value={props.title} entityId: props.entityId,
onChange={props.onTitleUpdate} }}
disabled={props.isNew} className="title"
/> placeholder={langStore.get("TITLE")}
</Tooltip> value={props.title}
onChange={props.onTitleUpdate}
disabled={props.isNew}
/>
<InputTextView <InputTextView
className="description" className="description"
placeholder="Description" placeholder={langStore.get("DESCRIPTION")}
value={props.description} value={props.description}
onChange={props.onDescriptionUpdate} onChange={props.onDescriptionUpdate}
disabled={props.isNew} disabled={props.isNew}
@@ -90,24 +112,24 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
</div> </div>
<div className="buttons"> <div className="buttons">
<ButtonIcon <ButtonIcon
titleSlug="SELECT_AUTOMATION"
className="select" className="select"
icon={<SelectIcon />} icon={<SelectIcon />}
onClick={props.onSelect} onClick={props.onSelect}
title="Select automation"
/> />
<ButtonIcon <ButtonIcon
titleSlug="TRIGGER_AUTOMATION"
className="run" className="run"
icon={<RunIcon />} icon={<RunIcon />}
onClick={props.onRun} onClick={props.onRun}
title="Trigger automation"
/> />
<ButtonIcon <ButtonIcon
titleSlug="DELETE_AUTOMATION"
className="delete" className="delete"
icon={<DeleteForeverIcon />} icon={<DeleteForeverIcon />}
onClick={props.onDelete} onClick={props.onDelete}
title="Delete automation"
/> />
</div> </div>
</div> </Box>
); );
}; };
@@ -71,6 +71,7 @@ const story = makeStory({
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
configuration_key: ["automation"], configuration_key: ["automation"],
readonly: false,
}, },
]); ]);
setSelAutoId(id); setSelAutoId(id);
@@ -100,6 +101,7 @@ const makeAuto = (
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
configuration_key: ["automation"], configuration_key: ["automation"],
readonly: false,
...data, ...data,
}; };
}; };
@@ -18,6 +18,7 @@ import {
} from "../types"; } from "../types";
import { Button } from "components/Inputs/Buttons/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
export type AutomationManagerSidebarProps = { export type AutomationManagerSidebarProps = {
tagsDB: TagDB; tagsDB: TagDB;
@@ -41,6 +42,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
onSelectedAutomationId, onSelectedAutomationId,
...events ...events
}) => { }) => {
const langStore = useLang();
const [searchText, setSearchText] = useState(""); const [searchText, setSearchText] = useState("");
const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>([]); const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>([]);
const [isHidden, setHidden] = useState(false); const [isHidden, setHidden] = useState(false);
@@ -76,9 +78,13 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
].join(" ")} ].join(" ")}
> >
<div className="automation-manager--sidebar-box--nav"> <div className="automation-manager--sidebar-box--nav">
<InputText label="Search" value={searchText} onChange={setSearchText} /> <InputText
label={langStore.get("SEARCH")}
value={searchText}
onChange={setSearchText}
/>
<InputMultiSelect <InputMultiSelect
label="Tags" label={langStore.get("TAGS")}
selected={selectedTagIdx} selected={selectedTagIdx}
onChange={setSelectedTagIdx} onChange={setSelectedTagIdx}
options={tags} options={tags}
@@ -109,7 +115,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
color="primary" color="primary"
className="add-btn" className="add-btn"
> >
Add {langStore.get("ADD")}
</Button> </Button>
<ButtonIcon <ButtonIcon
className="hide-btn" className="hide-btn"
@@ -38,10 +38,11 @@ const automations: AutomationManagerAuto[] = [
description: a.description ?? "", description: a.description ?? "",
state: "on", state: "on",
tags: a.tags, tags: a.tags,
id: a.id, id: a.id as string,
isSelected: false, isSelected: false,
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
readonly: false,
configuration_key: ["automation"], configuration_key: ["automation"],
})); }));
@@ -51,7 +52,8 @@ const bigList = bigMockAutoList.map<AutomationManagerAuto>((a) => ({
description: a.description ?? "", description: a.description ?? "",
state: "on", state: "on",
tags: a.tags, tags: a.tags,
id: a.id, id: a.id as string,
readonly: false,
isSelected: false, isSelected: false,
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
@@ -109,7 +109,7 @@ export const MissingAutoInConfig = make({
entity_id: `automation.${auto1.id}`, entity_id: `automation.${auto1.id}`,
attributes: { attributes: {
id: auto1.id, id: auto1.id,
friendly_name: auto1.alias, friendly_name: auto1.alias ?? auto1.id ?? "",
}, },
context: { id: "", parent_id: null, user_id: null }, context: { id: "", parent_id: null, user_id: null },
last_changed: "", last_changed: "",
@@ -15,6 +15,7 @@ import * as av from "types/validators/autmation";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { APIResponse } from "apiService/types"; import { APIResponse } from "apiService/types";
import { useLang } from "lang";
export type AutomationManagerProps = { export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => Promise<any>; onAutomationStateChange: (eid: string, on: boolean) => Promise<any>;
@@ -33,6 +34,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
forceDeleteAutomation: _forceDeleteAutomation, forceDeleteAutomation: _forceDeleteAutomation,
triggerAutomation: _triggerAutomation, triggerAutomation: _triggerAutomation,
}) => { }) => {
const langStore = useLang();
const snackbr = useSnackbar(); const snackbr = useSnackbar();
const confirm = useConfirm(); const confirm = useConfirm();
const validationsShown = useRef(false); const validationsShown = useRef(false);
@@ -52,9 +54,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}) })
.catch((err) => { .catch((err) => {
console.error(err); console.error(err);
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", String(err)), { snackbr.enqueueSnackbar(
variant: "error", langStore.get(errorMessage, {
}); err: String(err),
}),
{
variant: "error",
}
);
setIsSaving(isSaving.filter((k) => k !== name)); setIsSaving(isSaving.filter((k) => k !== name));
}); });
} }
@@ -68,9 +75,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
if (resp.ok) { if (resp.ok) {
refreshAutomations(); refreshAutomations();
} else { } else {
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", resp.error), { snackbr.enqueueSnackbar(
variant: "error", langStore.get(errorMessage, {
}); err: resp.error,
}),
{
variant: "error",
}
);
} }
} }
}); });
@@ -78,24 +90,26 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
const onAutomationStateChange = (eid: string, on: boolean) => const onAutomationStateChange = (eid: string, on: boolean) =>
wrapPromise( wrapPromise(
"changing automation state", langStore.get("AUTOMATION_MANAGER_STATE_CHANGE"),
'failed to toggle autonation due to "{{err}}"', "AUTOMATION_MANAGER_STATE_CHANGE_FAIL",
() => _onAutomationStateChange(eid, on) () => _onAutomationStateChange(eid, on)
); );
const refreshAutomations = () => const refreshAutomations = () =>
wrapPromise( wrapPromise(
"refreshing automations", langStore.get("AUTOMATION_MANAGER_REFRESH"),
'failed refreshing automations due to "{{err}}"', "AUTOMATION_MANAGER_REFRESH_FAIL",
() => _refreshAutomations() () => _refreshAutomations()
); );
const forceDeleteAutomation = (eid: string) => const forceDeleteAutomation = (eid: string) =>
wrapPromise("deleting automations", 'failed delete due to "{{err}}"', () => wrapPromise(
_forceDeleteAutomation(eid) langStore.get("AUTOMATION_MANAGER_DELETE"),
"AUTOMATION_MANAGER_DELETE_FAIL",
() => _forceDeleteAutomation(eid)
); );
const triggerAutomation = (eid: string) => const triggerAutomation = (eid: string) =>
wrapPromise( wrapPromise(
"triggering automations", langStore.get("AUTOMATION_MANAGER_TRIGGER"),
'failed trigger due to "{{err}}"', "AUTOMATION_MANAGER_TRIGGER_FAIL",
() => _triggerAutomation(eid) () => _triggerAutomation(eid)
); );
@@ -129,7 +143,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
cancellationButtonProps: { cancellationButtonProps: {
style: { display: "none" }, style: { display: "none" },
}, },
title: "Invalid Automations detected!", title: langStore.get("ERROR_INVALID_AUTOMATION_DETECTED"),
content: ( content: (
<> <>
<ol className="invalid-automation-modal-list"> <ol className="invalid-automation-modal-list">
@@ -165,6 +179,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
.catch(console.error); .catch(console.error);
} }
} }
// eslint-disable-next-line
}, [api.state.automations, confirm]); }, [api.state.automations, confirm]);
// handle bad states // handle bad states
@@ -172,8 +187,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return ( return (
<div className="automation-manager error"> <div className="automation-manager error">
<Alert color="error"> <Alert color="error">
Failed to connect to websocket, please check that your access token is {langStore.get("ERROR_FAILED_CONNECTION_TO_HA")}
properly setup
</Alert>{" "} </Alert>{" "}
<br /> <br />
<code>{JSON.stringify(haEntities.error)}</code> <code>{JSON.stringify(haEntities.error)}</code>
@@ -205,7 +219,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return ( return (
<div className="automation-manager error"> <div className="automation-manager error">
<Alert color="error"> <Alert color="error">
Failed to load automations from <code>/config</code> {langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG")}
</Alert>{" "} </Alert>{" "}
<br /> <br />
<code>{error}</code> <code>{error}</code>
@@ -237,8 +251,8 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
onAutomationStateChange={onAutomationStateChange} onAutomationStateChange={onAutomationStateChange}
onAutomationAdd={(auto) => onAutomationAdd={(auto) =>
wrapApiPromise( wrapApiPromise(
"adding automation", langStore.get("AUTOMATION_MANAGER_ADD"),
"Failed to create automation, recieved error: {{err}}!", "AUTOMATION_MANAGER_ADD_FAIL",
() => api.createAutomation(auto) as any () => api.createAutomation(auto) as any
) )
} }
@@ -258,7 +272,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
} }
if (!deleteSent) { if (!deleteSent) {
snackbr.enqueueSnackbar( 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", variant: "error",
} }
@@ -268,15 +282,15 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}} }}
onAutomationUpdate={(auto) => onAutomationUpdate={(auto) =>
wrapApiPromise( wrapApiPromise(
"updating automation", langStore.get("AUTOMATION_MANAGER_UPDATE"),
"Failed to update automation, recieved error: {{err}}!", "AUTOMATION_MANAGER_UPDATE_FAIL",
() => api.updateAutomation(auto) as any () => api.updateAutomation(auto) as any
) )
} }
onUpdateTags={async (aid, t) => { onUpdateTags={async (aid, t) => {
wrapApiPromise( wrapApiPromise(
"updating tags", langStore.get("AUTOMATION_MANAGER_UPDATE_TAGS"),
"Failed to update tags, recieved error: {{err}}!", "AUTOMATION_MANAGER_UPDATE_TAGS_FAIL",
() => () =>
api.updateTags({ api.updateTags({
automation_id: aid, automation_id: aid,
@@ -12,6 +12,7 @@ export type AutomationManagerAuto = AutomationManagerAutoUpdatable & {
source_file: string; source_file: string;
source_file_type: string; source_file_type: string;
configuration_key: string[]; configuration_key: string[];
readonly: boolean;
}; };
export type AutomationManagerAutoItem = AutomationManagerAuto & { export type AutomationManagerAutoItem = AutomationManagerAuto & {
flags: AutomationManagerItemFlags; flags: AutomationManagerItemFlags;
@@ -0,0 +1,63 @@
import Alert from "@mui/material/Alert";
import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "apiService/core";
import { UserProfile } from "apiService/types";
import { InputList } from "components/Inputs/InputList";
import { useLang } from "lang";
import { FC, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress";
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);
});
}
};
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")}
/>
{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;
}
+41
View File
@@ -0,0 +1,41 @@
import "./index.css";
import { FC, useState } from "react";
import { useHAConnection } from "haService/connection";
import { Button } from "components/Inputs/Buttons/Button";
import SettingsSuggestOutlinedIcon from "@mui/icons-material/SettingsSuggestOutlined";
import { useLang } from "lang";
import { Modal } from "components/Modal";
import { UserProfileEditor, UserProfileProps } from "./UserProfile";
export type BottomBarProps = UserProfileProps;
export const BottomBar: FC<BottomBarProps> = ({ api }) => {
const lang = useLang();
const ha = useHAConnection();
const version = process.env.REACT_APP_BUILD_VERSION ?? "n/a";
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: {version}</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 { useState } from "react";
import { AutomationCondition } from "types/automations/conditions"; import { AutomationCondition } from "types/automations/conditions";
import { ConditionNodeBase } from "./ConditionNodeBase"; import { ConditionNodeBase } from "./ConditionNodeBase";
export default { import { makeStory } from "devUtils";
title: "ConditionEditor/NodeBase",
component: ConditionNodeBase,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof ConditionNodeBase>;
const Template: ComponentStory<typeof ConditionNodeBase> = ({ const { make, componentMeta } = makeStory({
condition, Component: ConditionNodeBase,
...args meta: {
}) => { title: "ConditionEditor/NodeBase",
const [data, setData] = useState(condition); },
return ( BaseTemplate: ({ condition, ...args }) => {
<Page> const [data, setData] = useState(condition);
return (
<ConditionNodeBase <ConditionNodeBase
{...args} {...args}
condition={data} condition={data}
@@ -24,20 +19,20 @@ const Template: ComponentStory<typeof ConditionNodeBase> = ({
setData(data); setData(data);
}} }}
/> />
</Page> );
); },
}; });
export const TemplateViewer = Template.bind({}); export default componentMeta;
TemplateViewer.args = {
export const TemplateViewer = make({
condition: { condition: {
condition: "template", condition: "template",
value_template: "states('switch.light_kitchen') == 'on'", value_template: "states('switch.light_kitchen') == 'on'",
} as AutomationCondition, } as AutomationCondition,
}; });
export const MultipleThings = Template.bind({}); export const MultipleThings = make({
MultipleThings.args = {
condition: { condition: {
condition: "or", condition: "or",
conditions: [ conditions: [
@@ -62,4 +57,4 @@ MultipleThings.args = {
}, },
], ],
} as AutomationCondition, } as AutomationCondition,
}; });
@@ -12,6 +12,7 @@ import { getViewer } from "./viewRender";
import { getEditor } from "./editorRender"; import { getEditor } from "./editorRender";
import useWindowSize from "utils/useWindowSize"; import useWindowSize from "utils/useWindowSize";
import { ConditionNodeSettings } from "./ConditionNodeSettings"; import { ConditionNodeSettings } from "./ConditionNodeSettings";
import { useLang } from "lang";
export type ConditionNodeBaseProps = { export type ConditionNodeBaseProps = {
condition: AutomationCondition; condition: AutomationCondition;
@@ -24,6 +25,7 @@ export type ConditionNodeBaseViewMode = "edit" | "yaml" | "view";
export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => { export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
// state // state
const ha = useHA(); const ha = useHA();
const langStore = useLang();
const { isMobile } = useWindowSize(); const { isMobile } = useWindowSize();
const [{ isEdited, condition }, setCondition] = useState<{ const [{ isEdited, condition }, setCondition] = useState<{
isEdited: boolean; isEdited: boolean;
@@ -61,6 +63,7 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
onChange={updateCondition} onChange={updateCondition}
ha={ha} ha={ha}
initialViewMode="edit" initialViewMode="edit"
langStore={langStore}
/> />
); );
} }
@@ -101,6 +104,7 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
}, },
} as any) } as any)
} }
prettyOptionLabels={false}
/> />
{isMobile && icons} {isMobile && icons}
</div> </div>
@@ -31,6 +31,7 @@ import { prettyName } from "utils/formatting";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Buttons/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { RemoveCircle } from "@mui/icons-material"; import { RemoveCircle } from "@mui/icons-material";
import { LangStore } from "lang";
interface Editor<C extends AutomationCondition> interface Editor<C extends AutomationCondition>
extends FC<{ extends FC<{
@@ -38,6 +39,7 @@ interface Editor<C extends AutomationCondition>
onChange: (condition: C) => void; onChange: (condition: C) => void;
ha: HAService; ha: HAService;
initialViewMode: ConditionNodeBaseViewMode; initialViewMode: ConditionNodeBaseViewMode;
langStore: LangStore;
}> {} }> {}
export const getEditor = (condition: AutomationCondition): Editor<any> => { export const getEditor = (condition: AutomationCondition): Editor<any> => {
@@ -70,11 +72,12 @@ export const getEditor = (condition: AutomationCondition): Editor<any> => {
export const TemplateEditor: Editor<TemplateCondition> = ({ export const TemplateEditor: Editor<TemplateCondition> = ({
onChange, onChange,
condition, condition,
langStore,
}) => { }) => {
return ( return (
<> <>
<InputYaml <InputYaml
label="Template" label={langStore.get("TEMPLATE")}
value={condition.value_template} value={condition.value_template}
onChange={(value_template) => onChange={(value_template) =>
onChange({ onChange({
@@ -119,6 +122,7 @@ export const DeviceConditionEditor: Editor<DeviceCondition> = ({
export const NumericStateEditor: Editor<NumericCondition> = ({ export const NumericStateEditor: Editor<NumericCondition> = ({
onChange, onChange,
condition, condition,
langStore,
}) => { }) => {
return ( return (
<> <>
@@ -133,7 +137,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
} }
/> />
<InputText <InputText
label="Attribute" label={langStore.get("ATTRIBUTE")}
value={condition.attribute ?? ""} value={condition.attribute ?? ""}
onChange={(attribute) => onChange={(attribute) =>
onChange({ onChange({
@@ -143,7 +147,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
} }
/> />
<InputNumber <InputNumber
label="Above" label={langStore.get("ABOVE")}
value={condition.above ? Number(condition.above) : undefined} value={condition.above ? Number(condition.above) : undefined}
onChange={(above) => onChange={(above) =>
onChange({ onChange({
@@ -153,7 +157,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
} }
/> />
<InputNumber <InputNumber
label="Below" label={langStore.get("BELOW")}
value={condition.below ? Number(condition.below) : undefined} value={condition.below ? Number(condition.below) : undefined}
onChange={(below) => onChange={(below) =>
onChange({ onChange({
@@ -163,7 +167,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
} }
/> />
<InputYaml <InputYaml
label="Template" label={langStore.get("TEMPLATE")}
value={condition.value_template ?? ""} value={condition.value_template ?? ""}
onChange={(value_template) => onChange={(value_template) =>
onChange({ onChange({
@@ -221,6 +225,7 @@ export const StateEditor: Editor<StateCondition> = ({
onChange, onChange,
condition, condition,
ha, ha,
langStore,
}) => { }) => {
const restrictToDomain = const restrictToDomain =
!condition.entity_id || condition.entity_id.length === 0 !condition.entity_id || condition.entity_id.length === 0
@@ -241,7 +246,7 @@ export const StateEditor: Editor<StateCondition> = ({
} }
/> />
<InputAutoComplete <InputAutoComplete
label="Attribute" label={langStore.get("ATTRIBUTE")}
value={condition.attribute ?? ""} value={condition.attribute ?? ""}
options={ha.entities.getAttributes(condition.entity_id)} options={ha.entities.getAttributes(condition.entity_id)}
multiple={false} multiple={false}
@@ -253,11 +258,11 @@ export const StateEditor: Editor<StateCondition> = ({
} }
/> />
<InputText <InputText
label="State" label={langStore.get("STATE")}
value={String(condition.state)} value={String(condition.state)}
placeholder={ha.entities placeholder={ha.entities
.getStates(condition.entity_id, condition.attribute) .getStates(condition.entity_id, condition.attribute)
.join(" or ")} .join(` ${langStore.get("OR").toLowerCase()} `)}
onChange={(state) => onChange={(state) =>
onChange({ onChange({
...condition, ...condition,
@@ -266,7 +271,7 @@ export const StateEditor: Editor<StateCondition> = ({
} }
/> />
<InputTime <InputTime
label="For" label={langStore.get("FOR")}
value={condition.for} value={condition.for}
onChange={(_for) => onChange={(_for) =>
onChange({ onChange({
@@ -280,7 +285,11 @@ export const StateEditor: Editor<StateCondition> = ({
}; };
type TimeEditorShows = "after" | "before" | "weekday"; 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[]>( const [shows, setShows] = useState<TimeEditorShows[]>(
Object.keys(condition).filter((k) => Object.keys(condition).filter((k) =>
["after", "before", "weekday"].includes(k) ["after", "before", "weekday"].includes(k)
@@ -321,19 +330,19 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
<b className="label">{prettyName(show)}</b> <b className="label">{prettyName(show)}</b>
<InputAutoComplete <InputAutoComplete
className="condition-node--time-editor--weekday" className="condition-node--time-editor--weekday"
label="Weekday" label={langStore.get("WEEKDAY")}
value={condition.weekday ?? []} value={condition.weekday ?? []}
multiple={true} multiple={true}
getID={(opt) => opt} getID={(opt) => opt}
getLabel={(opt) => { getLabel={(opt) => {
return { return {
mon: "Monday", mon: langStore.get("DAY_mon"),
tue: "Tuesday", tue: langStore.get("DAY_tue"),
wed: "Wednesday", wed: langStore.get("DAY_wed"),
thu: "Thursday", thu: langStore.get("DAY_thu"),
fri: "Friday", fri: langStore.get("DAY_fri"),
sat: "Saturday", sat: langStore.get("DAY_sat"),
sun: "Sunday", sun: langStore.get("DAY_sun"),
}[opt]; }[opt];
}} }}
onChange={(weekday: any) => onChange={(weekday: any) =>
@@ -362,7 +371,7 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
{shows.length < 3 && ( {shows.length < 3 && (
<InputList <InputList
className="condition-node--time-editor--new" className="condition-node--time-editor--new"
label="Option" label={langStore.get("OPTION")}
options={["after", "before", "weekday"].filter( options={["after", "before", "weekday"].filter(
(k: any) => !shows.includes(k) (k: any) => !shows.includes(k)
)} )}
@@ -378,11 +387,12 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
export const TriggerEditor: Editor<TriggerCondition> = ({ export const TriggerEditor: Editor<TriggerCondition> = ({
onChange, onChange,
condition, condition,
langStore,
}) => { }) => {
return ( return (
<> <>
<InputText <InputText
label="Trigger ID" label={langStore.get("TRIGGER_ID")}
value={condition.id} value={condition.id}
onChange={(id) => onChange={(id) =>
onChange({ 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 ( return (
<> <>
<InputEntity <InputEntity
label="Zone" label={langStore.get("ZONE")}
value={condition.zone ?? []} value={condition.zone ?? []}
multiple multiple
onChange={(zone) => onChange={(zone) =>
@@ -411,7 +425,7 @@ export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => {
restrictToDomain={["zone"]} restrictToDomain={["zone"]}
/> />
<InputEntity <InputEntity
label="Entity with Location" label={langStore.get("ENTITY_WITH_LOCATION")}
value={condition.entity_id} value={condition.entity_id}
multiple multiple
onChange={(entity_id) => onChange={(entity_id) =>
@@ -1,26 +1,22 @@
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { MockPage, Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import { AutomationCondition } from "types/automations/conditions"; import { AutomationCondition } from "types/automations/conditions";
import { ConditionEditor } from "."; import { ConditionEditor } from ".";
import { makeStory } from "devUtils";
export default { const { make, componentMeta } = makeStory({
title: "ConditionEditor", Component: ConditionEditor,
component: ConditionEditor, meta: {
parameters: { actions: { argTypesRegex: "^on.*" } }, title: "ConditionEditor",
args: { args: {
initialViewMode: "edit", initialViewMode: "edit",
},
}, },
} as ComponentMeta<typeof ConditionEditor>; BaseTemplate: ({ condition, ...args }) => {
const [data, setData] = useState(condition);
const Template: ComponentStory<typeof ConditionEditor> = ({ return (
condition,
...args
}) => {
const [data, setData] = useState(condition);
return (
<Page>
<ConditionEditor <ConditionEditor
{...args} {...args}
condition={data} condition={data}
@@ -28,29 +24,28 @@ const Template: ComponentStory<typeof ConditionEditor> = ({
setData(data); setData(data);
}} }}
/> />
</Page> );
); },
}; });
export const TemplateViewer = Template.bind({}); export default componentMeta;
TemplateViewer.args = {
export const TemplateViewer = make({
condition: { condition: {
condition: "template", condition: "template",
value_template: "states('switch.light_kitchen') == 'on'", value_template: "states('switch.light_kitchen') == 'on'",
} as AutomationCondition, } as AutomationCondition,
}; });
export const NumericStateViewer = Template.bind({}); export const NumericStateViewer = make({
NumericStateViewer.args = {
condition: { condition: {
condition: "numeric_state", condition: "numeric_state",
entity_id: "sensor.humidity_kitchen", entity_id: "sensor.humidity_kitchen",
above: "10", above: "10",
} as AutomationCondition, } as AutomationCondition,
}; });
export const LogicCondition = Template.bind({}); export const LogicCondition = make({
LogicCondition.args = {
condition: { condition: {
condition: "or", condition: "or",
conditions: [ conditions: [
@@ -81,9 +76,8 @@ LogicCondition.args = {
}, },
], ],
} as AutomationCondition, } as AutomationCondition,
}; });
export const TimeCondition = Template.bind({}); export const TimeCondition = make({
TimeCondition.args = {
condition: { condition: {
condition: "or", condition: "or",
conditions: [ conditions: [
@@ -104,7 +98,7 @@ TimeCondition.args = {
}, },
], ],
} as AutomationCondition, } as AutomationCondition,
}; });
export const MultipleConditions: ComponentStory<typeof ConditionEditor> = ( export const MultipleConditions: ComponentStory<typeof ConditionEditor> = (
args args
@@ -134,12 +128,12 @@ export const MultipleConditions: ComponentStory<typeof ConditionEditor> = (
], ],
}); });
return ( return (
<Page> <MockPage>
<ConditionEditor <ConditionEditor
onUpdate={setState} onUpdate={setState}
onDelete={() => {}} onDelete={() => {}}
condition={state} condition={state}
/> />
</Page> </MockPage>
); );
}; };
@@ -1,46 +1,34 @@
import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { DAGGraphBoard } from "."; import { DAGGraphBoard } from ".";
import { Page } from "components/Page";
import { SimpleErrorElement } from "components/SimpleErrorElement"; import { SimpleErrorElement } from "components/SimpleErrorElement";
export default { import { makeStory } from "devUtils";
title: "DAGGraph/Board",
component: DAGGraphBoard,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof DAGGraphBoard>;
const Template: ComponentStory<typeof DAGGraphBoard> = (args) => { const { make, componentMeta } = makeStory({
return ( Component: DAGGraphBoard,
<Page> meta: {
<DAGGraphBoard {...args} /> title: "DAGGraph/Board",
</Page> },
); });
};
export const Loading = Template.bind({}); export default componentMeta;
Loading.args = { export const Example = make({});
...Loading.args,
export const Loading = make({
state: { state: {
ready: false, ready: false,
}, },
}; });
export const Errored = Template.bind({}); export const Errored = make({
Errored.args = {
...Loading.args,
state: { state: {
ready: true, ready: true,
data: { data: {
error: <SimpleErrorElement error={new Error("Test")} />, error: <SimpleErrorElement error={new Error("Test")} />,
}, },
}, },
}; });
export const Empty = Template.bind({}); export const Empty = make({
Empty.args = {
...Empty.args,
state: { state: {
ready: true, ready: true,
data: { data: {
@@ -50,11 +38,9 @@ Empty.args = {
}, },
}, },
}, },
}; });
export const Basic = Template.bind({}); export const Basic = make({
Basic.args = {
...Basic.args,
state: { state: {
ready: true, ready: true,
data: { data: {
@@ -88,4 +74,4 @@ Basic.args = {
}, },
}, },
}, },
}; });
@@ -1,6 +1,6 @@
import React from "react"; import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { MockPage } from "components/Page";
import { ButtonNode } from "./ButtonNode"; import { ButtonNode } from "./ButtonNode";
import { DAGGraphBoard } from "components/DAGGraph/board"; import { DAGGraphBoard } from "components/DAGGraph/board";
import { ButtonNodeMaker } from "."; import { ButtonNodeMaker } from ".";
@@ -25,7 +25,7 @@ const Template: ComponentStory<typeof ButtonNode> = (args) => {
...args, ...args,
}; };
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -80,7 +80,7 @@ const Template: ComponentStory<typeof ButtonNode> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -13,6 +13,7 @@ import { prettyName } from "utils/formatting";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { useLang } from "lang";
export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> = export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
({ ({
@@ -27,6 +28,7 @@ export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
title, title,
children, children,
}) => { }) => {
const lang = useLang();
const color = convertNodeTypeToSequenceNodeColor(collectionType); const color = convertNodeTypeToSequenceNodeColor(collectionType);
const nodeColor = useSequenceNodeColor(color); const nodeColor = useSequenceNodeColor(color);
const confirm = useConfirm(); const confirm = useConfirm();
@@ -55,14 +57,19 @@ export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
}) })
.then(() => { .then(() => {
onDelete(); onDelete();
snackbr.enqueueSnackbar("Deleted.", { snackbr.enqueueSnackbar(lang.get("DELETED"), {
variant: "info", variant: "info",
}); });
}) })
.catch(() => .catch(() =>
snackbr.enqueueSnackbar(`Did not delete ${trueTile}.`, { snackbr.enqueueSnackbar(
variant: "info", lang.get("NOT_DELETED_THING", {
}) item: trueTile,
}),
{
variant: "info",
}
)
); );
}} }}
borderless borderless
@@ -1,7 +1,6 @@
import React, { FC } from "react"; import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { MockPage } from "components/Page";
import { CollectionNode } from "./CollectionNode";
import { DAGGraphBoard } from "components/DAGGraph/board"; import { DAGGraphBoard } from "components/DAGGraph/board";
import { CollectionNodeMaker } from "./index"; import { CollectionNodeMaker } from "./index";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants"; import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
@@ -19,7 +18,7 @@ type DemoProps = {
}; };
const Demo: FC<DemoProps> = (args) => { const Demo: FC<DemoProps> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -64,7 +63,7 @@ const Demo: FC<DemoProps> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -84,7 +83,7 @@ export const Colors: ComponentStory<typeof Demo> = (args) => <Demo {...args} />;
export const Empty: ComponentStory<typeof Demo> = (args) => { export const Empty: ComponentStory<typeof Demo> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -124,7 +123,7 @@ export const Empty: ComponentStory<typeof Demo> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -135,7 +134,7 @@ Empty.args = {
export const ReturnTarget: ComponentStory<typeof Demo> = (args) => { export const ReturnTarget: ComponentStory<typeof Demo> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -222,7 +221,7 @@ export const ReturnTarget: ComponentStory<typeof Demo> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -123,7 +123,7 @@
position: absolute; position: absolute;
top: -1em; top: -1em;
left: -1em; left: -1em;
background-color: var(--mui-common-black); background-color: var(--mui-background-paper);
border-color: var(--mui-grey-400); border-color: var(--mui-grey-400);
border-style: solid; border-style: solid;
border-width: 0.5px; border-width: 0.5px;
@@ -1,6 +1,6 @@
import React from "react"; import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { MockPage } from "components/Page";
import { SequenceNode } from "./SequenceNode"; import { SequenceNode } from "./SequenceNode";
import { DAGGraphBoard } from "components/DAGGraph/board"; import { DAGGraphBoard } from "components/DAGGraph/board";
import { SequenceNodeMaker } from "./index"; import { SequenceNodeMaker } from "./index";
@@ -21,7 +21,7 @@ export default {
const Template: ComponentStory<typeof SequenceNode> = (args) => { const Template: ComponentStory<typeof SequenceNode> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -46,13 +46,13 @@ const Template: ComponentStory<typeof SequenceNode> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
export const Colors: ComponentStory<typeof SequenceNode> = (args) => { export const Colors: ComponentStory<typeof SequenceNode> = (args) => {
return ( return (
<Page> <MockPage>
<DAGGraphBoard <DAGGraphBoard
closeModal={() => {}} closeModal={() => {}}
state={{ state={{
@@ -85,7 +85,7 @@ export const Colors: ComponentStory<typeof SequenceNode> = (args) => {
}, },
}} }}
/> />
</Page> </MockPage>
); );
}; };
@@ -16,6 +16,7 @@ import InputBoolean from "components/Inputs/Base/InputBoolean";
import { SpeedDial } from "components/SpeedDial"; import { SpeedDial } from "components/SpeedDial";
import { SequenceNodeElementProps } from "./types"; import { SequenceNodeElementProps } from "./types";
import { useSequenceNodeColor } from "./util"; import { useSequenceNodeColor } from "./util";
import { useLang } from "lang";
export const SequenceNodeElement: FC< export const SequenceNodeElement: FC<
PropsWithChildren<SequenceNodeElementProps> PropsWithChildren<SequenceNodeElementProps>
@@ -35,6 +36,7 @@ export const SequenceNodeElement: FC<
isClosed, isClosed,
setIsClosed, setIsClosed,
}) => { }) => {
const langStore = useLang();
const confirm = useConfirm(); const confirm = useConfirm();
const snackbr = useSnackbar(); const snackbr = useSnackbar();
const nodeColor = useSequenceNodeColor(color); const nodeColor = useSequenceNodeColor(color);
@@ -89,18 +91,21 @@ export const SequenceNodeElement: FC<
<IconButton <IconButton
onClick={() => { onClick={() => {
confirm({ confirm({
description: "Are you sure you want to delete this node?", description: langStore.get("CONFIRMATION_DELETE_THIS_NODE"),
}) })
.then(() => { .then(() => {
onXClick(); onXClick();
snackbr.enqueueSnackbar("Deleted.", { snackbr.enqueueSnackbar(langStore.get("DELETED"), {
variant: "info", variant: "info",
}); });
}) })
.catch(() => .catch(() =>
snackbr.enqueueSnackbar("Did not delete node.", { snackbr.enqueueSnackbar(
variant: "info", langStore.get("NOT_DELETED_NODE"),
}) {
variant: "info",
}
)
); );
}} }}
size="small" size="small"
+11 -4
View File
@@ -8,6 +8,7 @@ import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { cleanUpUndefined } from "utils/helpers"; import { cleanUpUndefined } from "utils/helpers";
import { DeviceBaseType, DeviceTypeCapability } from "haService/types"; import { DeviceBaseType, DeviceTypeCapability } from "haService/types";
import { AutomationDeviceState } from "types/automations/common"; import { AutomationDeviceState } from "types/automations/common";
import { useLang } from "lang";
export type DeviceEditorProps<DBT extends DeviceBaseType> = { export type DeviceEditorProps<DBT extends DeviceBaseType> = {
type: "action" | "condition" | "trigger"; type: "action" | "condition" | "trigger";
@@ -23,6 +24,8 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
caps, caps,
options, options,
}: DeviceEditorProps<DBT>) { }: DeviceEditorProps<DBT>) {
// state
const langStore = useLang();
// aliases // aliases
const update = (upd: Partial<AutomationDeviceState & Record<string, any>>) => const update = (upd: Partial<AutomationDeviceState & Record<string, any>>) =>
setState( setState(
@@ -40,13 +43,13 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
<> <>
<InputDevice <InputDevice
key="devices" key="devices"
label="Device" label={langStore.get("DEVICE")}
value={state.device_id ?? ""} value={state.device_id ?? ""}
onChange={(device_id) => setState({ device_id: device_id ?? "" })} onChange={(device_id) => setState({ device_id: device_id ?? "" })}
/> />
<InputAutoComplete <InputAutoComplete
key="action" key="action"
label="Action" label={langStore.get("ACTION")}
multiple={false} multiple={false}
value={actionId} value={actionId}
options={Object.keys(options).map((k) => options[k])} options={Object.keys(options).map((k) => options[k])}
@@ -67,7 +70,7 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
{entities.length > 0 && ( {entities.length > 0 && (
<InputEntity <InputEntity
key={"entities" + state.device_id} key={"entities" + state.device_id}
label="Entity" label={langStore.get("ENTITY")}
value={state.entity_id ?? ""} value={state.entity_id ?? ""}
multiple={false} multiple={false}
onChange={(entity_id) => onChange={(entity_id) =>
@@ -85,7 +88,11 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
/> />
)} )}
{Object.keys(options).length + entities.length === 0 && ( {Object.keys(options).length + entities.length === 0 && (
<>This device has no {type}s.</> <>
{langStore.get("WARNING_DEVICE_NO_TYPES", {
type: `${type}s`,
})}
</>
)} )}
</> </>
); );
@@ -1,35 +1,43 @@
import React, { FC } from "react"; import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { ErrorBoundary } from "."; import { ErrorBoundary } from ".";
import { Page } from "components/Page";
import { makeStory } from "devUtils";
import { MockPage } from "components/Page";
import { ComponentStory } from "@storybook/react";
export default { const { make, componentMeta } = makeStory({
title: 'ErrorBoundary', Component: () => <div>Example</div>,
meta: {
title: "ErrorBoundary",
component: ErrorBoundary, component: ErrorBoundary,
parameters: { actions: { argTypesRegex: '^on.*' } }, },
args: { });
}
} as ComponentMeta<typeof ErrorBoundary>
export const ErrorThrown: ComponentStory<typeof ErrorBoundary> = args => { export default componentMeta;
const BadComponent: FC = () => { export const Example = make({});
throw new Error("!!!")
}
return <Page>
<ErrorBoundary>
<BadComponent />
</ErrorBoundary>
</Page>
}
export const NoError: ComponentStory<typeof ErrorBoundary> = args => { export const ErrorThrown: ComponentStory<typeof ErrorBoundary> = (args) => {
const GoodComponent: FC = () => { const BadComponent: FC = () => {
return <span>All Good.</span> throw new Error("!!!");
} };
return <Page> return (
<ErrorBoundary> <MockPage>
<GoodComponent /> <ErrorBoundary>
</ErrorBoundary> <BadComponent />
</Page> </ErrorBoundary>
} </MockPage>
);
};
export const NoError: ComponentStory<typeof ErrorBoundary> = (args) => {
const GoodComponent: FC = () => {
return <span>All Good.</span>;
};
return (
<MockPage>
<ErrorBoundary>
<GoodComponent />
</ErrorBoundary>
</MockPage>
);
};
+25 -13
View File
@@ -1,6 +1,8 @@
import "./ButtonIcons.css"; import "./ButtonIcons.css";
import Tooltip from "@mui/material/Tooltip";
import { FC, ReactNode } from "react"; import { FC, ReactNode } from "react";
import MuiIconButton, { IconButtonTypeMap } from "@mui/material/IconButton"; import IconButton, { IconButtonTypeMap } from "@mui/material/IconButton";
import { useLang } from "lang";
export type ButtonIconProps = { export type ButtonIconProps = {
icon: ReactNode; icon: ReactNode;
@@ -10,21 +12,31 @@ export type ButtonIconProps = {
disabled?: boolean; disabled?: boolean;
color?: IconButtonTypeMap["props"]["color"]; color?: IconButtonTypeMap["props"]["color"];
borderless?: boolean; borderless?: boolean;
titleSlug?: string;
titleParams?: Record<string, string>;
}; };
export const ButtonIcon: FC<ButtonIconProps> = (props) => { export const ButtonIcon: FC<ButtonIconProps> = (props) => {
const langStore = useLang();
return ( return (
<MuiIconButton <Tooltip
className={[ title={
"icon-button", props.titleSlug ? langStore.get(props.titleSlug, props.titleParams) : ""
props.className ?? "", }
props.borderless ? "borderless" : "", describeChild
].join(" ")}
onClick={props.onClick}
title={props.title}
color={props.color}
disabled={props.disabled}
> >
{props.icon} <IconButton
</MuiIconButton> className={[
"icon-button",
props.className ?? "",
props.borderless ? "borderless" : "",
].join(" ")}
onClick={props.onClick}
title={props.title}
color={props.color}
disabled={props.disabled}
>
{props.icon}
</IconButton>
</Tooltip>
); );
}; };
@@ -12,7 +12,7 @@ import {
GearIcon, GearIcon,
} from "."; } from ".";
import { ButtonIcon } from "./ButtonIcons"; import { ButtonIcon } from "./ButtonIcons";
import { Page } from "components/Page"; import { MockPage } from "components/Page";
export default { export default {
title: "Icons", title: "Icons",
@@ -21,7 +21,7 @@ export default {
export const IconList: ComponentStory<typeof IconBase> = (args) => { export const IconList: ComponentStory<typeof IconBase> = (args) => {
return ( return (
<Page> <MockPage>
<PencilIcon {...args} /> <PencilIcon {...args} />
<CheckMarkIcon {...args} /> <CheckMarkIcon {...args} />
<AddIcon {...args} /> <AddIcon {...args} />
@@ -29,7 +29,7 @@ export const IconList: ComponentStory<typeof IconBase> = (args) => {
<InfoIcon {...args} /> <InfoIcon {...args} />
<ZoomIcon {...args} /> <ZoomIcon {...args} />
<GearIcon {...args} /> <GearIcon {...args} />
</Page> </MockPage>
); );
}; };
IconList.args = { IconList.args = {
@@ -39,9 +39,9 @@ IconList.args = {
export const ButtonIconExample: ComponentStory<typeof IconBase> = (args) => { export const ButtonIconExample: ComponentStory<typeof IconBase> = (args) => {
return ( return (
<Page> <MockPage>
<ButtonIcon icon={<ArrowIcon {...args} />} /> <ButtonIcon icon={<ArrowIcon {...args} />} />
</Page> </MockPage>
); );
}; };
ButtonIconExample.args = { ButtonIconExample.args = {
@@ -4,6 +4,7 @@ import {
InputAutoCompletePropsBase, InputAutoCompletePropsBase,
} from "./InputAutoComplete"; } from "./InputAutoComplete";
import { useHAAreas } from "haService/AreaRegistry"; import { useHAAreas } from "haService/AreaRegistry";
import { useLang } from "lang";
export type InputAreaProps = InputAutoCompletePropsBase & { export type InputAreaProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[]; restrictToDomain?: string[];
@@ -11,12 +12,13 @@ export type InputAreaProps = InputAutoCompletePropsBase & {
}; };
export const InputArea: FC<InputAreaProps> = (props) => { export const InputArea: FC<InputAreaProps> = (props) => {
const lang = useLang();
// state // state
const areas = useHAAreas(); const areas = useHAAreas();
return ( return (
<InputAutoComplete <InputAutoComplete
{...props} {...props}
label={props.label ?? "Area"} label={props.label ?? lang.get("AREA")}
getID={areas.getID} getID={areas.getID}
getLabel={areas.getLabel} getLabel={areas.getLabel}
options={areas.getOptions()} options={areas.getOptions()}
@@ -7,6 +7,7 @@ import Popper from "@mui/material/Popper";
import { SearchItem } from "./extras"; import { SearchItem } from "./extras";
import { ReactNode } from "react"; import { ReactNode } from "react";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { useLang } from "lang";
export type BaseOption<T = {}> = { export type BaseOption<T = {}> = {
id: string; id: string;
@@ -65,6 +66,7 @@ export function computeSimilarity(
export function InputAutoComplete<T extends Option>( export function InputAutoComplete<T extends Option>(
props: InputAutoCompleteProps<T> props: InputAutoCompleteProps<T>
) { ) {
const lang = useLang();
// aliases // aliases
const getID = (opt: T): string => { const getID = (opt: T): string => {
if (props.getID) { if (props.getID) {
@@ -212,7 +214,7 @@ export function InputAutoComplete<T extends Option>(
}} }}
variant="filled" variant="filled"
required={props.required} required={props.required}
label={props.label ?? "Entity ID"} label={props.label ?? lang.get("ENTITY_ID")}
helperText={helperText} helperText={helperText}
disabled={props.disabled} disabled={props.disabled}
error={error} error={error}
@@ -1,36 +1,39 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import { InputDevice } from "./InputDevice"; import { InputDevice } from "./InputDevice";
export default { import { makeStory } from "devUtils";
title: 'Inputs/InputDevice',
component: InputDevice,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputDevice>;
const { make, componentMeta } = makeStory({
Component: InputDevice,
meta: {
title: "Inputs/InputDevice",
},
BaseTemplate: (args) => {
const [value, setValue] = useState(args.value);
return (
<div
style={{
maxWidth: 200,
}}
>
<InputDevice
{...args}
value={value as any}
onChange={(v: any) => {
setValue(v);
args.onChange(v as any);
}}
/>
</div>
);
},
});
export default componentMeta;
export const Example = make({});
const Template: ComponentStory<typeof InputDevice> = args => { export const Single = make({
const [value, setValue] = useState(args.value)
return <Page>
<div style={{
maxWidth: 200
}}>
<InputDevice {...args} value={value as any} onChange={(v: any) => {
setValue(v)
args.onChange(v as any)
}} />
</div>
</Page>
}
export const Single = Template.bind({})
Single.args = {
...Single.args,
multiple: false, multiple: false,
value: 'sensor.humidity_bathroom' value: "sensor.humidity_bathroom",
} as any });
@@ -1,5 +1,6 @@
import { FC } from "react"; import { FC } from "react";
import { useHADeviceRegistry } from "haService"; import { useHADeviceRegistry } from "haService";
import { useLang } from "lang";
import { import {
InputAutoComplete, InputAutoComplete,
InputAutoCompletePropsBase, InputAutoCompletePropsBase,
@@ -9,11 +10,12 @@ export type InputDeviceProps = InputAutoCompletePropsBase;
export const InputDevice: FC<InputDeviceProps> = (props) => { export const InputDevice: FC<InputDeviceProps> = (props) => {
// state // state
const lang = useLang();
const dr = useHADeviceRegistry(); const dr = useHADeviceRegistry();
return ( return (
<InputAutoComplete <InputAutoComplete
{...props} {...props}
label={props.label ?? "Device"} label={props.label ?? lang.get("DEVICE")}
getID={dr.getID} getID={dr.getID}
getLabel={dr.getLabel} getLabel={dr.getLabel}
options={dr.getOptions()} options={dr.getOptions()}
@@ -1,84 +1,77 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import { InputEntity } from "./InputEntities"; import { InputEntity } from "./InputEntities";
export default { import { makeStory } from "devUtils";
title: 'Inputs/InputEntity',
component: InputEntity,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputEntity>;
const { make, componentMeta } = makeStory({
Component: InputEntity,
meta: {
title: "Inputs/InputEntity",
},
BaseTemplate: (args) => {
const [value, setValue] = useState(args.value);
return (
<div
style={{
maxWidth: 200,
}}
>
<InputEntity
{...args}
value={value as any}
onChange={(v: any) => {
setValue(v);
args.onChange(v as any);
}}
/>
</div>
);
},
});
export default componentMeta;
export const Example = make({});
const Template: ComponentStory<typeof InputEntity> = args => { export const Single = make({
const [value, setValue] = useState(args.value)
return <Page>
<div style={{
maxWidth: 200
}}>
<InputEntity {...args} value={value as any} onChange={(v: any) => {
setValue(v)
args.onChange(v as any)
}} />
</div>
</Page>
}
export const Single = Template.bind({})
Single.args = {
...Single.args,
multiple: false, multiple: false,
value: 'sensor.bathroom' value: "sensor.bathroom",
} as any });
export const Many = Template.bind({}) export const Many = make({
Many.args = {
...Many.args,
multiple: true, multiple: true,
value: ['sensor.bathroom', 'person.ari'] value: ["sensor.bathroom", "person.ari"],
} as any });
export const ManyEmpty = Template.bind({}) export const ManyEmpty = make({
ManyEmpty.args = {
...ManyEmpty.args,
multiple: true, multiple: true,
value: [] value: [],
} as any });
export const ManyButGotSingle = make({
export const ManyButGotSingle = Template.bind({})
ManyButGotSingle.args = {
...ManyButGotSingle.args,
multiple: true, multiple: true,
value: 'sensor.bathroom' value: "sensor.bathroom",
} as any });
export const InvalidDomain = make({
export const InvalidDomain = Template.bind({})
InvalidDomain.args = {
...InvalidDomain.args,
multiple: true, multiple: true,
value: 'sensor.bathroom', value: "sensor.bathroom",
restrictToDomain: ['zone'], restrictToDomain: ["zone"],
} as any });
export const InvalidManyDomain = make({
export const InvalidManyDomain = Template.bind({})
InvalidManyDomain.args = {
...InvalidManyDomain.args,
multiple: true, multiple: true,
value: 'sensor.bathroom', value: "sensor.bathroom",
restrictToDomain: ['zone', 'switch'], restrictToDomain: ["zone", "switch"],
} as any });
export const InvalidLots = Template.bind({}) export const InvalidLots = make({
InvalidLots.args = {
...InvalidLots.args,
multiple: true, multiple: true,
value: ['person.ari', 'sensor.bathroom', 'binary_sensor.ping_tv', 'device_tracker.phone'], value: [
restrictToDomain: ['zone', 'switch'], "person.ari",
} as any "sensor.bathroom",
"binary_sensor.ping_tv",
"device_tracker.phone",
],
restrictToDomain: ["zone", "switch"],
});
@@ -1,36 +1,39 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import { InputService } from "./InputService"; import { InputService } from "./InputService";
export default { import { makeStory } from "devUtils";
title: 'Inputs/InputService',
component: InputService,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputService>;
const { make, componentMeta } = makeStory({
Component: InputService,
meta: {
title: "Inputs/InputService",
},
BaseTemplate: (args) => {
const [value, setValue] = useState(args.value);
return (
<div
style={{
maxWidth: 200,
}}
>
<InputService
{...args}
value={value as any}
onChange={(v: any) => {
setValue(v);
args.onChange(v as any);
}}
/>
</div>
);
},
});
export default componentMeta;
export const Example = make({});
const Template: ComponentStory<typeof InputService> = args => { export const Single = make({
const [value, setValue] = useState(args.value)
return <Page>
<div style={{
maxWidth: 200
}}>
<InputService {...args} value={value as any} onChange={(v: any) => {
setValue(v)
args.onChange(v as any)
}} />
</div>
</Page>
}
export const Single = Template.bind({})
Single.args = {
...Single.args,
multiple: false, multiple: false,
value: '' value: "",
} as any });
@@ -1,19 +1,27 @@
import { FC } from "react"; import { FC } from "react";
import { useHAServices } from 'haService'; import { useHAServices } from "haService";
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete'; import {
import { prettyName } from 'utils/formatting'; InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { prettyName } from "utils/formatting";
import { useLang } from "lang";
export type InputServiceProps = InputAutoCompletePropsBase & { multiple?: false }; export type InputServiceProps = InputAutoCompletePropsBase & {
multiple?: false;
};
export const InputService: FC<InputServiceProps> = props => { export const InputService: FC<InputServiceProps> = (props) => {
const services = useHAServices(); const services = useHAServices();
return <InputAutoComplete const lang = useLang();
{...props} return (
label={props.label ?? "Service"} <InputAutoComplete
options={services.getOptions()} {...props}
getID={services.getID} label={props.label ?? lang.get("SERVICE")}
getLabel={services.getLabel} options={services.getOptions()}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''} getID={services.getID}
getLabel={services.getLabel}
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
/> />
} );
};
@@ -1,19 +1,17 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import { InputTimeEntity } from "./InputTimeEntity"; import { InputTimeEntity } from "./InputTimeEntity";
export default { import { makeStory } from "devUtils";
title: "Inputs/InputTimeEntity",
component: InputTimeEntity,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof InputTimeEntity>;
const Template: ComponentStory<typeof InputTimeEntity> = (args) => { const { make, componentMeta } = makeStory({
const [value, setValue] = useState(""); Component: InputTimeEntity,
return ( meta: {
<Page> title: "Inputs/InputTimeEntity",
},
BaseTemplate: (args) => {
const [value, setValue] = useState("");
return (
<div <div
style={{ style={{
padding: "1em", padding: "1em",
@@ -28,8 +26,8 @@ const Template: ComponentStory<typeof InputTimeEntity> = (args) => {
}} }}
/> />
</div> </div>
</Page> );
); },
}; });
export const SimpleText = Template.bind({}); export const SimpleText = make({});
@@ -12,6 +12,7 @@ import {
} from "utils/time"; } from "utils/time";
import { InputEntity } from "./InputEntities"; import { InputEntity } from "./InputEntities";
import { InputTime } from "components/Inputs/Base/InputTime"; import { InputTime } from "components/Inputs/Base/InputTime";
import { useLang } from "lang";
export type InputTimeEntityProps = { export type InputTimeEntityProps = {
value: string; value: string;
@@ -23,6 +24,7 @@ export const InputTimeEntity: FC<InputTimeEntityProps> = ({
onChange, onChange,
className = "", className = "",
}) => { }) => {
const lang = useLang();
const is24Hour = isAutomationTimeString24Hours(value); const is24Hour = isAutomationTimeString24Hours(value);
let editor: ReactNode; let editor: ReactNode;
if (is24Hour) { if (is24Hour) {
@@ -39,7 +41,7 @@ export const InputTimeEntity: FC<InputTimeEntityProps> = ({
} else { } else {
editor = ( editor = (
<InputEntity <InputEntity
label="Time Entity" label={lang.get("TIME_ENTITY")}
restrictMode="or" restrictMode="or"
restrictedDeviceClass={["timestamp"]} restrictedDeviceClass={["timestamp"]}
restrictToDomain={["input_datetime"]} restrictToDomain={["input_datetime"]}
@@ -1,18 +1,14 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { SearchItem } from "./extras"; import { SearchItem } from "./extras";
export default { import { makeStory } from "devUtils";
title: "Inputs/Extras/SearchItem",
component: SearchItem,
parameters: { actions: { argTypesRegex: "^on.*" } },
argTypes: {},
} as ComponentMeta<typeof SearchItem>;
const Template: ComponentStory<typeof SearchItem> = (args) => { const { make, componentMeta } = makeStory({
return ( Component: SearchItem,
<Page> meta: {
title: "Inputs/Extras/SearchItem",
},
BaseTemplate: (args) => {
return (
<div <div
style={{ style={{
width: "15em", width: "15em",
@@ -22,15 +18,16 @@ const Template: ComponentStory<typeof SearchItem> = (args) => {
> >
<SearchItem {...args} /> <SearchItem {...args} />
</div> </div>
</Page> );
); },
}; });
export const Simple = Template.bind({}); export default componentMeta;
Simple.args = {
export const Simple = make({
id: "sensor.humidity_main_bedroom", id: "sensor.humidity_main_bedroom",
label: "Main Bedroom Humidity", label: "Main Bedroom Humidity",
searchTerm: "bedroom", searchTerm: "bedroom",
listProps: {}, listProps: {},
onlyShowLabel: false, onlyShowLabel: false,
}; });
@@ -4,24 +4,30 @@ import { useState } from "react";
import InputBoolean from "./InputBoolean"; import InputBoolean from "./InputBoolean";
export default { import { makeStory } from "devUtils";
title: 'Inputs/InputBoolean',
component: InputBoolean,
parameters: { actions: { argTypesRegex: '^on.*' } },
} as ComponentMeta<typeof InputBoolean>;
const { make, componentMeta } = makeStory({
Component: InputBoolean,
meta: {
title: "Inputs/InputBoolean",
args: {
label: "Template",
},
},
BaseTemplate: (args) => {
const [state, onChange] = useState(args.value);
return (
<InputBoolean
{...args}
value={state}
onChange={(v) => {
args.onChange(v);
onChange(v);
}}
/>
);
},
});
const Template: ComponentStory<typeof InputBoolean> = args => { export default componentMeta;
const [state, onChange] = useState(args.value) export const Example = make({});
return <Page>
<InputBoolean {...args} value={state} onChange={v => {
args.onChange(v)
onChange(v)
}} />
</Page>
}
export const SimpleText = Template.bind({})
SimpleText.args = {
label: "Template",
}
@@ -1,32 +1,31 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import InputNumber from "./InputNumber"; import InputNumber from "./InputNumber";
export default { import { makeStory } from "devUtils";
title: 'Inputs/InputNumber',
component: InputNumber,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {
label: {
defaultValue: 'Sample Title'
}
}
} as ComponentMeta<typeof InputNumber>;
const { make, componentMeta } = makeStory({
Component: InputNumber,
meta: {
title: "Inputs/InputNumber",
argTypes: {
label: {
defaultValue: "Sample Title",
},
},
},
BaseTemplate: (args) => {
const [value, setValue] = useState<number | undefined>(args.value);
return <InputNumber {...args} value={value} onChange={setValue} />;
},
});
export const NullStart: ComponentStory<typeof InputNumber> = args => { export default componentMeta;
const [value, setValue] = useState<number | undefined>(undefined) export const NullStart = make({
return <Page> value: undefined,
<InputNumber {...args} value={value} onChange={setValue} /> });
</Page>
}
export const SomeStuffAtStart: ComponentStory<typeof InputNumber> = args => {
const [value, setValue] = useState<number | undefined>(10) export const SomeStuffAtStart = make({
return <Page> value: 10,
<InputNumber {...args} value={value} onChange={setValue} /> });
</Page>
}
@@ -4,22 +4,21 @@ import { useState } from "react";
import InputText from "./InputText"; import InputText from "./InputText";
export default { import { makeStory } from "devUtils";
title: 'Inputs/InputText',
component: InputText,
parameters: { actions: { argTypesRegex: '^on.*' } },
} as ComponentMeta<typeof InputText>;
const { make, componentMeta } = makeStory({
Component: InputText,
meta: {
title: "Inputs/InputText",
},
BaseTemplate: (args) => {
const [value, setValue] = useState("");
return <InputText {...args} value={value} onChange={setValue} />;
},
});
const Template: ComponentStory<typeof InputText> = args => { export default componentMeta;
const [value, setValue] = useState('') export const SimpleText = make({
return <Page>
<InputText {...args} value={value} onChange={setValue} />
</Page>
}
export const SimpleText = Template.bind({})
SimpleText.args = {
label: "Entity ID", label: "Entity ID",
} });
@@ -1,20 +1,15 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import { AutomationTime } from "types/automations/common"; import { AutomationTime } from "types/automations/common";
import { InputTime } from "./InputTime"; import { InputTime } from "./InputTime";
export default { import { makeStory } from "devUtils";
title: "Inputs/InputTime",
component: InputTime,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof InputTime>;
const Template: ComponentStory<typeof InputTime> = (args) => { const { make, componentMeta } = makeStory({
const [value, setValue] = useState<AutomationTime | undefined>(undefined); Component: InputTime,
return ( BaseTemplate: (args) => {
<Page> const [value, setValue] = useState<AutomationTime | undefined>(undefined);
return (
<div <div
style={{ style={{
padding: "1em", padding: "1em",
@@ -29,12 +24,17 @@ const Template: ComponentStory<typeof InputTime> = (args) => {
}} }}
/> />
</div> </div>
</Page> );
); },
}; meta: {
title: "Inputs/InputTime",
},
});
export const SimpleText = Template.bind({}); export default componentMeta;
SimpleText.args = { export const Example = make({});
export const SimpleText = make({
label: "Time Stamp", label: "Time Stamp",
value: "10", value: "10",
}; });
+22 -15
View File
@@ -12,6 +12,7 @@ import {
} from "utils/time"; } from "utils/time";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
// constants // constants
const fields: Array<keyof AutomationTimeObject> = [ const fields: Array<keyof AutomationTimeObject> = [
@@ -29,6 +30,7 @@ export type InputTimeProps = {
}; };
export const InputTime: FC<InputTimeProps> = (props) => { export const InputTime: FC<InputTimeProps> = (props) => {
// state // state
const lang = useLang();
const [disabled, setDisabled] = useState(!props.value); const [disabled, setDisabled] = useState(!props.value);
const [displayValue, setDisplayValue] = useState( const [displayValue, setDisplayValue] = useState(
convertAutomationTimeToTimeObject(props.value) convertAutomationTimeToTimeObject(props.value)
@@ -127,21 +129,26 @@ export const InputTime: FC<InputTimeProps> = (props) => {
<div className={["input-time", props.className ?? ""].join(" ")}> <div className={["input-time", props.className ?? ""].join(" ")}>
{/* <InputLabel >{props.label}</InputLabel> */} {/* <InputLabel >{props.label}</InputLabel> */}
<div className="input-time--inner"> <div className="input-time--inner">
{fields.map((name) => ( {fields.map((name) => {
<TextField const label = prettyName(
key={name} lang.get(`TIME_UNITS_${name}`.toUpperCase())
variant="filled" );
label={prettyName(name)} return (
defaultValue="00" <TextField
InputProps={{ key={name}
disabled, variant="filled"
type: "number", label={label}
title: prettyName(name), defaultValue="00"
}} InputProps={{
value={displayValue[name] ?? 0} disabled,
onChange={(e) => updateOne(name)(e.target.value)} type: "number",
/> title: label,
))} }}
value={displayValue[name] ?? 0}
onChange={(e) => updateOne(name)(e.target.value)}
/>
);
})}
{!props.restrictEmpty && ( {!props.restrictEmpty && (
<ButtonIcon <ButtonIcon
onClick={() => setDisabled(!disabled)} onClick={() => setDisabled(!disabled)}
@@ -4,24 +4,24 @@ import { useState } from "react";
import InputYaml from "./InputYaml"; import InputYaml from "./InputYaml";
export default { import { makeStory } from "devUtils";
title: 'Inputs/InputYaml',
component: InputYaml,
parameters: { actions: { argTypesRegex: '^on.*' } },
} as ComponentMeta<typeof InputYaml>;
const { make, componentMeta } = makeStory({
Component: InputYaml,
BaseTemplate: (args) => {
const [value, setValue] = useState({
test: "data",
});
return <InputYaml {...args} value={value} onChange={setValue} />;
},
meta: {
title: "Inputs/InputYaml",
},
});
const Template: ComponentStory<typeof InputYaml> = args => { export default componentMeta;
export const Example = make({});
const [value, setValue] = useState({ export const SimpleText = make({
"test": "data"
})
return <Page>
<InputYaml {...args} value={value} onChange={setValue} />
</Page>
}
export const SimpleText = Template.bind({})
SimpleText.args = {
label: "Template", label: "Template",
} });
@@ -9,6 +9,7 @@ import FormHelperText from "@mui/material/FormHelperText";
import InputAdornment from "@mui/material/InputAdornment"; import InputAdornment from "@mui/material/InputAdornment";
import { Save } from "@mui/icons-material"; import { Save } from "@mui/icons-material";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
export interface Props<T extends {}> { export interface Props<T extends {}> {
label: string; label: string;
@@ -34,6 +35,7 @@ export default function InputYaml<T extends {}>({
helperText, helperText,
endAdornment, endAdornment,
}: Props<T>) { }: Props<T>) {
const langStore = useLang();
const originalText = yaml.dump(value); const originalText = yaml.dump(value);
const [{ text, error }, setState] = useState<{ const [{ text, error }, setState] = useState<{
text: string; text: string;
@@ -48,7 +50,7 @@ export default function InputYaml<T extends {}>({
yaml.load(t); yaml.load(t);
setState({ text: t, error: undefined }); setState({ text: t, error: undefined });
} catch (_) { } catch (_) {
setState({ text: t, error: "! Invalid Yaml !" }); setState({ text: t, error: langStore.get("ERROR_INVALID_YAML") });
} }
}; };
const onSave = () => { const onSave = () => {
@@ -94,7 +96,9 @@ export default function InputYaml<T extends {}>({
<ButtonIcon <ButtonIcon
disabled={!hasChanged} disabled={!hasChanged}
onClick={() => onSave()} onClick={() => onSave()}
title={!!error ? "Invalid YAML" : hasChanged ? "Save" : ""} title={
!!error ? "Invalid YAML" : hasChanged ? langStore.get("SAVE") : ""
}
icon={ icon={
<Save <Save
color={hasChanged ? (!!error ? "error" : "success") : "disabled"} color={hasChanged ? (!!error ? "error" : "success") : "disabled"}
@@ -1,29 +1,22 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import InputAutoText from "./InputAutoText"; import InputAutoText from "./InputAutoText";
export default { import { makeStory } from "devUtils";
title: "Inputs/InputAutoText",
component: InputAutoText, const { make, componentMeta } = makeStory({
parameters: { actions: { argTypesRegex: "^on.*" } }, Component: InputAutoText,
args: { meta: {
label: "Something", title: "Inputs/InputAutoText",
value: "", args: {
options: ["test", "usa", "canada"], label: "Something",
value: "",
options: ["test", "usa", "canada"],
},
}, },
} as ComponentMeta<typeof InputAutoText>; });
const Template: ComponentStory<typeof InputAutoText> = (args) => { export default componentMeta;
return ( export const Example = make({});
<Page>
<InputAutoText {...args} />
</Page>
);
};
export const Basic = Template.bind({}); export const WithError = make({
export const WithError = Template.bind({});
WithError.args = {
...WithError.args,
error: "Oh no!", error: "Oh no!",
}; });
@@ -1,47 +1,35 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { Page } from "components/Page";
import { useState, useEffect } from 'react'; import { useState, useEffect } from "react";
import { InputList } from "./InputList"; import { InputList } from "./InputList";
export default { import { makeStory } from "devUtils";
title: 'Inputs/InputList',
component: InputList,
parameters: { actions: { argTypesRegex: '^on.*' } },
} as ComponentMeta<typeof InputList>;
const { make, componentMeta } = makeStory({
Component: InputList,
BaseTemplate: (args) => {
const [value, setValue] = useState(args.current);
useEffect(() => {
if (value !== args.current) {
setValue(args.current);
}
}, [args.current]);
return <InputList {...args} current={value} onChange={setValue} />;
},
meta: {
title: "Inputs/InputList",
},
});
const Template: ComponentStory<typeof InputList> = args => { export default componentMeta;
const [value, setValue] = useState(args.current); export const SimpleText = make({
useEffect(() => {
if (value !== args.current) {
setValue(args.current)
}
}, [args.current])
return <Page>
<InputList {...args} current={value} onChange={setValue} />
</Page>
}
export const SimpleText = Template.bind({})
SimpleText.args = {
label: "Entity ID", label: "Entity ID",
options: [ options: ["Bob", "Martin", "Toots"],
'Bob', });
'Martin',
"Toots"
]
}
export const InvalidSelection = make({
export const InvalidSelection = Template.bind({})
InvalidSelection.args = {
current: "Derek", current: "Derek",
label: "Entity ID", label: "Entity ID",
options: [ options: ["Bob", "Martin", "Toots"],
'Bob', });
'Martin',
"Toots"
]
}
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more