Compare commits

...
29 Commits
Author SHA1 Message Date
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
104 changed files with 2020 additions and 1250 deletions

No files matched your search

+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
+9
View File
@@ -1,5 +1,14 @@
# 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.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.2] - Patches ## [0.6.2] - Patches
- Attempting to increasing websocket file limit - Attempting to increasing websocket file limit
+2 -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
+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("/")
+7 -1
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")
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,22 @@ def make_automation_router(automations: AutomationManager) -> APIRouter:
@router.post("/item") @router.post("/item")
def insert_auto(body: Automation): def insert_auto(body: Automation):
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):
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)
+22 -110
View File
@@ -1,129 +1,41 @@
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] = {}
def reset(self): def reset(self):
self.db_file.unlink(missing_ok=True) self.db = {}
self.create_db()
@contextmanager
def get_cur(self) -> Iterator[sqlite3.Cursor]:
conn = sqlite3.connect(self.db_file)
cur = conn.cursor()
try:
yield cur
conn.commit()
except sqlite3.DatabaseError as err:
raise DBError(*err.args) from err
finally:
cur.close()
conn.close()
def create_db(self):
with self.get_cur() as cur:
cur.execute(
f"""
CREATE TABLE IF NOT EXISTS {automations_tbl} (
id TEXT NOT NULL PRIMARY KEY,
alias TEXT,
description TEXT,
mode TEXT NOT NULL,
source_file TEXT NOT NULL,
source_file_type TEXT NOT NULL,
configuration_key BLOB NOT NULL,
rest BLOB NOT NULL
);
"""
)
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 self.db.get(automation.id, None) is None:
cur.execute( self.db[automation.id] = automation
f""" else:
INSERT INTO {automations_tbl} VALUES ( repeated_automations.append(
"{automation.id}", f"automation id '{automation.id}' in '{automation.source_file}' was already seen before. Please check for duplicate automation ids in your files."
"{automation.alias}", )
"{automation.description}", if len(repeated_automations) > 0:
"{automation.mode}", raise RepeatedAutomationId(repeated_automations)
"{automation.source_file}",
"{automation.source_file_type}",
"{encode_obj(automation.configuration_key)}",
"{encode_auto(automation)}"
);
""",
)
except sqlite3.IntegrityError as err:
raise RepeatedAutomationId(
f"automation id '{automation.id}' in '{automation.source_file}' was already seen before. Please check for duplicate automation ids in your files."
) from err
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.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
+4 -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)
+6
View File
@@ -15,11 +15,17 @@ 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]
+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))
+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)
@@ -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()
+1 -1
View File
@@ -1,5 +1,5 @@
name: Shortumation name: Shortumation
version: v0.6.2 version: v0.6.3
slug: shortumation slug: shortumation
image: asosnovsky/shortumation-{arch} image: asosnovsky/shortumation-{arch}
url: "https://github.com/asosnovsky/Shortumation" url: "https://github.com/asosnovsky/Shortumation"
+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>
+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);
+8 -6
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(),
+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,
},
})
),
};
};
@@ -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,23 +103,23 @@ 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}
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"]}
@@ -129,14 +131,14 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<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,23 +1,21 @@
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(
@@ -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,7 @@ 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";
interface Props { interface Props {
automation?: AutomationData | BareAutomationData; automation?: AutomationData | BareAutomationData;
@@ -51,6 +52,7 @@ export const AutomationEditor: FC<Props> = ({
isNew, isNew,
}) => { }) => {
// state // state
const langStore = useLang();
const { const {
state, state,
updateSequence, updateSequence,
@@ -131,7 +133,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 +147,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 +167,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 +204,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,7 +217,7 @@ 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>
<DAGAutomationGraph <DAGAutomationGraph
@@ -242,26 +242,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 +277,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,
@@ -317,12 +318,10 @@ export const ValidationBox: FC<{
</> </>
))} ))}
</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>
); );
@@ -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]
@@ -54,13 +56,13 @@ export const useAutomationDB = (
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,7 +74,8 @@ 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 configData: Record<string, AutomationData> = configAutomations.reduce(
(all, n) => ({ (all, n) => ({
@@ -93,7 +96,9 @@ const genMapping = (
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 +112,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] = [
@@ -134,13 +139,12 @@ const genMapping = (
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.",
}, },
auto, auto,
]; ];
@@ -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);
@@ -76,8 +78,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();
@@ -44,10 +46,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 (_) {
@@ -128,9 +129,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>
); );
}; };
@@ -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"
@@ -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,
@@ -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"]}
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,
@@ -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 = {
@@ -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,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,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({});
@@ -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",
}; });
@@ -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"
]
}
+17 -1
View File
@@ -7,6 +7,7 @@ import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select"; import Select from "@mui/material/Select";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { ReactNode } from "react"; import { ReactNode } from "react";
import { useLang } from "lang";
export type Props<T extends string | Object> = { export type Props<T extends string | Object> = {
current?: T; current?: T;
@@ -17,6 +18,7 @@ export type Props<T extends string | Object> = {
className?: string; className?: string;
prettyOptionLabels?: boolean; prettyOptionLabels?: boolean;
getKey?: (n: T) => string; getKey?: (n: T) => string;
getLabel?: (n: T) => string;
getDescription?: (n: T) => string; getDescription?: (n: T) => string;
placeholder?: any; placeholder?: any;
title?: string; title?: string;
@@ -34,6 +36,7 @@ export function InputList<T extends string | Object>({
className, className,
prettyOptionLabels = true, prettyOptionLabels = true,
getKey = String, getKey = String,
getLabel: _getLabel,
getDescription, getDescription,
placeholder, placeholder,
title, title,
@@ -42,8 +45,17 @@ export function InputList<T extends string | Object>({
disabled, disabled,
fullWidth = true, fullWidth = true,
}: Props<T>) { }: Props<T>) {
const langStore = useLang();
const invalidCurrent = const invalidCurrent =
current && !options.map(getKey).includes(getKey(current)); current && !options.map(getKey).includes(getKey(current));
const getLabel =
_getLabel ??
function (x: T) {
return typeof x === "string"
? prettyName(langStore.get(x.toUpperCase()))
: getKey(x);
};
return ( return (
<FormControl <FormControl
className={className} className={className}
@@ -73,7 +85,11 @@ export function InputList<T extends string | Object>({
> >
{options.map((t, i) => ( {options.map((t, i) => (
<MenuItem key={i} value={getKey(t)} className="input-list--menu-item"> <MenuItem key={i} value={getKey(t)} className="input-list--menu-item">
{prettyOptionLabels ? prettyName(getKey(t)) : getKey(t)} {prettyOptionLabels
? prettyName(getKey(t))
: getLabel
? getLabel(t)
: getKey(t)}
{!!getDescription && ( {!!getDescription && (
<> <>
<br /> <br />
@@ -1,24 +1,19 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import InputMultiSelect from "./InputMultiSelect"; import InputMultiSelect from "./InputMultiSelect";
export default { import { makeStory } from "devUtils";
title: "Inputs/InputMultiSelect",
component: InputMultiSelect,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof InputMultiSelect>;
const Template: ComponentStory<typeof InputMultiSelect> = (args) => { const { make, componentMeta } = makeStory({
const [value, setValue] = useState<number[]>(args.selected); Component: InputMultiSelect,
BaseTemplate: (args) => {
const [value, setValue] = useState<number[]>(args.selected);
useEffect(() => { useEffect(() => {
setValue(args.selected); setValue(args.selected);
}, [args.selected]); }, [args.selected]);
return ( return (
<Page>
<InputMultiSelect <InputMultiSelect
{...args} {...args}
onChange={(a) => { onChange={(a) => {
@@ -28,14 +23,18 @@ const Template: ComponentStory<typeof InputMultiSelect> = (args) => {
options={args.options} options={args.options}
selected={value} selected={value}
/> />
</Page> );
); },
}; meta: {
title: "Inputs/InputMultiSelect",
},
});
export const Simple = Template.bind({}); export default componentMeta;
Simple.args = {
export const Simple = make({
label: "Room Tags", label: "Room Tags",
options: ["Bears", "Cats", "Kitchen", "Bathroom"], options: ["Bears", "Cats", "Kitchen", "Bathroom"],
selected: [1], selected: [1],
max: 2, max: 2,
}; });
@@ -5,6 +5,7 @@ import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import Checkbox from "@mui/material/Checkbox"; import Checkbox from "@mui/material/Checkbox";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { useLang } from "lang";
export interface Props<T extends string> { export interface Props<T extends string> {
label: string; label: string;
@@ -23,6 +24,7 @@ export default function InputMultiSelect<T extends string>({
max = 3, max = 3,
}: Props<T>) { }: Props<T>) {
// alias // alias
const langStore = useLang();
const snackbr = useSnackbar(); const snackbr = useSnackbar();
return ( return (
<Autocomplete <Autocomplete
@@ -31,10 +33,13 @@ export default function InputMultiSelect<T extends string>({
value={selected.map((i) => options[i])} value={selected.map((i) => options[i])}
onChange={(_, newValues: T[] = []) => { onChange={(_, newValues: T[] = []) => {
if (newValues.length > max) { if (newValues.length > max) {
snackbr.enqueueSnackbar("Can only select up to 3 tags", { snackbr.enqueueSnackbar(
variant: "warning", langStore.get("VALIDATION_MAX_TAG_SELECTION", { count: "3" }),
autoHideDuration: 1500, {
}); variant: "warning",
autoHideDuration: 1500,
}
);
} }
onChange( onChange(
newValues newValues
@@ -1,58 +1,49 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react"; import { useState } from "react";
import InputTextBubble from "./InputTextBubble"; import InputTextBubble from "./InputTextBubble";
export default { import { makeStory } from "devUtils";
title: 'Inputs/InputTextBubble',
component: InputTextBubble,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {
label: {
defaultValue: 'Sample Title'
}
}
} as ComponentMeta<typeof InputTextBubble>;
const { make, componentMeta } = makeStory({
Component: InputTextBubble,
BaseTemplate: (args) => {
const [value, setValue] = useState<string | string[]>(args.value ?? "");
return (
<div style={{ maxWidth: "200px", overflow: "hidden" }}>
<InputTextBubble {...args} value={value} onChange={setValue} />
</div>
);
},
meta: {
title: "Inputs/InputTextBubble",
argTypes: {
label: {
defaultValue: "Sample Title",
},
},
},
});
export const ArrayText: ComponentStory<typeof InputTextBubble> = args => { export default componentMeta;
const [value, setValue] = useState<string | string[]>(['wow', 'lots of bubbles', 'itchen', 'bathroom']) export const ArrayText = make({
return <Page> value: ["wow", "lots of bubbles", "itchen", "bathroom"],
<div style={{ maxWidth: '200px', overflow: 'hidden' }}> });
<InputTextBubble {...args} value={value} onChange={setValue} /> export const JustText = make({
</div> value: "hello",
</Page> });
}
export const JustText: ComponentStory<typeof InputTextBubble> = args => { export const ManyOptions = make({
value: "hello",
const [value, setValue] = useState<string | string[]>('hello')
return <Page>
<InputTextBubble {...args} value={value} onChange={setValue} />
</Page>
}
export const ManyOptions: ComponentStory<typeof InputTextBubble> = args => {
const [value, setValue] = useState<string | string[]>('hello')
return <Page>
<InputTextBubble {...args} value={value} onChange={setValue} />
</Page>
}
ManyOptions.args = {
...ManyOptions.args,
options: [ options: [
'sensor.humidity_bathroom', "sensor.humidity_bathroom",
'sensor.humidity_bedroom', "sensor.humidity_bedroom",
'sensor.humidity_laundry', "sensor.humidity_laundry",
'sensor.temp_bathroom', "sensor.temp_bathroom",
'sensor.temp_bedroom', "sensor.temp_bedroom",
'switch.living_room', "switch.living_room",
'switch.bathroom', "switch.bathroom",
'light.bedroom_main', "light.bedroom_main",
'light.bedroom_second', "light.bedroom_second",
] ],
} });
@@ -4,17 +4,11 @@ import InputText from "./Base/InputText";
import { InputTextView } from "./InputTextView"; import { InputTextView } from "./InputTextView";
export default { import { makeStory } from "devUtils";
title: "Inputs/InputTextView",
component: InputTextView,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
value: "example",
},
} as ComponentMeta<typeof InputTextView>;
export const Basic: ComponentStory<typeof InputTextView> = (args) => ( const { make, componentMeta } = makeStory({
<Page> Component: InputTextView,
BaseTemplate: (args) => (
<div <div
style={{ style={{
display: "flex", display: "flex",
@@ -26,5 +20,15 @@ export const Basic: ComponentStory<typeof InputTextView> = (args) => (
<InputTextView {...args} /> <InputTextView {...args} />
<InputText {...args} /> <InputText {...args} />
</div> </div>
</Page> ),
); meta: {
title: "Inputs/InputTextView",
args: {
value: "example",
},
},
});
export default componentMeta;
export const Basic = make({});
+32 -17
View File
@@ -4,6 +4,8 @@ import { FC, PropsWithChildren, useState } from "react";
import CheckCircleOutlineOutlinedIcon from "@mui/icons-material/CheckCircleOutlineOutlined"; import CheckCircleOutlineOutlinedIcon from "@mui/icons-material/CheckCircleOutlineOutlined";
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined"; import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip";
import { useLang } from "lang";
export type InputTextViewProps = { export type InputTextViewProps = {
className?: string; className?: string;
@@ -12,11 +14,15 @@ export type InputTextViewProps = {
initialViewMode?: boolean; initialViewMode?: boolean;
placeholder?: string; placeholder?: string;
disabled?: boolean; disabled?: boolean;
borderless?: boolean;
titleSlug?: string;
titleParams?: Record<string, string>;
}; };
export const InputTextView: FC<PropsWithChildren<InputTextViewProps>> = ( export const InputTextView: FC<PropsWithChildren<InputTextViewProps>> = (
props props
) => { ) => {
const langStore = useLang();
const [viewMode, setViewMode] = useState(props.initialViewMode ?? true); const [viewMode, setViewMode] = useState(props.initialViewMode ?? true);
const [text, setText] = useState(props.value); const [text, setText] = useState(props.value);
const className = [ const className = [
@@ -27,24 +33,33 @@ export const InputTextView: FC<PropsWithChildren<InputTextViewProps>> = (
if (viewMode) { if (viewMode) {
return ( return (
<div <Tooltip
className={className} title={
onClick={() => !props.disabled && setViewMode(false)} props.titleSlug
? langStore.get(props.titleSlug, props.titleParams)
: ""
}
describeChild
> >
{!!props.value ? ( <div
<div className="input-text-view--text text-ellipsis"> className={className}
<span>{props.value}</span> onClick={() => !props.disabled && setViewMode(false)}
</div> >
) : ( {!!props.value ? (
<div className="input-text-view--text input-text-view--placeholder text-ellipsis"> <div className="input-text-view--text text-ellipsis">
<span>{props.placeholder}</span> <span>{props.value}</span>
</div> </div>
)} ) : (
{!props.disabled && ( <div className="input-text-view--text input-text-view--placeholder text-ellipsis">
<ModeEditOutlineOutlinedIcon className="input-text-view--edit" /> <span>{props.placeholder}</span>
)} </div>
{props.children} )}
</div> {!props.disabled && (
<ModeEditOutlineOutlinedIcon className="input-text-view--edit" />
)}
{props.children}
</div>
</Tooltip>
); );
} else { } else {
return ( return (
+3 -2
View File
@@ -9,14 +9,15 @@ export interface ModalStyleProps {
} }
export interface Props extends ModalStyleProps { export interface Props extends ModalStyleProps {
children: ReactNode; children: ReactNode;
className?: string;
} }
export const Modal: FC<Props> = ({ children, open }) => { export const Modal: FC<Props> = ({ children, open, className }) => {
const { isMobile } = useWindowSize(); const { isMobile } = useWindowSize();
return ( return (
<MuiModal open={open}> <MuiModal open={open}>
<div className={["modal--root", isMobile ? "mobile" : ""].join(" ")}> <div className={["modal--root", isMobile ? "mobile" : ""].join(" ")}>
<Card variant="outlined"> <Card variant="outlined">
<CardContent>{children}</CardContent> <CardContent className={className}>{children}</CardContent>
</Card> </Card>
</div> </div>
</MuiModal> </MuiModal>
@@ -13,6 +13,7 @@ import { getDescriptionFromAutomationNode } from "utils/formatting";
import { useHA } from "haService"; import { useHA } from "haService";
import { Generic } from "./Generic"; import { Generic } from "./Generic";
import { getNodeTypeAndValidate } from "utils/automations"; import { getNodeTypeAndValidate } from "utils/automations";
import { useLang } from "lang";
type UseState = <S>(s: S) => [S, Dispatch<SetStateAction<S>>]; type UseState = <S>(s: S) => [S, Dispatch<SetStateAction<S>>];
@@ -23,6 +24,7 @@ export const useEditorNodeState = (
uState: UseState = useState uState: UseState = useState
) => { ) => {
// state // state
const langStore = useLang();
const [allState, setAllState] = uState({ const [allState, setAllState] = uState({
yamlMode: false, yamlMode: false,
isModified: false, isModified: false,
@@ -77,7 +79,9 @@ export const useEditorNodeState = (
isErrored: allState.isErrored, isErrored: allState.isErrored,
get prettyNodeType() { get prettyNodeType() {
if (nodeType) { if (nodeType) {
return `${nodeType.slice(0, 1).toUpperCase()}${nodeType.slice(1)} Type`; return `${langStore.get(nodeType.toUpperCase())} ${langStore.get(
"TYPE"
)}`;
} else { } else {
return "n/a"; return "n/a";
} }
@@ -100,7 +104,7 @@ export const useEditorNodeState = (
aliasEditor = ( aliasEditor = (
<InputText <InputText
key="alias" key="alias"
label="Trigger ID" label={langStore.get("TRIGGER_ID")}
value={(allState.node as any).id} value={(allState.node as any).id}
onChange={(id) => onChange={(id) =>
setState({ setState({
@@ -115,7 +119,7 @@ export const useEditorNodeState = (
aliasEditor = ( aliasEditor = (
<InputText <InputText
key="alias" key="alias"
label="Alias" label={langStore.get("ALIAS")}
value={getDescriptionFromAutomationNode( value={getDescriptionFromAutomationNode(
allState.node, allState.node,
ha.namer, ha.namer,
@@ -2,11 +2,10 @@ import React from "react";
import { ComponentStory } from "@storybook/react"; import { ComponentStory } from "@storybook/react";
import { NodeEditor, NodeEditorProps } from "."; import { NodeEditor, NodeEditorProps } from ".";
import { AutomationCondition } from "types/automations/conditions";
import { Button } from "components/Inputs/Buttons/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { useState } from "react"; import { useState } from "react";
import { Modal } from "components/Modal"; import { Modal } from "components/Modal";
import { Page } from "components/Page"; import { MockPage } from "components/Page";
import { makeStory } from "devUtils"; import { makeStory } from "devUtils";
const { componentMeta, make } = makeStory({ const { componentMeta, make } = makeStory({
@@ -23,16 +22,14 @@ const { componentMeta, make } = makeStory({
Component: (props: NodeEditorProps) => { Component: (props: NodeEditorProps) => {
const [state, setState] = useState(props.node); const [state, setState] = useState(props.node);
return ( return (
<Page> <NodeEditor
<NodeEditor {...props}
{...props} node={state}
node={state} onSave={(s) => {
onSave={(s) => { setState(s);
setState(s); props.onSave && props.onSave(s);
props.onSave && props.onSave(s); }}
}} />
/>
</Page>
); );
}, },
}); });
@@ -77,12 +74,12 @@ export const DeviceTriggerExample = make({
export const InAModal: ComponentStory<typeof NodeEditor> = (props) => { export const InAModal: ComponentStory<typeof NodeEditor> = (props) => {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
return ( return (
<Page> <MockPage>
<Button onClick={() => setOpen(!open)}>Open Editor</Button> <Button onClick={() => setOpen(!open)}>Open Editor</Button>
<Modal open={open}> <Modal open={open}>
<NodeEditor {...props} onClose={() => setOpen(!open)} /> <NodeEditor {...props} onClose={() => setOpen(!open)} />
</Modal> </Modal>
</Page> </MockPage>
); );
}; };
+14 -10
View File
@@ -8,6 +8,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import InputBoolean from "components/Inputs/Base/InputBoolean"; import InputBoolean from "components/Inputs/Base/InputBoolean";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { getNodeSubTypeDescription } from "./utils"; import { getNodeSubTypeDescription } from "./utils";
import { useLang } from "lang";
export interface NodeEditorProps { export interface NodeEditorProps {
node: AutomationNode; node: AutomationNode;
@@ -29,6 +30,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
children, children,
}) => { }) => {
// state // state
const langStore = useLang();
const state = useEditorNodeState(node, allowedTypes, saveBtnCreateText); const state = useEditorNodeState(node, allowedTypes, saveBtnCreateText);
const confirm = useConfirm(); const confirm = useConfirm();
@@ -41,19 +43,19 @@ export const NodeEditor: FC<NodeEditorProps> = ({
) => { ) => {
const notes: string[] = []; const notes: string[] = [];
if (!isReady) { if (!isReady) {
notes.push("This node is missing some values"); notes.push(langStore.get("VALIDATION_MISSING_VALUES_FOR_NODE"));
} }
if (state.isErrored) { if (state.isErrored) {
notes.push("This node contains errors"); notes.push(langStore.get("VALIDATION_ERROR_VALUES_IN_NODE"));
} }
if (checkModified && isModified) { if (checkModified && isModified) {
notes.push("This node is has some unsaved work"); notes.push(langStore.get("VALIDATION_UNSAVED_WORK_IN_NODE"));
} }
if (notes.length > 0) { if (notes.length > 0) {
try { try {
await confirm({ await confirm({
confirmationText: "Yes", confirmationText: "Yes",
title: `Are you sure you want to ${what}?`, title: langStore.get("CONFIRM_EXIT", { what }),
description: ( description: (
<ul> <ul>
{notes.map((n, i) => ( {notes.map((n, i) => (
@@ -85,11 +87,11 @@ export const NodeEditor: FC<NodeEditorProps> = ({
<div className="node-editor--body-title"> <div className="node-editor--body-title">
{allowedTypes.length > 1 ? ( {allowedTypes.length > 1 ? (
<InputList <InputList
label="Type" label={langStore.get("TYPE")}
current={state.nodeType} current={state.nodeType}
options={allowedTypes} options={allowedTypes}
onChange={state.setNodeType} onChange={state.setNodeType}
prettyOptionLabels prettyOptionLabels={false}
/> />
) : ( ) : (
<></> <></>
@@ -101,7 +103,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
getDescription={getNodeSubTypeDescription} getDescription={getNodeSubTypeDescription}
options={state.subTypes} options={state.subTypes}
onChange={state.setSubType} onChange={state.setSubType}
prettyOptionLabels prettyOptionLabels={false}
/> />
) : ( ) : (
<></> <></>
@@ -115,7 +117,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
/> />
<InputBoolean <InputBoolean
className="enabled-flag" className="enabled-flag"
label="Enabled" label={langStore.get("ENABLED")}
value={state.data.enabled ?? true} value={state.data.enabled ?? true}
onChange={state.setEnabled} onChange={state.setEnabled}
/> />
@@ -140,9 +142,11 @@ export const NodeEditor: FC<NodeEditorProps> = ({
onClick={() => onClick={() =>
areYouSureNotReady("save").then((ok) => ok && onSave(state.data)) areYouSureNotReady("save").then((ok) => ok && onSave(state.data))
} }
title={!isReady ? "Some fields have not been properly filled up" : ""} title={
!isReady ? langStore.get("VALIDATION_NOT_ALL_FIELD_FILLED_IN") : ""
}
> >
{saveBtnCreateText ? "Create" : "Save"} {saveBtnCreateText ? langStore.get("CREATE") : langStore.get("SAVE")}
</Button> </Button>
{children} {children}
</div> </div>
+7
View File
@@ -7,6 +7,8 @@
overflow: hidden; overflow: hidden;
max-width: 100vw; max-width: 100vw;
max-height: 100vh; max-height: 100vh;
min-width: 100vw;
min-height: 100vh;
/* font */ /* font */
font-size: 16px; font-size: 16px;
@@ -15,4 +17,9 @@
/* background */ /* background */
background-color: var(--mui-background-default); background-color: var(--mui-background-default);
}
.page>.page-contents {
flex: 1;
overflow: hidden;
} }
+28 -17
View File
@@ -1,5 +1,5 @@
import "./index.css"; import "./index.css";
import { createRef, FC, ReactNode, useEffect, useRef } from "react"; import { createRef, FC, PropsWithChildren, useEffect, useRef } from "react";
import { import {
createTheme, createTheme,
Palette, Palette,
@@ -7,23 +7,21 @@ import {
ThemeProvider, ThemeProvider,
useTheme, useTheme,
} from "@mui/material/styles"; } from "@mui/material/styles";
import { VersionBox } from "components/VersionBox"; import { BottomBar } from "components/BottomBar";
import { SnackbarKey, SnackbarProvider, useSnackbar } from "notistack"; import { SnackbarKey, SnackbarProvider, useSnackbar } from "notistack";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import { useHAConnection } from "haService/connection"; import { useHAConnection } from "haService/connection";
import { ConfirmProvider } from "material-ui-confirm"; import { ConfirmProvider } from "material-ui-confirm";
import { Color } from "@mui/material"; import { Color } from "@mui/material";
import useWindowSize from "utils/useWindowSize"; import useWindowSize from "utils/useWindowSize";
import { ApiService } from "apiService/core";
import { ApiStateProvider, useMockApiService } from "apiService";
const theme = createTheme({ export type PageProps = PropsWithChildren<{
palette: { api: ApiService;
mode: "dark", }>;
},
});
export const InternalPage: FC<{ export const InternalPage: FC<PageProps> = ({ children, api }) => {
children: ReactNode;
}> = ({ children }) => {
const conn = useHAConnection(); const conn = useHAConnection();
const theme = useTheme(); const theme = useTheme();
const snackbar = useSnackbar(); const snackbar = useSnackbar();
@@ -62,25 +60,31 @@ export const InternalPage: FC<{
}, [conn, snackbar]); }, [conn, snackbar]);
return ( return (
<main className={["page", isMobile ? "mobile" : ""].join(" ")}> <main
className={["page", "center column", isMobile ? "mobile" : ""].join(" ")}
>
<div className="page-contents column">{children}</div>
<BottomBar api={api} />
<style> <style>
{`:root { {`:root {
${convertPaletteToCss(theme.palette)} ${convertPaletteToCss(theme.palette)}
}`} }`}
</style> </style>
<VersionBox />
{children}
</main> </main>
); );
}; };
export const Page: FC<{ export const Page: FC<PageProps> = (props) => {
children: ReactNode;
}> = ({ children }) => {
const notistackRef = createRef<any>(); const notistackRef = createRef<any>();
const onClickDismiss = (key: SnackbarKey) => () => { const onClickDismiss = (key: SnackbarKey) => () => {
notistackRef.current.closeSnackbar(key); notistackRef.current.closeSnackbar(key);
}; };
const theme = createTheme({
palette: {
mode: props.api.state.theme,
},
});
return ( return (
<ThemeProvider theme={theme}> <ThemeProvider theme={theme}>
<ConfirmProvider> <ConfirmProvider>
@@ -96,13 +100,20 @@ export const Page: FC<{
dense dense
preventDuplicate preventDuplicate
> >
<InternalPage>{children}</InternalPage> <ApiStateProvider value={props.api.state}>
<InternalPage {...props} />
</ApiStateProvider>
</SnackbarProvider> </SnackbarProvider>
</ConfirmProvider> </ConfirmProvider>
</ThemeProvider> </ThemeProvider>
); );
}; };
export const MockPage: FC<PropsWithChildren<{}>> = (props) => {
const api = useMockApiService([]);
return <Page api={api} {...props} />;
};
export const convertPaletteToCss = (p: Palette): string => { export const convertPaletteToCss = (p: Palette): string => {
let out = ``; let out = ``;
for (const k of [ for (const k of [
@@ -1,21 +1,15 @@
import React, { FC, useEffect, useState } from "react"; import React, { useState } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { ServiceEditor } from "."; import { ServiceEditor } from ".";
import { TypedHassService } from "haService/fieldTypes"; import { TypedHassService } from "haService/fieldTypes";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
export default { import { makeStory } from "devUtils";
title: "Services/ServiceEditor",
component: ServiceEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof ServiceEditor>;
const Template: ComponentStory<typeof ServiceEditor> = (props) => { const { make, componentMeta } = makeStory({
const [state, setState] = useState(props.data); Component: ServiceEditor,
return ( BaseTemplate: (props) => {
<Page> const [state, setState] = useState(props.data);
return (
<div <div
style={{ style={{
maxHeight: "99vh", maxHeight: "99vh",
@@ -63,22 +57,24 @@ const Template: ComponentStory<typeof ServiceEditor> = (props) => {
/> />
</div> </div>
</div> </div>
</Page> );
); },
}; meta: {
title: "Services/ServiceEditor",
},
});
const makeExample = (service: TypedHassService) => { export default componentMeta;
const Eg = Template.bind({}); export const Example = make({});
Eg.args = {
...Eg, const makeExample = (service: TypedHassService) =>
make({
service, service,
data: { data: {
target: {}, target: {},
field: {}, field: {},
}, },
}; });
return Eg;
};
export const NumberSetValue = makeExample({ export const NumberSetValue = makeExample({
name: "Set", name: "Set",
@@ -6,26 +6,27 @@ import SettingsApplicationsIcon from "@mui/icons-material/SettingsApplications";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { DeleteForeverOutlined } from "@mui/icons-material"; import { DeleteForeverOutlined } from "@mui/icons-material";
import EditIcon from "@mui/icons-material/Edit"; import EditIcon from "@mui/icons-material/Edit";
import { makeStory } from "devUtils";
export default { const { make, componentMeta } = makeStory({
title: "Nav/SpeedDial", Component: SpeedDial,
component: SpeedDial, BaseTemplate: () => (
}; <div
style={{
maxWidth: "10em",
maxHeight: "10em",
}}
>
<SpeedDial icon={<SettingsApplicationsIcon />}>
<ButtonIcon icon={<DeleteForeverOutlined />} />
<ButtonIcon icon={<EditIcon />} />
</SpeedDial>
</div>
),
meta: {
title: "Nav/SpeedDial",
},
});
export const IconList: ComponentStory<typeof SpeedDial> = () => { export default componentMeta;
return ( export const IconList = make({});
<Page>
<div
style={{
maxWidth: "10em",
maxHeight: "10em",
}}
>
<SpeedDial icon={<SettingsApplicationsIcon />}>
<ButtonIcon icon={<DeleteForeverOutlined />} />
<ButtonIcon icon={<EditIcon />} />
</SpeedDial>
</div>
</Page>
);
};
@@ -1,21 +0,0 @@
.version-box {
position: absolute;
bottom: -0.5em;
right: 0;
font-size: 0.5em;
}
.version-box #circle {
color: var(--mui-primary-main);
height: 1em;
width: 1em;
}
.version-box #circle.error {
color: var(--mui-error-main);
}
.version-box #circle.loaded {
color: var(--mui-success-light);
}
@@ -1,17 +0,0 @@
import "./index.css";
import { FC } from "react";
import { useHAConnection } from "haService/connection";
export const VersionBox: FC = () => {
const ha = useHAConnection();
const version = process.env.REACT_APP_BUILD_VERSION ?? "n/a";
return (
<div className="version-box">
version: {version} / HA Connection{" "}
<span id="circle" className={ha.status}>
🟢
</span>
</div>
);
};
+12 -1
View File
@@ -2,6 +2,8 @@ import "styles/root.css";
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { Page } from "components/Page";
import { ComponentProps, JSXElementConstructor } from "react"; import { ComponentProps, JSXElementConstructor } from "react";
import { ApiService } from "apiService/core";
import { useConnectedApiService, useMockApiService } from "apiService";
export type MakeStoryArgs< export type MakeStoryArgs<
T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any> T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>
@@ -9,6 +11,7 @@ export type MakeStoryArgs<
Component: T; Component: T;
BaseTemplate?: ComponentStory<T>; BaseTemplate?: ComponentStory<T>;
meta: Partial<ComponentMeta<T>> & { title: string }; meta: Partial<ComponentMeta<T>> & { title: string };
useLiveApi?: boolean;
}; };
export const makeStory = < export const makeStory = <
T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any> T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>
@@ -16,6 +19,7 @@ export const makeStory = <
BaseTemplate, BaseTemplate,
Component, Component,
meta, meta,
useLiveApi = false,
}: MakeStoryArgs<T>) => { }: MakeStoryArgs<T>) => {
const componentMeta: ComponentMeta<T> = { const componentMeta: ComponentMeta<T> = {
component: Component as any, component: Component as any,
@@ -24,8 +28,15 @@ export const makeStory = <
...meta, ...meta,
}; };
const Template: ComponentStory<T> = (args) => { const Template: ComponentStory<T> = (args) => {
let api: ApiService;
if (useLiveApi) {
api = useConnectedApiService();
} else {
api = useMockApiService([]);
}
return ( return (
<Page> <Page api={api}>
{BaseTemplate ? <BaseTemplate {...args} /> : <Component {...args} />} {BaseTemplate ? <BaseTemplate {...args} /> : <Component {...args} />}
</Page> </Page>
); );
+10 -13
View File
@@ -78,17 +78,14 @@ const Test: FC = () => {
); );
}; };
export default { import { makeStory } from "devUtils";
title: "Services/HA Service",
component: Test,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof Test>;
export const AutomationCall: ComponentStory<typeof Test> = (props) => { const { make, componentMeta } = makeStory({
return ( Component: Test,
<Page> meta: {
<Test {...props} /> title: "Services/HA Service",
</Page> },
); });
};
export default componentMeta;
export const AutomationCall = make({});
+9 -15
View File
@@ -1,8 +1,7 @@
import React, { FC } from "react"; import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useHADeviceRegistry } from "haService"; import { useHADeviceRegistry } from "haService";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { makeStory } from "devUtils";
const Test: FC<{ onRender: () => void }> = ({ onRender }) => { const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
const conn = useHADeviceRegistry(); const conn = useHADeviceRegistry();
@@ -35,17 +34,12 @@ const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
return <code>Loading...</code>; return <code>Loading...</code>;
}; };
export default { const { make, componentMeta } = makeStory({
title: "Services/Device Registry", Component: Test,
component: Test, meta: {
parameters: { actions: { argTypesRegex: "^on.*" } }, title: "Services/Device Registry",
args: {}, },
} as ComponentMeta<typeof Test>; });
export const Base: ComponentStory<typeof Test> = (props) => { export default componentMeta;
return ( export const Basic = make({});
<Page>
<Test {...props} />
</Page>
);
};
+3 -3
View File
@@ -1,6 +1,6 @@
import React, { FC, useState } from "react"; import React, { FC, useState } 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 { useHAEntities } from "haService/HAEntities"; import { useHAEntities } from "haService/HAEntities";
const Test: FC<{ onRender: () => void }> = ({ onRender }) => { const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
@@ -50,8 +50,8 @@ export default {
export const Base: ComponentStory<typeof Test> = (props) => { export const Base: ComponentStory<typeof Test> = (props) => {
return ( return (
<Page> <MockPage>
<Test {...props} /> <Test {...props} />
</Page> </MockPage>
); );
}; };
+3 -3
View File
@@ -1,6 +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 { useHAEntityRegistry } from "haService"; import { useHAEntityRegistry } from "haService";
const Test: FC<{ onRender: () => void }> = ({ onRender }) => { const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
@@ -43,8 +43,8 @@ export default {
export const Base: ComponentStory<typeof Test> = (props) => { export const Base: ComponentStory<typeof Test> = (props) => {
return ( return (
<Page> <MockPage>
<Test {...props} /> <Test {...props} />
</Page> </MockPage>
); );
}; };
+23 -7
View File
@@ -12,6 +12,7 @@ import { TypedHassService } from "./fieldTypes";
import { Option } from "components/Inputs/AutoComplete/InputAutoComplete"; import { Option } from "components/Inputs/AutoComplete/InputAutoComplete";
import { getDeviceExtraWsCalls } from "./extras"; import { getDeviceExtraWsCalls } from "./extras";
import { useHAEntities } from "./HAEntities"; import { useHAEntities } from "./HAEntities";
import { useLang } from "lang";
export type ServiceOption = Option<{ export type ServiceOption = Option<{
domain: string; domain: string;
@@ -137,6 +138,7 @@ export const useHAEntityRegistry = () => {
export type HAService = ReturnType<typeof useHA>; export type HAService = ReturnType<typeof useHA>;
export const useHA = () => { export const useHA = () => {
const langStore = useLang();
const entities = useHAEntities(); const entities = useHAEntities();
const devices = useHADeviceRegistry(); const devices = useHADeviceRegistry();
const services = useHAServices(); const services = useHAServices();
@@ -158,9 +160,14 @@ export const useHA = () => {
target, target,
service_data: data, service_data: data,
}); });
snackbr.enqueueSnackbar(`Successfully called ${domain}.${service}`, { snackbr.enqueueSnackbar(
variant: "success", langStore.get("INFO_SUCCESS_CALL", {
}); entityId: `${domain}.${service}`,
}),
{
variant: "success",
}
);
return result; return result;
} catch (err: any) { } catch (err: any) {
let msg = JSON.stringify(err); let msg = JSON.stringify(err);
@@ -168,7 +175,10 @@ export const useHA = () => {
msg = err.message; msg = err.message;
} }
snackbr.enqueueSnackbar( snackbr.enqueueSnackbar(
`Failed to call ${domain}.${service} because '${msg}'`, langStore.get("ERROR_FAILED_CALLING", {
entityId: `${domain}.${service}`,
msg,
}),
{ {
variant: "error", variant: "error",
} }
@@ -178,14 +188,20 @@ export const useHA = () => {
} }
if (conn.status === "error") { if (conn.status === "error") {
snackbr.enqueueSnackbar( snackbr.enqueueSnackbar(
`Failed to call service because connection is '${conn.status}' -- ${conn.error}`, langStore.get("ERROR_FAILED_CALLING_BC_CONNECTION", {
connStatus: conn.status,
connError: conn.error,
}),
{ {
variant: "error", variant: "error",
} }
); );
} else { } else {
snackbr.enqueueSnackbar( snackbr.enqueueSnackbar(
`Failed to call service because connection is '${conn.status}'`, langStore.get("ERROR_FAILED_CALLING_BC_CONNECTION", {
connStatus: conn.status,
connError: "",
}),
{ {
variant: "error", variant: "error",
} }
@@ -210,7 +226,7 @@ export const useHA = () => {
.map(entities.getLabel) .map(entities.getLabel)
.join(", "); .join(", ");
if (entity_id.length > maxEntities) { if (entity_id.length > maxEntities) {
return out + " and more"; return out + " " + langStore.get("AND_MORE");
} }
return out; return out;
} }
+3 -3
View File
@@ -1,6 +1,6 @@
import React, { FC, useEffect, useState } from "react"; import React, { FC, useEffect, useState } 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 { useHA } from "haService"; import { useHA } from "haService";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
@@ -89,8 +89,8 @@ export default {
export const ServiceCall: ComponentStory<typeof Test> = (props) => { export const ServiceCall: ComponentStory<typeof Test> = (props) => {
return ( return (
<Page> <MockPage>
<Test {...props} /> <Test {...props} />
</Page> </MockPage>
); );
}; };
+5 -11
View File
@@ -1,24 +1,18 @@
import React from "react"; import React from "react";
import ReactDOM from "react-dom";
import "./styles/root.css"; import "./styles/root.css";
import App from "./App"; import App from "./App";
import reportWebVitals from "./reportWebVitals"; import reportWebVitals from "./reportWebVitals";
ReactDOM.render( import { createRoot } from "react-dom/client";
const container = document.getElementById("root");
const root = createRoot(container!);
root.render(
<React.StrictMode> <React.StrictMode>
<App /> <App />
</React.StrictMode>, </React.StrictMode>
document.getElementById("root")
); );
// If you want to start measuring performance in your app, pass a function // If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.info)) // to log results (for example: reportWebVitals(console.info))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(console.info); reportWebVitals(console.info);
// import { createRoot } from 'react-dom/client';
// const container = document.getElementById('root');
// const root = createRoot(container!);
// root.render(<React.StrictMode>
// <App />
// </React.StrictMode>);
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more