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:
branches:
- main
concurrency:
group: build-${{ github.event.inputs.version || github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
metadata:
runs-on: ubuntu-latest
@@ -15,12 +18,6 @@ jobs:
outputs:
version: ${{ steps.version.outputs.VERSION }}
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.10.0
with:
all_but_latest: true
access_token: ${{ github.token }}
- name: Check out repository
uses: actions/checkout@v3
with:
@@ -76,12 +73,14 @@ jobs:
needs:
- metadata
- build-web
permissions:
packages: write
strategy:
matrix:
arch:
- "aarch64"
- "amd64"
- "armhf" # see https://github.com/asosnovsky/Shortumation/issues/147
- "armhf"
- "armv7"
- "i386"
@@ -89,6 +88,9 @@ jobs:
- name: Check out repository
uses: actions/checkout@v3
# - name: Login to Github Container Registry
# run: echo ${{ github.token }} | docker login ghcr.io -u ${{ github.repository_owner }} --password-stdin
- name: Login to DockerHub
uses: docker/login-action@v2.0.0
with:
@@ -103,7 +105,6 @@ jobs:
- name: ${{ matrix.arch }} / ${{ needs.metadata.outputs.version }}
uses: home-assistant/builder@master
continue-on-error: true
with:
args: |
--${{ matrix.arch }} \
+34 -31
View File
@@ -13,12 +13,16 @@ name: "CodeQL"
on:
push:
branches: [ "main" ]
branches: ["main"]
pull_request:
# The branches below must be a subset of the branches above
branches: [ "main" ]
branches: ["main"]
schedule:
- cron: '26 21 * * 2'
- cron: "26 21 * * 2"
concurrency:
group: codeql-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
analyze:
@@ -32,41 +36,40 @@ jobs:
strategy:
fail-fast: false
matrix:
language: [ 'javascript', 'python' ]
language: ["javascript", "python"]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Checkout repository
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
+7 -3
View File
@@ -4,17 +4,21 @@
#
# Source repository: https://github.com/actions/dependency-review-action
# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement
name: 'Dependency Review'
name: "Dependency Review"
on: [pull_request]
permissions:
contents: read
concurrency:
group: deprev-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
dependency-review:
runs-on: ubuntu-latest
steps:
- name: 'Checkout Repository'
- name: "Checkout Repository"
uses: actions/checkout@v3
- name: 'Dependency Review'
- name: "Dependency Review"
uses: actions/dependency-review-action@v2
+3
View File
@@ -6,6 +6,9 @@ on:
pull_request:
branches:
- main
concurrency:
group: test-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
metadata:
runs-on: ubuntu-latest
+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)
## [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
- Attempting to increasing websocket file limit
+2 -1
View File
@@ -2,7 +2,7 @@
ARG BUILD_ARCH
# <--- Main Image -->
FROM python:3.10-slim-buster
FROM python:3.10-slim-bullseye
WORKDIR /app
# <--- Post-Build Args -->
@@ -10,6 +10,7 @@ ARG BUILD_VERSION
# <--- Environment Variables -->
ENV BUILD_VERSION $BUILD_VERSION
ENV BUILD_ARCH $BUILD_ARCH
# <--- System Wide Dependencies -->
ENV LANG C.UTF-8
+25 -15
View File
@@ -1,20 +1,30 @@
get_index # unused function (src/api/app.py:43)
list_autos # unused function (src/api/routes/automations.py:13)
insert_auto # unused function (src/api/routes/automations.py:28)
update_auto # unused function (src/api/routes/automations.py:32)
delete_auto # unused function (src/api/routes/automations.py:40)
read_details # unused function (src/api/routes/details.py:11)
get_index # unused function (src/api/app.py:41)
list_autos # unused function (src/api/routes/automations.py:14)
insert_auto # unused function (src/api/routes/automations.py:30)
update_auto # unused function (src/api/routes/automations.py:35)
delete_auto # unused function (src/api/routes/automations.py:45)
read_details # unused function (src/api/routes/details.py:12)
read_profile # unused function (src/api/routes/details.py:24)
save_profile # unused function (src/api/routes/details.py:28)
read_ping # unused function (src/api/routes/ping.py:10)
websocket_endpoint # unused function (src/api/routes/socket.py:13)
params # unused variable (src/api/types.py:16)
total_items # unused variable (src/api/types.py:17)
data # unused variable (src/api/types.py:18)
trigger_variables # unused variable (src/automations/types.py:13)
trigger # unused variable (src/automations/types.py:15)
condition # unused variable (src/automations/types.py:16)
action # unused variable (src/automations/types.py:17)
_.to_json # unused method (src/automations/types.py:45)
_.automation_tags # unused property (src/hass_config/loader.py:17)
alias # unused variable (src/automations/types.py:36)
description # unused variable (src/automations/types.py:37)
trigger_variables # unused variable (src/automations/types.py:38)
mode # unused variable (src/automations/types.py:39)
trigger # unused variable (src/automations/types.py:40)
condition # unused variable (src/automations/types.py:41)
action # unused variable (src/automations/types.py:42)
_.to_json # unused method (src/automations/types.py:70)
error_name # unused variable (src/errors.py:22)
error_message # unused variable (src/errors.py:23)
error_traceback # unused variable (src/errors.py:24)
original_error # unused variable (src/errors.py:25)
_.automation_tags # unused property (src/hass_config/loader.py:28)
json_dumps # unused function (src/json_serializer.py:5)
SecretValue # unused class (src/yaml_serializer/__init__.py:40)
EnvVar # unused class (src/yaml_serializer/__init__.py:78)
theme # unused variable (src/user_profile.py:10)
lang # unused variable (src/user_profile.py:11)
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.staticfiles import StaticFiles
from src.automations.manager import AutomationManager
from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER
from src.hass_config.loader import HassConfig
from .routes import automations, details, ping, socket
def make_app(automation_mgr: AutomationManager) -> FastAPI:
def make_app(hass_config: HassConfig) -> FastAPI:
app = FastAPI()
has_web_folder = (ROOT_FOLDER / "web").exists()
if has_web_folder:
@@ -33,11 +33,9 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
)
app.include_router(ping.router, prefix="/ping")
app.include_router(
automations.make_automation_router(automation_mgr), prefix=f"{API_PREFIX}/automations"
)
app.include_router(
details.make_details_router(automation_mgr.hass_config), prefix=f"{API_PREFIX}/details"
automations.make_automation_router(hass_config), prefix=f"{API_PREFIX}/automations"
)
app.include_router(details.make_details_router(hass_config), prefix=f"{API_PREFIX}/details")
app.include_router(socket.router, prefix=f"{API_PREFIX}/socket")
@app.get("/")
+7 -1
View File
@@ -5,13 +5,15 @@ from src.automations.errors import FailedDeletion
from src.automations.manager import AutomationManager
from src.automations.types import Automation, ExtenededAutomation
from src.errors import ErrorSet
from src.hass_config.loader import HassConfig
def make_automation_router(automations: AutomationManager) -> APIRouter:
def make_automation_router(hass_config: HassConfig) -> APIRouter:
router = APIRouter()
@router.post("/list")
def list_autos(body: ListParams) -> ListData[ExtenededAutomation]:
automations = AutomationManager(hass_config)
try:
automations.reload()
return ListData(
@@ -27,18 +29,22 @@ def make_automation_router(automations: AutomationManager) -> APIRouter:
@router.post("/item")
def insert_auto(body: Automation):
automations = AutomationManager(hass_config)
automations.create(body)
@router.put("/item")
def update_auto(body: ExtenededAutomation):
automations = AutomationManager(hass_config)
automations.update(body)
@router.post("/item/tags")
def update_tags(body: UpdateTags):
automations = AutomationManager(hass_config)
automations.update_tags(body.automation_id, body.tags)
@router.delete("/item")
def delete_auto(body: ExtenededAutomation):
automations = AutomationManager(hass_config)
try:
automations.delete(body)
except FailedDeletion as err:
+12 -4
View File
@@ -3,6 +3,7 @@ from fastapi import APIRouter
from src.automations.loader import extract_automation_refs
from src.env import BUILD_VERSION, HASSIO_TOKEN, HASSIO_WS
from src.hass_config import HassConfig
from src.user_profile import UserProfile
def make_details_router(hass_config: HassConfig) -> APIRouter:
@@ -16,10 +17,17 @@ def make_details_router(hass_config: HassConfig) -> APIRouter:
"hassio_url": HASSIO_WS,
"config": hass_config.get_configuration_path(),
"tags": hass_config.get_automation_tags_path(),
"autos": {
config_key: auto_file
for config_key, auto_file in extract_automation_refs(hass_config)
},
"profile": hass_config.get_profile_path(),
"autos": list(map(repr, extract_automation_refs(hass_config))),
}
@router.get("/profile")
def read_profile():
return UserProfile.from_hass_config(hass_config)
@router.put("/profile")
def save_profile(user_profile: UserProfile):
user_profile.save(hass_config)
return {"saved": hass_config.get_profile_path()}
return router
+1 -2
View File
@@ -1,6 +1,5 @@
from src.api.app import make_app
from src.automations.manager import AutomationManager
from src.hass_config import find_hass_config
hass_config = find_hass_config()
app = make_app(AutomationManager(hass_config))
app = make_app(hass_config)
+22 -110
View File
@@ -1,129 +1,41 @@
import base64
import json
import sqlite3
from contextlib import contextmanager
from pathlib import Path
from typing import Iterable, Iterator
from typing import Iterable
from src.logger import get_logger
from .errors import (
DBDataError,
DBError,
DBNoAutomationFound,
RepeatedAutomationId,
)
from .errors import DBNoAutomationFound, RepeatedAutomationId
from .types import ExtenededAutomation
logger = get_logger(__file__)
automations_tbl = "autos"
def encode_auto(auto: ExtenededAutomation) -> str:
return base64.b64encode(
json.dumps(auto.to_primitive(include_tags=True)).encode("utf-8")
).decode("utf-8")
def encode_obj(auto: dict | list) -> str:
return base64.b64encode(json.dumps(auto).encode("utf-8")).decode("utf-8")
def decode_auto(
auto_str: str, source_file: str, source_file_type: str, configuration_key: str
) -> ExtenededAutomation:
return ExtenededAutomation(
source_file=source_file,
source_file_type=source_file_type,
configuration_key=decode_obj(configuration_key), # type: ignore
**decode_obj(auto_str),
)
def decode_obj(obj_str: str) -> dict | list:
return json.loads(base64.b64decode(obj_str.encode("utf-8")).decode("utf-8"))
class AutomationDBConnection:
def __init__(self, db_file: Path) -> None:
self.db_file = db_file
def __init__(self) -> None:
self.db: dict[str, ExtenededAutomation] = {}
def reset(self):
self.db_file.unlink(missing_ok=True)
self.create_db()
@contextmanager
def get_cur(self) -> Iterator[sqlite3.Cursor]:
conn = sqlite3.connect(self.db_file)
cur = conn.cursor()
try:
yield cur
conn.commit()
except sqlite3.DatabaseError as err:
raise DBError(*err.args) from err
finally:
cur.close()
conn.close()
def create_db(self):
with self.get_cur() as cur:
cur.execute(
f"""
CREATE TABLE IF NOT EXISTS {automations_tbl} (
id TEXT NOT NULL PRIMARY KEY,
alias TEXT,
description TEXT,
mode TEXT NOT NULL,
source_file TEXT NOT NULL,
source_file_type TEXT NOT NULL,
configuration_key BLOB NOT NULL,
rest BLOB NOT NULL
);
"""
)
self.db = {}
def insert_automations(self, automations: list[ExtenededAutomation]):
with self.get_cur() as cur:
for automation in automations:
try:
cur.execute(
f"""
INSERT INTO {automations_tbl} VALUES (
"{automation.id}",
"{automation.alias}",
"{automation.description}",
"{automation.mode}",
"{automation.source_file}",
"{automation.source_file_type}",
"{encode_obj(automation.configuration_key)}",
"{encode_auto(automation)}"
);
""",
)
except sqlite3.IntegrityError as err:
raise RepeatedAutomationId(
f"automation id '{automation.id}' in '{automation.source_file}' was already seen before. Please check for duplicate automation ids in your files."
) from err
repeated_automations = []
for automation in automations:
if self.db.get(automation.id, None) is None:
self.db[automation.id] = automation
else:
repeated_automations.append(
f"automation id '{automation.id}' in '{automation.source_file}' was already seen before. Please check for duplicate automation ids in your files."
)
if len(repeated_automations) > 0:
raise RepeatedAutomationId(repeated_automations)
def get_automation(self, automation_id: str) -> ExtenededAutomation:
with self.get_cur() as cur:
cur.execute(
f'SELECT rest, source_file, source_file_type, configuration_key FROM {automations_tbl} WHERE id = "{automation_id}"' # nosec
)
objs = cur.fetchone()
if objs is None:
raise DBNoAutomationFound(automation_id)
[rest, source_file, source_file_type, configuration_key] = objs
return decode_auto(rest, source_file, source_file_type, configuration_key)
if a := self.db.get(automation_id, None):
return a
raise DBNoAutomationFound(automation_id)
def list_automations(self, offset: int, limit: int) -> Iterable[ExtenededAutomation]:
with self.get_cur() as cur:
for [rest, source_file, source_file_type, configuration_key] in cur.execute(
f"SELECT rest, source_file, source_file_type, configuration_key FROM {automations_tbl} LIMIT {limit} OFFSET {offset}" # nosec
):
yield decode_auto(rest, source_file, source_file_type, configuration_key)
for i, auto in enumerate(self.db.values()):
if i >= offset and i < limit + offset:
yield auto
def count_automations(self) -> int:
with self.get_cur() as cur:
return cur.execute(f"SELECT count(id) FROM {automations_tbl}").fetchone()[0] # nosec
return len(self.db)
+4 -13
View File
@@ -1,8 +1,6 @@
from pathlib import Path
from tempfile import mktemp
from typing import Optional, Union
from src.errors import ErrorSet
from src.errors import ErrorSet, FormattedError
from src.hass_config.loader import HassConfig
from src.logger import get_logger
from src.yaml_serializer import dump_yaml, load_yaml
@@ -13,11 +11,7 @@ from .errors import (
DBError,
InvalidAutomationFile,
)
from .loader import (
get_base_automation_key,
load_and_iter_automations,
load_automation_path,
)
from .loader import get_base_automation_key, load_and_iter_automations
from .tags import TagManager
from .types import Automation, ExtenededAutomation
@@ -28,12 +22,9 @@ class AutomationManager:
def __init__(
self,
hass_config: HassConfig,
db_path: Optional[Path] = None,
) -> None:
if db_path is None:
db_path = Path(mktemp()) # nosec
self.hass_config = hass_config
self.db = AutomationDBConnection(db_path)
self.db = AutomationDBConnection()
self.tag_path = hass_config.get_automation_tags_path()
self.tag_manager = TagManager()
self.reload_tags()
@@ -66,7 +57,7 @@ class AutomationManager:
if len(batch) >= 0:
self.db.insert_automations(batch)
except DBError as e:
logger.warning(e)
logger.warning(FormattedError.from_error(e))
errors.append(e)
if len(errors) > 0:
raise ErrorSet(*errors)
+6
View File
@@ -15,11 +15,17 @@ class InlineAutomation(NamedTuple):
source_file: Path
automations: list[dict]
def __repr__(self) -> str:
return f"InlineAutomation(configuration_key='{self.configuration_key}', source_file='{self.source_file}')"
class IncludedAutoamtion(NamedTuple):
configuration_key: ConfigurationKey
ref: IncludedYamlDir
def __repr__(self) -> str:
return f"InlineAutomation(configuration_key='{self.configuration_key}', ref='{self.ref}')"
ExtractedAutomation = InlineAutomation | IncludedAutoamtion
AutomationExtractedIter = Iterator[ExtractedAutomation]
+23 -1
View File
@@ -1,3 +1,7 @@
import traceback
from typing import NamedTuple
class ErrorSet(Exception):
"""An exception collection exception"""
@@ -7,6 +11,24 @@ class ErrorSet(Exception):
def gen_message(self):
if len(self.errors) > 1:
return "Encountered multiple errors:\n >" + "\n >".join(map(repr, self.errors))
return "Encountered multiple errors:\n >" + "\n >".join(
map(FormattedError.from_error, self.errors)
)
else:
return str(self.errors[0].args)
class FormattedError(NamedTuple):
error_name: str
error_message: str
error_traceback: str
original_error: Exception
@classmethod
def from_error(cls, err: Exception):
return cls(
error_name=str(err.__class__.__name__),
error_message=str(err.args),
error_traceback="\n\n".join(traceback.format_tb(err.__traceback__)),
original_error=err,
)
+3
View File
@@ -60,5 +60,8 @@ class HassConfig:
def get_automation_tags_path(self) -> Path:
return self.get_shortumations_path() / "tags.yaml"
def get_profile_path(self) -> Path:
return self.get_shortumations_path() / "profile.yaml"
def get_configuration_path(self) -> Path:
return self.root_path / "configuration.yaml"
+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
from fastapi.testclient import TestClient
from src.api.app import make_app
from src.automations.types import Automation, ExtenededAutomation
from tests.utils import (
HA_CONFIG2_EXAMPLE,
HA_CONFIG6_EXAMPLE,
HA_CONFIG10_EXAMPLE,
get_example_automation_loader,
)
class BaseTestCase(TestCase):
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader()
self.client = TestClient(make_app(self.automation_loader))
from .util import BaseTestCase
class automation_pagination_tests(BaseTestCase):
@@ -90,20 +76,13 @@ class automation_pagination_tests(BaseTestCase):
class automation_pagination_tests_2(automation_pagination_tests):
source_config_path = HA_CONFIG2_EXAMPLE
test_params = {
"total": 1,
"subtest2_found_items": 0,
"subtest1_found_items": 1,
}
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG2_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_update_tests(BaseTestCase):
test_params = {
@@ -350,6 +329,7 @@ class automation_update_tests(BaseTestCase):
class automation_update_split_config_tests(automation_update_tests):
source_config_path = HA_CONFIG6_EXAMPLE
test_params = {
"total": 12,
"modify_item": 3,
@@ -378,30 +358,15 @@ class automation_update_split_config_tests(automation_update_tests):
},
}
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG6_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_update_split_config_and_inline_config_tests(automation_update_tests):
source_config_path = HA_CONFIG10_EXAMPLE
test_params = {
"total": 4,
"modify_item": 0,
"consitency_tests": {},
}
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(HA_CONFIG10_EXAMPLE)
self.client = TestClient(make_app(self.automation_loader))
class automation_delete_tests(BaseTestCase):
def test_delete_some(self):
+27
View File
@@ -0,0 +1,27 @@
from tests.unittests.api.util import BaseTestCase
class user_profile_tests(BaseTestCase):
def test_read_empty_profile(self):
resp = self.client.get("/details/profile")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["theme"], "dark")
self.assertEqual(resp.json()["lang"], "eng")
def test_update_profile(self):
resp = self.client.put("/details/profile", json={"theme": "light", "lang": "fra"})
self.assertEqual(resp.status_code, 200)
resp = self.client.get("/details/profile")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["theme"], "light")
self.assertEqual(resp.json()["lang"], "fra")
def test_update_invalid_profile(self):
resp = self.client.put("/details/profile", json={"theme": "creamy", "lang": "fra"})
self.assertEqual(resp.status_code, 422)
resp = self.client.get("/details/profile")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.json()["theme"], "dark")
self.assertEqual(resp.json()["lang"], "eng")
+19
View File
@@ -0,0 +1,19 @@
from unittest import TestCase
from fastapi.testclient import TestClient
from src.api.app import make_app
from tests.utils import HA_CONFIG_EXAMPLE, get_example_automation_loader
class BaseTestCase(TestCase):
source_config_path = HA_CONFIG_EXAMPLE
def setUp(self) -> None:
(
self.config_folder,
self.hass_config,
self.automation_loader,
) = get_example_automation_loader(config_to_copy=self.source_config_path)
self.client = TestClient(make_app(self.hass_config))
+3 -14
View File
@@ -1,23 +1,12 @@
from pathlib import Path
from src.automations.errors import DBDataError
from src.automations.errors import DBDataError, RepeatedAutomationId
from src.automations.types import ExtenededAutomation
from .utils import TestWithDB
class db_tests(TestWithDB):
def test_db_creation(self):
with self.db.get_cur() as cur:
cur.execute("SELECT name FROM sqlite_master WHERE type ='table'")
tables = cur.fetchall()
self.assertListEqual(tables, [("autos",)])
self.db.create_db()
with self.db.get_cur() as cur:
cur.execute("SELECT name FROM sqlite_master WHERE type ='table'")
tables = cur.fetchall()
self.assertListEqual(tables, [("autos",)])
def test_insert_automations(self):
originals = [
ExtenededAutomation(
@@ -61,7 +50,7 @@ class db_tests(TestWithDB):
configuration_key=["automation"],
),
]
with self.assertRaises(DBDataError) as err:
with self.assertRaises(RepeatedAutomationId):
self.db.insert_automations(originals)
autos = list(self.db.list_automations(0, 10))
self.assertEqual(len(autos), 0)
self.assertEqual(len(autos), 1)
@@ -28,7 +28,6 @@ class manager_tests(TestWithDB):
self.config_path = create_copy_of_example_config(ha_config_example)
self.automation_manager = AutomationManager(
HassConfig(self.config_path),
self.db_file,
)
return self.config_path, self.automation_manager
@@ -54,10 +53,6 @@ class manager_tests(TestWithDB):
{"platform": "zone", "entity_id": "person.thor", "zone": "zone.azguard"}
)
automation_manager.update(automation)
self.assertEqual(
automation_manager.get("sublist3-mlist2").trigger,
[],
)
automation_manager.reload()
self.assertEqual(
automation_manager.get("sublist3-mlist2").trigger,
+1 -12
View File
@@ -1,19 +1,8 @@
from pathlib import Path
from tempfile import mktemp
from unittest import TestCase
from src.automations.db import AutomationDBConnection
def make_temp_db():
return AutomationDBConnection(Path(mktemp() + ".db"))
class TestWithDB(TestCase):
def setUp(self) -> None:
self.db = make_temp_db()
self.db.create_db()
self.db_file = self.db.db_file
def tearDown(self) -> None:
self.db_file.unlink()
self.db = AutomationDBConnection()
+1 -1
View File
@@ -1,5 +1,5 @@
name: Shortumation
version: v0.6.2
version: v0.6.3
slug: shortumation
image: asosnovsky/shortumation-{arch}
url: "https://github.com/asosnovsky/Shortumation"
+2
View File
@@ -8,8 +8,10 @@ host_port="$host:$port"
pushd $api_location
echo "--------------------"
echo "BUILD_VERSION = "$BUILD_VERSION
echo "ARCH = "$BUILD_ARCH
echo "HOST = $host_port"
echo "HASSIO_WS = $HASSIO_WS"
echo $(uname -a)
echo $(python --version)
echo "--------------------"
python -m hypercorn src.app:app -b $host_port --config /app/hypercorn.toml
+2 -2
View File
@@ -9,9 +9,9 @@
"@mui/icons-material": "5.8.4",
"@mui/material": "5.8.6",
"@mui/styles": "5.8.6",
"@types/jest": "28.1.6",
"@types/jest": "28.1.8",
"@types/node": "17.0.36",
"@types/react": "18.0.15",
"@types/react": "18.0.18",
"@types/react-dom": "18.0.6",
"@types/ws": "8.5.3",
"@uiw/react-codemirror": "4.10.4",
+6 -9
View File
@@ -8,7 +8,11 @@ import { Page } from "components/Page";
const ConnectedAutomationRoute = () => {
const api = useConnectedApiService();
return <AutomationRoute api={api} />;
return (
<Page api={api}>
<AutomationRoute api={api} />
</Page>
);
};
function App() {
@@ -18,14 +22,7 @@ function App() {
<CookiesProvider>
<BrowserRouter>
<Routes>
<Route
path="*"
element={
<Page>
<ConnectedAutomationRoute />
</Page>
}
/>
<Route path="*" element={<ConnectedAutomationRoute />} />
</Routes>
</BrowserRouter>
</CookiesProvider>
+39 -12
View File
@@ -1,28 +1,55 @@
import { useEffect } from "react";
import { useDefaultApiState, makeReloadAutomations } from "./util";
import {
useDefaultApiState,
makeReloadAutomations,
makeProfileManager,
} from "./util";
import { AutomationAPI } from "./automations";
import { UserProfileAPI } from "./profile";
export type ApiService = ReturnType<typeof useAPIService>;
export const useAPIService = (automationAPI: AutomationAPI) => {
export const useAPIService = (
automationAPI: AutomationAPI,
userProfileAPI: UserProfileAPI
) => {
// state
const [state, setState] = useDefaultApiState();
const { reload, wrapCall } = makeReloadAutomations(
automationAPI,
const autoManager = makeReloadAutomations(automationAPI, state, setState);
const userProfileManager = makeProfileManager(
userProfileAPI,
state,
setState
);
// initial load of autos
useEffect(() => {
reload();
// eslint-disable-next-line
}, []);
if (state.automations.ready === undefined) {
autoManager.reload();
}
}, [state.automations.ready, autoManager]);
// initial load of profile
useEffect(() => {
if (state.userProfile.ready === undefined) {
userProfileManager.reload();
}
}, [state.userProfile.ready, userProfileManager]);
return {
state,
removeAutomation: wrapCall(automationAPI.remove),
updateAutomation: wrapCall(automationAPI.update),
createAutomation: wrapCall(automationAPI.create),
updateTags: wrapCall(automationAPI.updateTags),
state: {
...state,
get theme(): "dark" | "light" {
if (state.userProfile.ready && state.userProfile.ok) {
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 { makeRemoteAPI } from "./base";
import { useAPIService } from "./core";
import { useMockAPI } from "./mock";
import { useRef } from "react";
import { useAutoMockAPI, useProfileMockAPI } from "./mock";
import { createContext, useContext, useRef } from "react";
import { makeProfileAPI } from "./profile";
import { ApiState } from "./types";
const locationPrefixWeb = window.location.pathname.match(/(\/.+\/)web/i);
const baseURL = new URL(
@@ -13,12 +15,21 @@ const baseURL = new URL(
);
export const wsURL = baseURL + "socket";
export const remoteAutoAPI = makeRemoteAPI(baseURL + "automations");
export const detailsAPI = makeRemoteAPI(baseURL + "details");
export const useConnectedApiService = () =>
useAPIService(makeAutomationAPI(remoteAutoAPI));
useAPIService(makeAutomationAPI(remoteAutoAPI), makeProfileAPI(detailsAPI));
export const useMockApiService = (
initialAutos: AutomationData[],
returnErrors: boolean = false
) =>
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 { createMockAuto } from "../utils/mocks";
import { AutomationData } from "types/automations";
@@ -6,7 +6,7 @@ import { AutomationData } from "types/automations";
const fakeUseRef = (a: any) => ({ current: a });
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 });
expect(data.ok).toBe(true);
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 () => {
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 });
expect(data.ok).toBe(true);
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 () => {
const mockApi = makeAutomationAPI(useMockAPI([], fakeUseRef as any));
const mockApi = makeAutomationAPI(useAutoMockAPI([], fakeUseRef as any));
await mockApi.create(createMockAuto());
let data = await mockApi.list({ limit: 10, offset: 0 });
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 () => {
const mockApi = makeAutomationAPI(
useMockAPI(
useAutoMockAPI(
[
createMockAuto(),
createMockAuto(),
@@ -61,7 +63,7 @@ test("delete/update data from mock api", async () => {
test("update tags from mock api", async () => {
const mockApi = makeAutomationAPI(
useMockAPI(
useAutoMockAPI(
[
createMockAuto(),
createMockAuto(),
+39 -1
View File
@@ -1,13 +1,15 @@
import { useRef } from "react";
import { AutomationData, BareAutomationData } from "types/automations";
import { API } from "./base";
import { UserProfile } from "./types";
import {
AUTOMTAION_LIST,
AUTOMTAION_ITEM,
AUTOMTAION_ITEM_TAGS,
USER_PROFILE_ROOT,
} from "./paths";
export const useMockAPI = (
export const useAutoMockAPI = (
initialAutos: AutomationData[] = [],
makeRef = useRef,
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_ITEM = `${AUTOMTAION_ROOT}item` 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;
error: string;
};
export type Errorable<D> =
export type Waitable<D> =
| { ready: undefined }
| ({ ready: true } & APIResponse<D>)
| {
ready: false;
@@ -31,5 +32,11 @@ export interface ListData<D> {
}
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 { ApiState } from "./types";
import { AutomationAPI } from "./automations";
import { UserProfileAPI } from "./profile";
import { UserProfile } from "apiService/types";
export const useDefaultApiState = () =>
useState<ApiState>({
automations: { ready: false },
automations: { ready: undefined },
userProfile: { ready: undefined },
});
export const makeReloadAutomations = (
@@ -38,3 +41,50 @@ export const makeReloadAutomations = (
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 { TagDB } from "components/AutomationManager/TagDB";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
export interface AutoInfoBoxProps {
metadata: AutomationMetadata & Partial<AutomationShortumationMetadata>;
@@ -26,6 +27,7 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
tagDB,
}) => {
// state
const langStore = useLang();
const [newTag, setNewTag] = useState<[string, string]>(["", ""]);
const [[errorIndex, error], _setError] = useState<[number | "new", string]>([
-1,
@@ -54,12 +56,12 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
);
const validTagName = (newName: string): string | undefined => {
if (newName.length <= 0) {
return "Name must be at least 1 character long";
return langStore.get("VALIDATION_AUTOMATION_NAME");
}
// eslint-disable-next-line
for (const [name, _] of tags) {
if (name.trim() === newName.trim()) {
return `The tag '${name}' already exists`;
return langStore.get("VALIDATION_TAG_EXISTS", { name });
}
}
};
@@ -101,23 +103,23 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div className="automation-editor--info-box">
<div className="automation-editor--info-box-inner">
<InputText
label="ID"
label={langStore.get("ID")}
value={metadata.id}
onChange={onUpdateMetadata("id")}
/>
<InputText
label="Name"
label={langStore.get("NAME")}
value={metadata.alias ?? ""}
onChange={onUpdateMetadata("alias")}
/>
<InputText
multiline
label="Description"
label={langStore.get("DESCRIPTION")}
value={metadata.description ?? ""}
onChange={onUpdateMetadata("description")}
/>
<InputList
label="Mode"
label={langStore.get("MODE")}
current={metadata.mode}
onChange={onUpdateMetadata("mode")}
options={["parallel", "single", "queued", "restart"]}
@@ -129,14 +131,14 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div key={tagIndex} className="automation-editor--info-box--tag">
<InputAutoText
value={tagName}
label="Name"
label={langStore.get("NAME")}
onChange={(v) => updateTagName(v, tagIndex)}
options={foundNewTagNames}
error={errorIndex === tagIndex ? error : undefined}
/>
<InputAutoText
value={tagValue}
label="Tag"
label={langStore.get("TAG")}
onChange={(v) => onUpdateTags(v, tagIndex)}
options={tagDB.getTagValues(tagName)}
error={errorIndex === tagIndex ? error : undefined}
@@ -153,14 +155,14 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div className="automation-editor--info-box--tag">
<InputAutoText
value={newTag[0]}
label="Name"
label={langStore.get("NAME")}
onChange={(v) => setNewTag([v, newTag[1]])}
options={foundNewTagNames}
error={errorIndex === "new" ? error : undefined}
/>
<InputAutoText
value={newTag[1]}
label="Tag"
label={langStore.get("TAG")}
onChange={(v) => setNewTag([newTag[0], v])}
options={tagDB.getTagValues(newTag[0])}
error={errorIndex === "new" ? error : undefined}
@@ -1,23 +1,21 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { AutomationEditor } from "./index";
import { useState } from "react";
import { Page } from "components/Page";
import { useTagDB } from "components/AutomationManager/TagDB";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
export default {
title: "App/AutomationEditor",
component: AutomationEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
dims: DEFAULT_DIMS,
},
} as ComponentMeta<typeof AutomationEditor>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof AutomationEditor> = (args) => {
const [state, setState] = useState(args.automation);
return (
<Page>
const { make, componentMeta } = makeStory({
Component: AutomationEditor,
meta: {
title: "App/AutomationEditor",
args: {
dims: DEFAULT_DIMS,
},
},
BaseTemplate: (args) => {
const [state, setState] = useState(args.automation);
return (
<AutomationEditor
{...args}
tagDB={useTagDB(
@@ -29,15 +27,15 @@ const Template: ComponentStory<typeof AutomationEditor> = (args) => {
window.setTimeout(() => setState(s), 3000);
}}
/>
</Page>
);
};
);
},
});
export const Loading = Template.bind({});
export default componentMeta;
export const Simple = Template.bind({});
Simple.args = {
...Simple.args,
export const Loading = make({});
export const Simple = make({
automation: {
condition: [],
tags: {
@@ -94,11 +92,9 @@ Simple.args = {
},
],
},
};
});
export const EmptyStart = Template.bind({});
EmptyStart.args = {
...EmptyStart.args,
export const EmptyStart = make({
automation: {
condition: [],
tags: {},
@@ -115,22 +111,18 @@ EmptyStart.args = {
trigger: [],
action: [],
},
};
});
export const BadAutomationInvalidMetadata = Template.bind({});
BadAutomationInvalidMetadata.args = {
...BadAutomationInvalidMetadata.args,
export const BadAutomationInvalidMetadata = make({
automation: {
condition: [],
tags: {},
trigger: [],
action: [],
} as any,
};
});
export const BadAutomationInvalidTriggers = Template.bind({});
BadAutomationInvalidTriggers.args = {
...BadAutomationInvalidTriggers.args,
export const BadAutomationInvalidTriggers = make({
automation: {
condition: [],
tags: {},
@@ -147,11 +139,9 @@ BadAutomationInvalidTriggers.args = {
trigger: ["haha I am a string"] as any,
action: [],
},
};
});
export const BadAutomationInvalidSequence = Template.bind({});
BadAutomationInvalidSequence.args = {
...BadAutomationInvalidSequence.args,
export const BadAutomationInvalidSequence = make({
automation: {
condition: [],
tags: {},
@@ -165,14 +155,12 @@ BadAutomationInvalidSequence.args = {
action: [
{
choose: {},
},
} as any,
],
} as any,
};
});
export const RepeatExample = Template.bind({});
RepeatExample.args = {
...RepeatExample.args,
export const RepeatExample = make({
automation: {
id: "1654976151462",
alias: "Get out of baby room",
@@ -243,4 +231,4 @@ RepeatExample.args = {
],
tags: {},
},
};
});
@@ -31,6 +31,7 @@ import { MiniFailure } from "types/validators/helper";
import { AutoInfoBox } from "./AutoInfoBox";
import { useAutomatioEditorState, EditorData } from "./state";
import { useLang } from "lang";
interface Props {
automation?: AutomationData | BareAutomationData;
@@ -51,6 +52,7 @@ export const AutomationEditor: FC<Props> = ({
isNew,
}) => {
// state
const langStore = useLang();
const {
state,
updateSequence,
@@ -131,7 +133,7 @@ export const AutomationEditor: FC<Props> = ({
<div className="id">{state.data.id}</div>
<InputTextView
value={state.data.alias ?? ""}
placeholder="Name"
placeholder={langStore.get("NAME")}
onChange={(alias) =>
updateMetadata(
{
@@ -145,7 +147,7 @@ export const AutomationEditor: FC<Props> = ({
</span>
<InputList
fullWidth={false}
label="Mode"
label={langStore.get("MODE")}
className="automation-editor--flow-wrapper--toolbar--modes"
current={{
id: state.data.mode,
@@ -165,28 +167,26 @@ export const AutomationEditor: FC<Props> = ({
options={[
{
id: "single",
label: "Do not start a new run. Issue a warning.",
label: langStore.get("MODE_SIGNLE_LABEL"),
},
{
id: "parallel",
label:
"Start a new, independent run in parallel with previous runs.",
label: langStore.get("MODE_SIGNLE_PARALLEL"),
},
{
id: "queued",
label:
"Start a new run after all previous runs complete. Runs are guaranteed to execute in the order they were queued.",
label: langStore.get("MODE_SIGNLE_QUEUED"),
},
{
id: "restart",
label: "Start a new run after first stopping previous run.",
label: langStore.get("MODE_SIGNLE_RESTART"),
},
]}
/>
<InputTextView
className="description"
value={state.data.description ?? ""}
placeholder="Description"
placeholder={langStore.get("DESCRIPTION")}
onChange={(description) =>
updateMetadata(
{
@@ -204,7 +204,7 @@ export const AutomationEditor: FC<Props> = ({
onClick={() => setFlipped(!flipped)}
>
<Icon>{flipped ? "flip_to_front" : "flip_to_back"}</Icon>
Flip
{langStore.get("FLIPP")}
</Button>
)}
{state.status === "changed" && (
@@ -217,7 +217,7 @@ export const AutomationEditor: FC<Props> = ({
onClick={save}
disabled={state.status !== "changed"}
>
Save <CheckMarkIcon color="#bf4" />
{langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button>
</div>
<DAGAutomationGraph
@@ -242,26 +242,26 @@ export const AutomationEditor: FC<Props> = ({
// tooltipOpen
sx={{ pointerEvents: "auto" }}
icon={<RunIcon />}
tooltipTitle={"Trigger"}
tooltipTitle={langStore.get("TRIGGER")}
onClick={onTrigger}
/>
<SpeedDialAction
// tooltipOpen
icon={<DeleteIcon />}
tooltipTitle={"Delete"}
tooltipTitle={langStore.get("DELETE")}
onClick={onDelete}
/>
<SpeedDialAction
// tooltipOpen
icon={<EditIcon />}
tooltipTitle={"Metadata"}
tooltipTitle={langStore.get("METADATA")}
onClick={() => setInfoBox(!infoBoxOpen)}
/>
{state.status === "changed" && (
<SpeedDialAction
// tooltipOpen
icon={<UndoIcon />}
tooltipTitle={"Undo"}
tooltipTitle={langStore.get("UNDO")}
onClick={undo}
/>
)}
@@ -277,6 +277,7 @@ export const ValidationBox: FC<{
data: EditorData;
onSave: (d: EditorData) => void;
}> = (props) => {
const langStore = useLang();
const [{ failures, data }, setState] = useState({
failures: props.failures,
data: props.data,
@@ -317,12 +318,10 @@ export const ValidationBox: FC<{
</>
))}
</ul>
<span>
Please correct the automation file manually and then continue!
</span>
<InputYaml label="Raw" value={data} onChange={onSave} />
<span>{langStore.get("VALIDATION_PLEASE_CORRECT_FILE")}</span>
<InputYaml label={langStore.get("RAW")} value={data} onChange={onSave} />
<Button disabled={failures.length > 0} onClick={() => props.onSave(data)}>
Save
{langStore.get("SAVE")}
</Button>
</div>
);
@@ -1,4 +1,5 @@
import { HassEntities } from "home-assistant-js-websocket";
import { LangStore, useLang } from "lang";
import { useEffect, useState } from "react";
import { AutomationData, BareAutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults";
@@ -10,7 +11,8 @@ export const useAutomationDB = (
configAutomations: AutomationData[],
tagsDB: TagDB
) => {
const autoMap = genMapping(haEntities, configAutomations, tagsDB);
const langStore = useLang();
const autoMap = genMapping(haEntities, configAutomations, tagsDB, langStore);
const [newAuto, setNewAuto] =
useState<
null | [AutomationManagerAuto, AutomationData | BareAutomationData]
@@ -54,13 +56,13 @@ export const useAutomationDB = (
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: "unregistered",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: {},
issue: "New Automation",
issue: langStore.get("NEW_AUTOMATION"),
isNew: true,
source_file: "n/a",
source_file_type: "n/a",
configuration_key: ["n/a"],
source_file: langStore.get("N/A"),
source_file_type: langStore.get("N/A"),
configuration_key: [],
},
auto,
]);
@@ -72,7 +74,8 @@ export const useAutomationDB = (
const genMapping = (
haEntities: HassEntities,
configAutomations: AutomationData[],
tagsDB: TagDB
tagsDB: TagDB,
langStore: LangStore
) => {
const configData: Record<string, AutomationData> = configAutomations.reduce(
(all, n) => ({
@@ -93,7 +96,9 @@ const genMapping = (
let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state)
? undefined
: `recived invalid state "${entityData.state}, this could be because you have a lingering automation that was not cleared by homeassistant, try to reboot HA or manually clear this automation from HA Database."`;
: langStore.get("ISSUES_INVALID_STATE", {
state: entityData.state,
});
let found: AutomationData | null = null;
let source_file = "n/a";
let source_file_type = "n/a";
@@ -107,7 +112,7 @@ const genMapping = (
configuration_key = found.configuration_key ?? configuration_key;
delete configData[autoId];
} else {
issue = "failed to find this automation in '/config' folder";
issue = langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG");
}
automatioinMap[autoId] = [
@@ -134,13 +139,12 @@ const genMapping = (
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: "unregistered",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: tagsDB.getTags(auto.id),
source_file: auto.source_file,
source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key,
issue:
"homeassistant did not load this automation, try to manually reload automations or restart homeassistant.",
issue: langStore.get("ISSUES_NO_LOAD_AUTOMATION"),
},
auto,
];
@@ -10,6 +10,7 @@ import {
} from "./state";
import Alert from "@mui/material/Alert";
import { useConfirm } from "material-ui-confirm";
import { useLang } from "lang";
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
onAutomationDelete: (aid: string, eid: string) => void;
@@ -17,13 +18,14 @@ export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
export const AutomationManagerLoaded: FC<
PropsWithChildren<AutomationManagerLoadedProps>
> = ({ children, ...args }) => {
const langStore = useLang();
const state = useAutomationManagerState(args);
const confirm = useConfirm();
const onAutomationDelete = async (aid: string, eid: string) =>
confirm({
title: "Are you sure you want to delete this automation?",
confirmationText: "Delete",
title: langStore.get("CONFIRMATION_DELETE_THIS_AUTOMATION"),
confirmationText: langStore.get("DELETE"),
})
.then(() => {
args.onAutomationDelete(aid, eid);
@@ -76,8 +78,9 @@ export const AutomationManagerLoaded: FC<
) : (
<div>
<Alert color="warning">
Failed to find an automation on disk with id{" "}
{state.currentAutomationId}.
{langStore.get("ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK", {
id: state.currentAutomationId,
})}
</Alert>
</div>
)
@@ -7,6 +7,7 @@ import { useAutomationDB } from "./automationDB";
import { useConfirm } from "material-ui-confirm";
import { AutomationManagerAutoUpdatable } from "../types";
import { useSnackbar } from "notistack";
import { useLang } from "lang";
export type UseAutomationManagerStateArgs = {
configAutomations: AutomationData[];
@@ -26,6 +27,7 @@ export const useAutomationManagerState = ({
onAutomationStateChange,
}: UseAutomationManagerStateArgs) => {
// state
const langStore = useLang();
const confirm = useConfirm();
const snackbr = useSnackbar();
const cookies = useAMSCookies();
@@ -44,10 +46,9 @@ export const useAutomationManagerState = ({
const stillHaveNewAreYouSure = async () => {
try {
await confirm({
content:
"Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.",
confirmationText: "Switch Automation",
cancellationText: "Cancel",
content: langStore.get("WARNING_SWITCHING_FROM_NONE_SAVE"),
confirmationText: langStore.get("SWITCH_AUTOMATION"),
cancellationText: langStore.get("CANCEL"),
});
return true;
} catch (_) {
@@ -128,9 +129,10 @@ export const useAutomationManagerState = ({
}
} else {
snackbr.enqueueSnackbar(
`Failed to save automation "${aid}" contents - ${JSON.stringify(
a
)} -- not found in /config`,
langStore.get("ERROR_FAILED_TO_SAVE", {
aid,
contents: JSON.stringify(a),
}),
{ variant: "error" }
);
}
@@ -12,6 +12,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "../TagDB";
import { useLang } from "lang";
export type TagsProps = {
automationId: string;
@@ -29,6 +30,7 @@ export type TagModalState =
};
export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
const langStore = useLang();
const [modalState, setModal] = useState<TagModalState>({ open: false });
const tags = tagsDB.getTags(automationId, true);
const onUpdate = (t: Record<string, string>) =>
@@ -44,7 +46,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText
className="name"
options={tagsDB.getTagNames(Object.keys(tags))}
label="Tag Name"
label={langStore.get("TAG_NAME")}
value={modalState.tag[0]}
onChange={(v) =>
setModal({
@@ -56,7 +58,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
<InputAutoText
className="value"
options={tagsDB.getTagValues(modalState.tag[0])}
label="Tag Value"
label={langStore.get("TAG_VALUE")}
value={modalState.tag[1]}
onChange={(v) =>
setModal({
@@ -67,7 +69,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
/>
<div className="buttons">
<Button onClick={() => setModal({ open: false })} color="info">
Close
{langStore.get("CLOSE")}
</Button>
<Button
disabled={!validTag}
@@ -80,7 +82,7 @@ export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
}}
color="success"
>
{modalState.isNew ? "Create" : "Save"}
{modalState.isNew ? langStore.get("CREATE") : langStore.get("SAVE")}
</Button>
</div>
</div>
@@ -9,12 +9,16 @@ import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import SelectIcon from "@mui/icons-material/HighlightAltSharp";
import RunIcon from "@mui/icons-material/RunCircleOutlined";
import Tooltip from "@mui/material/Tooltip";
import Box from "@mui/material/Box";
import Chip from "@mui/material/Chip";
import { InputTextView } from "components/Inputs/InputTextView";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { AutomationManagerAuto } from "../types";
import { Tags } from "./Tags";
import { TagDB } from "../TagDB";
import { Chip, Tooltip } from "@mui/material";
import { useLang } from "lang";
export type MetadataBoxProps = AutomationManagerAuto & {
onDelete: () => void;
@@ -28,8 +32,12 @@ export type MetadataBoxProps = AutomationManagerAuto & {
};
export const MetadataBox: FC<MetadataBoxProps> = (props) => {
const isValidState = ["on", "off"].includes(props.state);
const langStore = useLang();
const prettyState = ["on", "off"].includes(props.state)
? langStore.get(`AUTOMATION_STATE_${props.state}`)
: props.state;
return (
<div
<Box
className={[
"automation-manager--metadatabox",
props.isSelected ? "selected" : "",
@@ -38,7 +46,13 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
>
<div
className="metadatabox--switch"
title={!isValidState ? "Invalid state" : `Automation is ${props.state}`}
title={
!isValidState
? langStore.get("ERROR_INVALID_AUTOMATION_STATE")
: langStore.get("AUTOMATION_STATE_IS", {
state: prettyState,
})
}
>
<Switch
checked={props.state !== "off"}
@@ -53,28 +67,36 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
<div className="metadatabox--title">
<span className="metadatabox--title--source">
<Tooltip
title={`This automation is located in the file ${props.source_file}. It's currently '${props.state}', it's entity id is '${props.entityId}' and it's automation id is '${props.id}'`}
title={langStore.get("AUTOMATION_METADATA_TOOLTIP_TEXT", {
source_file: props.source_file,
state: prettyState,
entityId: props.entityId,
id: props.id,
})}
>
<Chip
label={`@${props.source_file} (${props.source_file_type}) - ${
props.entityId ?? "n/a"
props.entityId ?? langStore.get("N/A")
}`}
className="text-ellipsis"
/>
</Tooltip>
</span>
<Tooltip title={`ID=${props.id}, EntityID=${props.entityId}`}>
<InputTextView
className="title"
placeholder="Title"
value={props.title}
onChange={props.onTitleUpdate}
disabled={props.isNew}
/>
</Tooltip>
<InputTextView
titleSlug="AUTOMATION_METADATA_TOOLTIP_SIMPLE"
titleParams={{
id: props.id,
entityId: props.entityId,
}}
className="title"
placeholder={langStore.get("TITLE")}
value={props.title}
onChange={props.onTitleUpdate}
disabled={props.isNew}
/>
<InputTextView
className="description"
placeholder="Description"
placeholder={langStore.get("DESCRIPTION")}
value={props.description}
onChange={props.onDescriptionUpdate}
disabled={props.isNew}
@@ -90,24 +112,24 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
</div>
<div className="buttons">
<ButtonIcon
titleSlug="SELECT_AUTOMATION"
className="select"
icon={<SelectIcon />}
onClick={props.onSelect}
title="Select automation"
/>
<ButtonIcon
titleSlug="TRIGGER_AUTOMATION"
className="run"
icon={<RunIcon />}
onClick={props.onRun}
title="Trigger automation"
/>
<ButtonIcon
titleSlug="DELETE_AUTOMATION"
className="delete"
icon={<DeleteForeverIcon />}
onClick={props.onDelete}
title="Delete automation"
/>
</div>
</div>
</Box>
);
};
@@ -18,6 +18,7 @@ import {
} from "../types";
import { Button } from "components/Inputs/Buttons/Button";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
export type AutomationManagerSidebarProps = {
tagsDB: TagDB;
@@ -41,6 +42,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
onSelectedAutomationId,
...events
}) => {
const langStore = useLang();
const [searchText, setSearchText] = useState("");
const [selectedTagIdx, setSelectedTagIdx] = useState<number[]>([]);
const [isHidden, setHidden] = useState(false);
@@ -76,9 +78,13 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
].join(" ")}
>
<div className="automation-manager--sidebar-box--nav">
<InputText label="Search" value={searchText} onChange={setSearchText} />
<InputText
label={langStore.get("SEARCH")}
value={searchText}
onChange={setSearchText}
/>
<InputMultiSelect
label="Tags"
label={langStore.get("TAGS")}
selected={selectedTagIdx}
onChange={setSelectedTagIdx}
options={tags}
@@ -109,7 +115,7 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
color="primary"
className="add-btn"
>
Add
{langStore.get("ADD")}
</Button>
<ButtonIcon
className="hide-btn"
@@ -15,6 +15,7 @@ import * as av from "types/validators/autmation";
import { useConfirm } from "material-ui-confirm";
import InputYaml from "components/Inputs/Base/InputYaml";
import { APIResponse } from "apiService/types";
import { useLang } from "lang";
export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => Promise<any>;
@@ -33,6 +34,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
forceDeleteAutomation: _forceDeleteAutomation,
triggerAutomation: _triggerAutomation,
}) => {
const langStore = useLang();
const snackbr = useSnackbar();
const confirm = useConfirm();
const validationsShown = useRef(false);
@@ -52,9 +54,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
})
.catch((err) => {
console.error(err);
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", String(err)), {
variant: "error",
});
snackbr.enqueueSnackbar(
langStore.get(errorMessage, {
err: String(err),
}),
{
variant: "error",
}
);
setIsSaving(isSaving.filter((k) => k !== name));
});
}
@@ -68,9 +75,14 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
if (resp.ok) {
refreshAutomations();
} else {
snackbr.enqueueSnackbar(errorMessage.replace("{{err}}", resp.error), {
variant: "error",
});
snackbr.enqueueSnackbar(
langStore.get(errorMessage, {
err: resp.error,
}),
{
variant: "error",
}
);
}
}
});
@@ -78,24 +90,26 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
const onAutomationStateChange = (eid: string, on: boolean) =>
wrapPromise(
"changing automation state",
'failed to toggle autonation due to "{{err}}"',
langStore.get("AUTOMATION_MANAGER_STATE_CHANGE"),
"AUTOMATION_MANAGER_STATE_CHANGE_FAIL",
() => _onAutomationStateChange(eid, on)
);
const refreshAutomations = () =>
wrapPromise(
"refreshing automations",
'failed refreshing automations due to "{{err}}"',
langStore.get("AUTOMATION_MANAGER_REFRESH"),
"AUTOMATION_MANAGER_REFRESH_FAIL",
() => _refreshAutomations()
);
const forceDeleteAutomation = (eid: string) =>
wrapPromise("deleting automations", 'failed delete due to "{{err}}"', () =>
_forceDeleteAutomation(eid)
wrapPromise(
langStore.get("AUTOMATION_MANAGER_DELETE"),
"AUTOMATION_MANAGER_DELETE_FAIL",
() => _forceDeleteAutomation(eid)
);
const triggerAutomation = (eid: string) =>
wrapPromise(
"triggering automations",
'failed trigger due to "{{err}}"',
langStore.get("AUTOMATION_MANAGER_TRIGGER"),
"AUTOMATION_MANAGER_TRIGGER_FAIL",
() => _triggerAutomation(eid)
);
@@ -129,7 +143,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
cancellationButtonProps: {
style: { display: "none" },
},
title: "Invalid Automations detected!",
title: langStore.get("ERROR_INVALID_AUTOMATION_DETECTED"),
content: (
<>
<ol className="invalid-automation-modal-list">
@@ -165,6 +179,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
.catch(console.error);
}
}
// eslint-disable-next-line
}, [api.state.automations, confirm]);
// handle bad states
@@ -172,8 +187,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return (
<div className="automation-manager error">
<Alert color="error">
Failed to connect to websocket, please check that your access token is
properly setup
{langStore.get("ERROR_FAILED_CONNECTION_TO_HA")}
</Alert>{" "}
<br />
<code>{JSON.stringify(haEntities.error)}</code>
@@ -205,7 +219,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
return (
<div className="automation-manager error">
<Alert color="error">
Failed to load automations from <code>/config</code>
{langStore.get("ISSUES_FIND_AUTOMATION_IN_CONFIG")}
</Alert>{" "}
<br />
<code>{error}</code>
@@ -237,8 +251,8 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
onAutomationStateChange={onAutomationStateChange}
onAutomationAdd={(auto) =>
wrapApiPromise(
"adding automation",
"Failed to create automation, recieved error: {{err}}!",
langStore.get("AUTOMATION_MANAGER_ADD"),
"AUTOMATION_MANAGER_ADD_FAIL",
() => api.createAutomation(auto) as any
)
}
@@ -258,7 +272,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}
if (!deleteSent) {
snackbr.enqueueSnackbar(
"Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant",
langStore.get("AUTOMATION_MANAGER_DELETE_LIGHT"),
{
variant: "error",
}
@@ -268,15 +282,15 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}}
onAutomationUpdate={(auto) =>
wrapApiPromise(
"updating automation",
"Failed to update automation, recieved error: {{err}}!",
langStore.get("AUTOMATION_MANAGER_UPDATE"),
"AUTOMATION_MANAGER_UPDATE_FAIL",
() => api.updateAutomation(auto) as any
)
}
onUpdateTags={async (aid, t) => {
wrapApiPromise(
"updating tags",
"Failed to update tags, recieved error: {{err}}!",
langStore.get("AUTOMATION_MANAGER_UPDATE_TAGS"),
"AUTOMATION_MANAGER_UPDATE_TAGS_FAIL",
() =>
api.updateTags({
automation_id: aid,
@@ -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 { AutomationCondition } from "types/automations/conditions";
import { ConditionNodeBase } from "./ConditionNodeBase";
export default {
title: "ConditionEditor/NodeBase",
component: ConditionNodeBase,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof ConditionNodeBase>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof ConditionNodeBase> = ({
condition,
...args
}) => {
const [data, setData] = useState(condition);
return (
<Page>
const { make, componentMeta } = makeStory({
Component: ConditionNodeBase,
meta: {
title: "ConditionEditor/NodeBase",
},
BaseTemplate: ({ condition, ...args }) => {
const [data, setData] = useState(condition);
return (
<ConditionNodeBase
{...args}
condition={data}
@@ -24,20 +19,20 @@ const Template: ComponentStory<typeof ConditionNodeBase> = ({
setData(data);
}}
/>
</Page>
);
};
);
},
});
export const TemplateViewer = Template.bind({});
TemplateViewer.args = {
export default componentMeta;
export const TemplateViewer = make({
condition: {
condition: "template",
value_template: "states('switch.light_kitchen') == 'on'",
} as AutomationCondition,
};
});
export const MultipleThings = Template.bind({});
MultipleThings.args = {
export const MultipleThings = make({
condition: {
condition: "or",
conditions: [
@@ -62,4 +57,4 @@ MultipleThings.args = {
},
],
} as AutomationCondition,
};
});
@@ -12,6 +12,7 @@ import { getViewer } from "./viewRender";
import { getEditor } from "./editorRender";
import useWindowSize from "utils/useWindowSize";
import { ConditionNodeSettings } from "./ConditionNodeSettings";
import { useLang } from "lang";
export type ConditionNodeBaseProps = {
condition: AutomationCondition;
@@ -24,6 +25,7 @@ export type ConditionNodeBaseViewMode = "edit" | "yaml" | "view";
export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
// state
const ha = useHA();
const langStore = useLang();
const { isMobile } = useWindowSize();
const [{ isEdited, condition }, setCondition] = useState<{
isEdited: boolean;
@@ -61,6 +63,7 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
onChange={updateCondition}
ha={ha}
initialViewMode="edit"
langStore={langStore}
/>
);
}
@@ -101,6 +104,7 @@ export const ConditionNodeBase: FC<ConditionNodeBaseProps> = (props) => {
},
} as any)
}
prettyOptionLabels={false}
/>
{isMobile && icons}
</div>
@@ -31,6 +31,7 @@ import { prettyName } from "utils/formatting";
import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Buttons/Button";
import { RemoveCircle } from "@mui/icons-material";
import { LangStore } from "lang";
interface Editor<C extends AutomationCondition>
extends FC<{
@@ -38,6 +39,7 @@ interface Editor<C extends AutomationCondition>
onChange: (condition: C) => void;
ha: HAService;
initialViewMode: ConditionNodeBaseViewMode;
langStore: LangStore;
}> {}
export const getEditor = (condition: AutomationCondition): Editor<any> => {
@@ -70,11 +72,12 @@ export const getEditor = (condition: AutomationCondition): Editor<any> => {
export const TemplateEditor: Editor<TemplateCondition> = ({
onChange,
condition,
langStore,
}) => {
return (
<>
<InputYaml
label="Template"
label={langStore.get("TEMPLATE")}
value={condition.value_template}
onChange={(value_template) =>
onChange({
@@ -119,6 +122,7 @@ export const DeviceConditionEditor: Editor<DeviceCondition> = ({
export const NumericStateEditor: Editor<NumericCondition> = ({
onChange,
condition,
langStore,
}) => {
return (
<>
@@ -133,7 +137,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
}
/>
<InputText
label="Attribute"
label={langStore.get("ATTRIBUTE")}
value={condition.attribute ?? ""}
onChange={(attribute) =>
onChange({
@@ -143,7 +147,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
}
/>
<InputNumber
label="Above"
label={langStore.get("ABOVE")}
value={condition.above ? Number(condition.above) : undefined}
onChange={(above) =>
onChange({
@@ -153,7 +157,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
}
/>
<InputNumber
label="Below"
label={langStore.get("BELOW")}
value={condition.below ? Number(condition.below) : undefined}
onChange={(below) =>
onChange({
@@ -163,7 +167,7 @@ export const NumericStateEditor: Editor<NumericCondition> = ({
}
/>
<InputYaml
label="Template"
label={langStore.get("TEMPLATE")}
value={condition.value_template ?? ""}
onChange={(value_template) =>
onChange({
@@ -221,6 +225,7 @@ export const StateEditor: Editor<StateCondition> = ({
onChange,
condition,
ha,
langStore,
}) => {
const restrictToDomain =
!condition.entity_id || condition.entity_id.length === 0
@@ -241,7 +246,7 @@ export const StateEditor: Editor<StateCondition> = ({
}
/>
<InputAutoComplete
label="Attribute"
label={langStore.get("ATTRIBUTE")}
value={condition.attribute ?? ""}
options={ha.entities.getAttributes(condition.entity_id)}
multiple={false}
@@ -253,11 +258,11 @@ export const StateEditor: Editor<StateCondition> = ({
}
/>
<InputText
label="State"
label={langStore.get("STATE")}
value={String(condition.state)}
placeholder={ha.entities
.getStates(condition.entity_id, condition.attribute)
.join(" or ")}
.join(` ${langStore.get("OR").toLowerCase()} `)}
onChange={(state) =>
onChange({
...condition,
@@ -280,7 +285,11 @@ export const StateEditor: Editor<StateCondition> = ({
};
type TimeEditorShows = "after" | "before" | "weekday";
export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
export const TimeEditor: Editor<TimeCondition> = ({
onChange,
condition,
langStore,
}) => {
const [shows, setShows] = useState<TimeEditorShows[]>(
Object.keys(condition).filter((k) =>
["after", "before", "weekday"].includes(k)
@@ -321,19 +330,19 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
<b className="label">{prettyName(show)}</b>
<InputAutoComplete
className="condition-node--time-editor--weekday"
label="Weekday"
label={langStore.get("WEEKDAY")}
value={condition.weekday ?? []}
multiple={true}
getID={(opt) => opt}
getLabel={(opt) => {
return {
mon: "Monday",
tue: "Tuesday",
wed: "Wednesday",
thu: "Thursday",
fri: "Friday",
sat: "Saturday",
sun: "Sunday",
mon: langStore.get("DAY_mon"),
tue: langStore.get("DAY_tue"),
wed: langStore.get("DAY_wed"),
thu: langStore.get("DAY_thu"),
fri: langStore.get("DAY_fri"),
sat: langStore.get("DAY_sat"),
sun: langStore.get("DAY_sun"),
}[opt];
}}
onChange={(weekday: any) =>
@@ -362,7 +371,7 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
{shows.length < 3 && (
<InputList
className="condition-node--time-editor--new"
label="Option"
label={langStore.get("OPTION")}
options={["after", "before", "weekday"].filter(
(k: any) => !shows.includes(k)
)}
@@ -378,11 +387,12 @@ export const TimeEditor: Editor<TimeCondition> = ({ onChange, condition }) => {
export const TriggerEditor: Editor<TriggerCondition> = ({
onChange,
condition,
langStore,
}) => {
return (
<>
<InputText
label="Trigger ID"
label={langStore.get("TRIGGER_ID")}
value={condition.id}
onChange={(id) =>
onChange({
@@ -395,11 +405,15 @@ export const TriggerEditor: Editor<TriggerCondition> = ({
);
};
export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => {
export const ZoneEditor: Editor<ZoneCondition> = ({
onChange,
condition,
langStore,
}) => {
return (
<>
<InputEntity
label="Zone"
label={langStore.get("ZONE")}
value={condition.zone ?? []}
multiple
onChange={(zone) =>
@@ -411,7 +425,7 @@ export const ZoneEditor: Editor<ZoneCondition> = ({ onChange, condition }) => {
restrictToDomain={["zone"]}
/>
<InputEntity
label="Entity with Location"
label={langStore.get("ENTITY_WITH_LOCATION")}
value={condition.entity_id}
multiple
onChange={(entity_id) =>
@@ -1,26 +1,22 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { MockPage, Page } from "components/Page";
import { useState } from "react";
import { AutomationCondition } from "types/automations/conditions";
import { ConditionEditor } from ".";
import { makeStory } from "devUtils";
export default {
title: "ConditionEditor",
component: ConditionEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
initialViewMode: "edit",
const { make, componentMeta } = makeStory({
Component: ConditionEditor,
meta: {
title: "ConditionEditor",
args: {
initialViewMode: "edit",
},
},
} as ComponentMeta<typeof ConditionEditor>;
const Template: ComponentStory<typeof ConditionEditor> = ({
condition,
...args
}) => {
const [data, setData] = useState(condition);
return (
<Page>
BaseTemplate: ({ condition, ...args }) => {
const [data, setData] = useState(condition);
return (
<ConditionEditor
{...args}
condition={data}
@@ -28,29 +24,28 @@ const Template: ComponentStory<typeof ConditionEditor> = ({
setData(data);
}}
/>
</Page>
);
};
);
},
});
export const TemplateViewer = Template.bind({});
TemplateViewer.args = {
export default componentMeta;
export const TemplateViewer = make({
condition: {
condition: "template",
value_template: "states('switch.light_kitchen') == 'on'",
} as AutomationCondition,
};
});
export const NumericStateViewer = Template.bind({});
NumericStateViewer.args = {
export const NumericStateViewer = make({
condition: {
condition: "numeric_state",
entity_id: "sensor.humidity_kitchen",
above: "10",
} as AutomationCondition,
};
});
export const LogicCondition = Template.bind({});
LogicCondition.args = {
export const LogicCondition = make({
condition: {
condition: "or",
conditions: [
@@ -81,9 +76,8 @@ LogicCondition.args = {
},
],
} as AutomationCondition,
};
export const TimeCondition = Template.bind({});
TimeCondition.args = {
});
export const TimeCondition = make({
condition: {
condition: "or",
conditions: [
@@ -104,7 +98,7 @@ TimeCondition.args = {
},
],
} as AutomationCondition,
};
});
export const MultipleConditions: ComponentStory<typeof ConditionEditor> = (
args
@@ -134,12 +128,12 @@ export const MultipleConditions: ComponentStory<typeof ConditionEditor> = (
],
});
return (
<Page>
<MockPage>
<ConditionEditor
onUpdate={setState}
onDelete={() => {}}
condition={state}
/>
</Page>
</MockPage>
);
};
@@ -1,46 +1,34 @@
import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { DAGGraphBoard } from ".";
import { Page } from "components/Page";
import { SimpleErrorElement } from "components/SimpleErrorElement";
export default {
title: "DAGGraph/Board",
component: DAGGraphBoard,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof DAGGraphBoard>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof DAGGraphBoard> = (args) => {
return (
<Page>
<DAGGraphBoard {...args} />
</Page>
);
};
const { make, componentMeta } = makeStory({
Component: DAGGraphBoard,
meta: {
title: "DAGGraph/Board",
},
});
export const Loading = Template.bind({});
Loading.args = {
...Loading.args,
export default componentMeta;
export const Example = make({});
export const Loading = make({
state: {
ready: false,
},
};
});
export const Errored = Template.bind({});
Errored.args = {
...Loading.args,
export const Errored = make({
state: {
ready: true,
data: {
error: <SimpleErrorElement error={new Error("Test")} />,
},
},
};
});
export const Empty = Template.bind({});
Empty.args = {
...Empty.args,
export const Empty = make({
state: {
ready: true,
data: {
@@ -50,11 +38,9 @@ Empty.args = {
},
},
},
};
});
export const Basic = Template.bind({});
Basic.args = {
...Basic.args,
export const Basic = make({
state: {
ready: true,
data: {
@@ -88,4 +74,4 @@ Basic.args = {
},
},
},
};
});
@@ -1,6 +1,6 @@
import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { MockPage } from "components/Page";
import { ButtonNode } from "./ButtonNode";
import { DAGGraphBoard } from "components/DAGGraph/board";
import { ButtonNodeMaker } from ".";
@@ -25,7 +25,7 @@ const Template: ComponentStory<typeof ButtonNode> = (args) => {
...args,
};
return (
<Page>
<MockPage>
<DAGGraphBoard
closeModal={() => {}}
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 { useConfirm } from "material-ui-confirm";
import { useSnackbar } from "notistack";
import { useLang } from "lang";
export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
({
@@ -27,6 +28,7 @@ export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
title,
children,
}) => {
const lang = useLang();
const color = convertNodeTypeToSequenceNodeColor(collectionType);
const nodeColor = useSequenceNodeColor(color);
const confirm = useConfirm();
@@ -55,14 +57,19 @@ export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
})
.then(() => {
onDelete();
snackbr.enqueueSnackbar("Deleted.", {
snackbr.enqueueSnackbar(lang.get("DELETED"), {
variant: "info",
});
})
.catch(() =>
snackbr.enqueueSnackbar(`Did not delete ${trueTile}.`, {
variant: "info",
})
snackbr.enqueueSnackbar(
lang.get("NOT_DELETED_THING", {
item: trueTile,
}),
{
variant: "info",
}
)
);
}}
borderless
@@ -1,7 +1,6 @@
import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { CollectionNode } from "./CollectionNode";
import { MockPage } from "components/Page";
import { DAGGraphBoard } from "components/DAGGraph/board";
import { CollectionNodeMaker } from "./index";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
@@ -19,7 +18,7 @@ type DemoProps = {
};
const Demo: FC<DemoProps> = (args) => {
return (
<Page>
<MockPage>
<DAGGraphBoard
closeModal={() => {}}
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) => {
return (
<Page>
<MockPage>
<DAGGraphBoard
closeModal={() => {}}
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) => {
return (
<Page>
<MockPage>
<DAGGraphBoard
closeModal={() => {}}
state={{
@@ -222,7 +221,7 @@ export const ReturnTarget: ComponentStory<typeof Demo> = (args) => {
},
}}
/>
</Page>
</MockPage>
);
};
@@ -123,7 +123,7 @@
position: absolute;
top: -1em;
left: -1em;
background-color: var(--mui-common-black);
background-color: var(--mui-background-paper);
border-color: var(--mui-grey-400);
border-style: solid;
border-width: 0.5px;
@@ -1,6 +1,6 @@
import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { MockPage } from "components/Page";
import { SequenceNode } from "./SequenceNode";
import { DAGGraphBoard } from "components/DAGGraph/board";
import { SequenceNodeMaker } from "./index";
@@ -21,7 +21,7 @@ export default {
const Template: ComponentStory<typeof SequenceNode> = (args) => {
return (
<Page>
<MockPage>
<DAGGraphBoard
closeModal={() => {}}
state={{
@@ -46,13 +46,13 @@ const Template: ComponentStory<typeof SequenceNode> = (args) => {
},
}}
/>
</Page>
</MockPage>
);
};
export const Colors: ComponentStory<typeof SequenceNode> = (args) => {
return (
<Page>
<MockPage>
<DAGGraphBoard
closeModal={() => {}}
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 { SequenceNodeElementProps } from "./types";
import { useSequenceNodeColor } from "./util";
import { useLang } from "lang";
export const SequenceNodeElement: FC<
PropsWithChildren<SequenceNodeElementProps>
@@ -35,6 +36,7 @@ export const SequenceNodeElement: FC<
isClosed,
setIsClosed,
}) => {
const langStore = useLang();
const confirm = useConfirm();
const snackbr = useSnackbar();
const nodeColor = useSequenceNodeColor(color);
@@ -89,18 +91,21 @@ export const SequenceNodeElement: FC<
<IconButton
onClick={() => {
confirm({
description: "Are you sure you want to delete this node?",
description: langStore.get("CONFIRMATION_DELETE_THIS_NODE"),
})
.then(() => {
onXClick();
snackbr.enqueueSnackbar("Deleted.", {
snackbr.enqueueSnackbar(langStore.get("DELETED"), {
variant: "info",
});
})
.catch(() =>
snackbr.enqueueSnackbar("Did not delete node.", {
variant: "info",
})
snackbr.enqueueSnackbar(
langStore.get("NOT_DELETED_NODE"),
{
variant: "info",
}
)
);
}}
size="small"
+11 -4
View File
@@ -8,6 +8,7 @@ import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { cleanUpUndefined } from "utils/helpers";
import { DeviceBaseType, DeviceTypeCapability } from "haService/types";
import { AutomationDeviceState } from "types/automations/common";
import { useLang } from "lang";
export type DeviceEditorProps<DBT extends DeviceBaseType> = {
type: "action" | "condition" | "trigger";
@@ -23,6 +24,8 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
caps,
options,
}: DeviceEditorProps<DBT>) {
// state
const langStore = useLang();
// aliases
const update = (upd: Partial<AutomationDeviceState & Record<string, any>>) =>
setState(
@@ -40,13 +43,13 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
<>
<InputDevice
key="devices"
label="Device"
label={langStore.get("DEVICE")}
value={state.device_id ?? ""}
onChange={(device_id) => setState({ device_id: device_id ?? "" })}
/>
<InputAutoComplete
key="action"
label="Action"
label={langStore.get("ACTION")}
multiple={false}
value={actionId}
options={Object.keys(options).map((k) => options[k])}
@@ -67,7 +70,7 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
{entities.length > 0 && (
<InputEntity
key={"entities" + state.device_id}
label="Entity"
label={langStore.get("ENTITY")}
value={state.entity_id ?? ""}
multiple={false}
onChange={(entity_id) =>
@@ -85,7 +88,11 @@ export function DeviceEditor<DBT extends DeviceBaseType>({
/>
)}
{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 { ComponentMeta, ComponentStory } from '@storybook/react';
import { ErrorBoundary } from ".";
import { Page } from "components/Page";
import { makeStory } from "devUtils";
import { MockPage } from "components/Page";
import { ComponentStory } from "@storybook/react";
export default {
title: 'ErrorBoundary',
const { make, componentMeta } = makeStory({
Component: () => <div>Example</div>,
meta: {
title: "ErrorBoundary",
component: ErrorBoundary,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {
}
} as ComponentMeta<typeof ErrorBoundary>
},
});
export const ErrorThrown: ComponentStory<typeof ErrorBoundary> = args => {
const BadComponent: FC = () => {
throw new Error("!!!")
}
return <Page>
<ErrorBoundary>
<BadComponent />
</ErrorBoundary>
</Page>
}
export default componentMeta;
export const Example = make({});
export const NoError: ComponentStory<typeof ErrorBoundary> = args => {
const GoodComponent: FC = () => {
return <span>All Good.</span>
}
return <Page>
<ErrorBoundary>
<GoodComponent />
</ErrorBoundary>
</Page>
}
export const ErrorThrown: ComponentStory<typeof ErrorBoundary> = (args) => {
const BadComponent: FC = () => {
throw new Error("!!!");
};
return (
<MockPage>
<ErrorBoundary>
<BadComponent />
</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 Tooltip from "@mui/material/Tooltip";
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 = {
icon: ReactNode;
@@ -10,21 +12,31 @@ export type ButtonIconProps = {
disabled?: boolean;
color?: IconButtonTypeMap["props"]["color"];
borderless?: boolean;
titleSlug?: string;
titleParams?: Record<string, string>;
};
export const ButtonIcon: FC<ButtonIconProps> = (props) => {
const langStore = useLang();
return (
<MuiIconButton
className={[
"icon-button",
props.className ?? "",
props.borderless ? "borderless" : "",
].join(" ")}
onClick={props.onClick}
title={props.title}
color={props.color}
disabled={props.disabled}
<Tooltip
title={
props.titleSlug ? langStore.get(props.titleSlug, props.titleParams) : ""
}
describeChild
>
{props.icon}
</MuiIconButton>
<IconButton
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,
} from ".";
import { ButtonIcon } from "./ButtonIcons";
import { Page } from "components/Page";
import { MockPage } from "components/Page";
export default {
title: "Icons",
@@ -21,7 +21,7 @@ export default {
export const IconList: ComponentStory<typeof IconBase> = (args) => {
return (
<Page>
<MockPage>
<PencilIcon {...args} />
<CheckMarkIcon {...args} />
<AddIcon {...args} />
@@ -29,7 +29,7 @@ export const IconList: ComponentStory<typeof IconBase> = (args) => {
<InfoIcon {...args} />
<ZoomIcon {...args} />
<GearIcon {...args} />
</Page>
</MockPage>
);
};
IconList.args = {
@@ -39,9 +39,9 @@ IconList.args = {
export const ButtonIconExample: ComponentStory<typeof IconBase> = (args) => {
return (
<Page>
<MockPage>
<ButtonIcon icon={<ArrowIcon {...args} />} />
</Page>
</MockPage>
);
};
ButtonIconExample.args = {
@@ -1,36 +1,39 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { InputDevice } from "./InputDevice";
export default {
title: 'Inputs/InputDevice',
component: InputDevice,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputDevice>;
import { makeStory } from "devUtils";
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 => {
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,
export const Single = make({
multiple: false,
value: 'sensor.humidity_bathroom'
} as any
value: "sensor.humidity_bathroom",
});
@@ -1,84 +1,77 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { InputEntity } from "./InputEntities";
export default {
title: 'Inputs/InputEntity',
component: InputEntity,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputEntity>;
import { makeStory } from "devUtils";
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 => {
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,
export const Single = make({
multiple: false,
value: 'sensor.bathroom'
} as any
value: "sensor.bathroom",
});
export const Many = Template.bind({})
Many.args = {
...Many.args,
export const Many = make({
multiple: true,
value: ['sensor.bathroom', 'person.ari']
} as any
value: ["sensor.bathroom", "person.ari"],
});
export const ManyEmpty = Template.bind({})
ManyEmpty.args = {
...ManyEmpty.args,
export const ManyEmpty = make({
multiple: true,
value: []
} as any
value: [],
});
export const ManyButGotSingle = Template.bind({})
ManyButGotSingle.args = {
...ManyButGotSingle.args,
export const ManyButGotSingle = make({
multiple: true,
value: 'sensor.bathroom'
} as any
value: "sensor.bathroom",
});
export const InvalidDomain = Template.bind({})
InvalidDomain.args = {
...InvalidDomain.args,
export const InvalidDomain = make({
multiple: true,
value: 'sensor.bathroom',
restrictToDomain: ['zone'],
} as any
value: "sensor.bathroom",
restrictToDomain: ["zone"],
});
export const InvalidManyDomain = Template.bind({})
InvalidManyDomain.args = {
...InvalidManyDomain.args,
export const InvalidManyDomain = make({
multiple: true,
value: 'sensor.bathroom',
restrictToDomain: ['zone', 'switch'],
} as any
value: "sensor.bathroom",
restrictToDomain: ["zone", "switch"],
});
export const InvalidLots = Template.bind({})
InvalidLots.args = {
...InvalidLots.args,
export const InvalidLots = make({
multiple: true,
value: ['person.ari', 'sensor.bathroom', 'binary_sensor.ping_tv', 'device_tracker.phone'],
restrictToDomain: ['zone', 'switch'],
} as any
value: [
"person.ari",
"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 { InputService } from "./InputService";
export default {
title: 'Inputs/InputService',
component: InputService,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {}
} as ComponentMeta<typeof InputService>;
import { makeStory } from "devUtils";
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 => {
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,
export const Single = make({
multiple: false,
value: ''
} as any
value: "",
});
@@ -1,19 +1,17 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { InputTimeEntity } from "./InputTimeEntity";
export default {
title: "Inputs/InputTimeEntity",
component: InputTimeEntity,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof InputTimeEntity>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof InputTimeEntity> = (args) => {
const [value, setValue] = useState("");
return (
<Page>
const { make, componentMeta } = makeStory({
Component: InputTimeEntity,
meta: {
title: "Inputs/InputTimeEntity",
},
BaseTemplate: (args) => {
const [value, setValue] = useState("");
return (
<div
style={{
padding: "1em",
@@ -28,8 +26,8 @@ const Template: ComponentStory<typeof InputTimeEntity> = (args) => {
}}
/>
</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";
export default {
title: "Inputs/Extras/SearchItem",
component: SearchItem,
parameters: { actions: { argTypesRegex: "^on.*" } },
argTypes: {},
} as ComponentMeta<typeof SearchItem>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof SearchItem> = (args) => {
return (
<Page>
const { make, componentMeta } = makeStory({
Component: SearchItem,
meta: {
title: "Inputs/Extras/SearchItem",
},
BaseTemplate: (args) => {
return (
<div
style={{
width: "15em",
@@ -22,15 +18,16 @@ const Template: ComponentStory<typeof SearchItem> = (args) => {
>
<SearchItem {...args} />
</div>
</Page>
);
};
);
},
});
export const Simple = Template.bind({});
Simple.args = {
export default componentMeta;
export const Simple = make({
id: "sensor.humidity_main_bedroom",
label: "Main Bedroom Humidity",
searchTerm: "bedroom",
listProps: {},
onlyShowLabel: false,
};
});
@@ -4,24 +4,30 @@ import { useState } from "react";
import InputBoolean from "./InputBoolean";
export default {
title: 'Inputs/InputBoolean',
component: InputBoolean,
parameters: { actions: { argTypesRegex: '^on.*' } },
} as ComponentMeta<typeof InputBoolean>;
import { makeStory } from "devUtils";
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 => {
const [state, onChange] = useState(args.value)
return <Page>
<InputBoolean {...args} value={state} onChange={v => {
args.onChange(v)
onChange(v)
}} />
</Page>
}
export const SimpleText = Template.bind({})
SimpleText.args = {
label: "Template",
}
export default componentMeta;
export const Example = make({});
@@ -1,32 +1,31 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import InputNumber from "./InputNumber";
export default {
title: 'Inputs/InputNumber',
component: InputNumber,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {
label: {
defaultValue: 'Sample Title'
}
}
} as ComponentMeta<typeof InputNumber>;
import { makeStory } from "devUtils";
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)
return <Page>
<InputNumber {...args} value={value} onChange={setValue} />
</Page>
}
export const SomeStuffAtStart: ComponentStory<typeof InputNumber> = args => {
export const NullStart = make({
value: undefined,
});
const [value, setValue] = useState<number | undefined>(10)
return <Page>
<InputNumber {...args} value={value} onChange={setValue} />
</Page>
}
export const SomeStuffAtStart = make({
value: 10,
});
@@ -4,22 +4,21 @@ import { useState } from "react";
import InputText from "./InputText";
export default {
title: 'Inputs/InputText',
component: InputText,
parameters: { actions: { argTypesRegex: '^on.*' } },
} as ComponentMeta<typeof InputText>;
import { makeStory } from "devUtils";
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('')
return <Page>
<InputText {...args} value={value} onChange={setValue} />
</Page>
}
export const SimpleText = Template.bind({})
SimpleText.args = {
export const SimpleText = make({
label: "Entity ID",
}
});
@@ -1,20 +1,15 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import { AutomationTime } from "types/automations/common";
import { InputTime } from "./InputTime";
export default {
title: "Inputs/InputTime",
component: InputTime,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof InputTime>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof InputTime> = (args) => {
const [value, setValue] = useState<AutomationTime | undefined>(undefined);
return (
<Page>
const { make, componentMeta } = makeStory({
Component: InputTime,
BaseTemplate: (args) => {
const [value, setValue] = useState<AutomationTime | undefined>(undefined);
return (
<div
style={{
padding: "1em",
@@ -29,12 +24,17 @@ const Template: ComponentStory<typeof InputTime> = (args) => {
}}
/>
</div>
</Page>
);
};
);
},
meta: {
title: "Inputs/InputTime",
},
});
export const SimpleText = Template.bind({});
SimpleText.args = {
export default componentMeta;
export const Example = make({});
export const SimpleText = make({
label: "Time Stamp",
value: "10",
};
});
@@ -4,24 +4,24 @@ import { useState } from "react";
import InputYaml from "./InputYaml";
export default {
title: 'Inputs/InputYaml',
component: InputYaml,
parameters: { actions: { argTypesRegex: '^on.*' } },
} as ComponentMeta<typeof InputYaml>;
import { makeStory } from "devUtils";
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({
"test": "data"
})
return <Page>
<InputYaml {...args} value={value} onChange={setValue} />
</Page>
}
export const SimpleText = Template.bind({})
SimpleText.args = {
export const SimpleText = make({
label: "Template",
}
});
@@ -9,6 +9,7 @@ import FormHelperText from "@mui/material/FormHelperText";
import InputAdornment from "@mui/material/InputAdornment";
import { Save } from "@mui/icons-material";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
export interface Props<T extends {}> {
label: string;
@@ -34,6 +35,7 @@ export default function InputYaml<T extends {}>({
helperText,
endAdornment,
}: Props<T>) {
const langStore = useLang();
const originalText = yaml.dump(value);
const [{ text, error }, setState] = useState<{
text: string;
@@ -48,7 +50,7 @@ export default function InputYaml<T extends {}>({
yaml.load(t);
setState({ text: t, error: undefined });
} catch (_) {
setState({ text: t, error: "! Invalid Yaml !" });
setState({ text: t, error: langStore.get("ERROR_INVALID_YAML") });
}
};
const onSave = () => {
@@ -94,7 +96,9 @@ export default function InputYaml<T extends {}>({
<ButtonIcon
disabled={!hasChanged}
onClick={() => onSave()}
title={!!error ? "Invalid YAML" : hasChanged ? "Save" : ""}
title={
!!error ? "Invalid YAML" : hasChanged ? langStore.get("SAVE") : ""
}
icon={
<Save
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";
export default {
title: "Inputs/InputAutoText",
component: InputAutoText,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
label: "Something",
value: "",
options: ["test", "usa", "canada"],
import { makeStory } from "devUtils";
const { make, componentMeta } = makeStory({
Component: InputAutoText,
meta: {
title: "Inputs/InputAutoText",
args: {
label: "Something",
value: "",
options: ["test", "usa", "canada"],
},
},
} as ComponentMeta<typeof InputAutoText>;
});
const Template: ComponentStory<typeof InputAutoText> = (args) => {
return (
<Page>
<InputAutoText {...args} />
</Page>
);
};
export default componentMeta;
export const Example = make({});
export const Basic = Template.bind({});
export const WithError = Template.bind({});
WithError.args = {
...WithError.args,
export const WithError = make({
error: "Oh no!",
};
});
@@ -1,47 +1,35 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState, useEffect } from 'react';
import { useState, useEffect } from "react";
import { InputList } from "./InputList";
export default {
title: 'Inputs/InputList',
component: InputList,
parameters: { actions: { argTypesRegex: '^on.*' } },
} as ComponentMeta<typeof InputList>;
import { makeStory } from "devUtils";
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);
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 = {
export const SimpleText = make({
label: "Entity ID",
options: [
'Bob',
'Martin',
"Toots"
]
}
options: ["Bob", "Martin", "Toots"],
});
export const InvalidSelection = Template.bind({})
InvalidSelection.args = {
export const InvalidSelection = make({
current: "Derek",
label: "Entity ID",
options: [
'Bob',
'Martin',
"Toots"
]
}
options: ["Bob", "Martin", "Toots"],
});
+17 -1
View File
@@ -7,6 +7,7 @@ import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import { prettyName } from "utils/formatting";
import { ReactNode } from "react";
import { useLang } from "lang";
export type Props<T extends string | Object> = {
current?: T;
@@ -17,6 +18,7 @@ export type Props<T extends string | Object> = {
className?: string;
prettyOptionLabels?: boolean;
getKey?: (n: T) => string;
getLabel?: (n: T) => string;
getDescription?: (n: T) => string;
placeholder?: any;
title?: string;
@@ -34,6 +36,7 @@ export function InputList<T extends string | Object>({
className,
prettyOptionLabels = true,
getKey = String,
getLabel: _getLabel,
getDescription,
placeholder,
title,
@@ -42,8 +45,17 @@ export function InputList<T extends string | Object>({
disabled,
fullWidth = true,
}: Props<T>) {
const langStore = useLang();
const invalidCurrent =
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 (
<FormControl
className={className}
@@ -73,7 +85,11 @@ export function InputList<T extends string | Object>({
>
{options.map((t, i) => (
<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 && (
<>
<br />
@@ -1,24 +1,19 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useEffect, useState } from "react";
import InputMultiSelect from "./InputMultiSelect";
export default {
title: "Inputs/InputMultiSelect",
component: InputMultiSelect,
parameters: { actions: { argTypesRegex: "^on.*" } },
} as ComponentMeta<typeof InputMultiSelect>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof InputMultiSelect> = (args) => {
const [value, setValue] = useState<number[]>(args.selected);
const { make, componentMeta } = makeStory({
Component: InputMultiSelect,
BaseTemplate: (args) => {
const [value, setValue] = useState<number[]>(args.selected);
useEffect(() => {
setValue(args.selected);
}, [args.selected]);
useEffect(() => {
setValue(args.selected);
}, [args.selected]);
return (
<Page>
return (
<InputMultiSelect
{...args}
onChange={(a) => {
@@ -28,14 +23,18 @@ const Template: ComponentStory<typeof InputMultiSelect> = (args) => {
options={args.options}
selected={value}
/>
</Page>
);
};
);
},
meta: {
title: "Inputs/InputMultiSelect",
},
});
export const Simple = Template.bind({});
Simple.args = {
export default componentMeta;
export const Simple = make({
label: "Room Tags",
options: ["Bears", "Cats", "Kitchen", "Bathroom"],
selected: [1],
max: 2,
};
});
@@ -5,6 +5,7 @@ import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
import Checkbox from "@mui/material/Checkbox";
import { useSnackbar } from "notistack";
import { useLang } from "lang";
export interface Props<T extends string> {
label: string;
@@ -23,6 +24,7 @@ export default function InputMultiSelect<T extends string>({
max = 3,
}: Props<T>) {
// alias
const langStore = useLang();
const snackbr = useSnackbar();
return (
<Autocomplete
@@ -31,10 +33,13 @@ export default function InputMultiSelect<T extends string>({
value={selected.map((i) => options[i])}
onChange={(_, newValues: T[] = []) => {
if (newValues.length > max) {
snackbr.enqueueSnackbar("Can only select up to 3 tags", {
variant: "warning",
autoHideDuration: 1500,
});
snackbr.enqueueSnackbar(
langStore.get("VALIDATION_MAX_TAG_SELECTION", { count: "3" }),
{
variant: "warning",
autoHideDuration: 1500,
}
);
}
onChange(
newValues
@@ -1,58 +1,49 @@
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useState } from "react";
import InputTextBubble from "./InputTextBubble";
export default {
title: 'Inputs/InputTextBubble',
component: InputTextBubble,
parameters: { actions: { argTypesRegex: '^on.*' } },
argTypes: {
label: {
defaultValue: 'Sample Title'
}
}
} as ComponentMeta<typeof InputTextBubble>;
import { makeStory } from "devUtils";
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'])
return <Page>
<div style={{ maxWidth: '200px', overflow: 'hidden' }}>
<InputTextBubble {...args} value={value} onChange={setValue} />
</div>
</Page>
}
export const ArrayText = make({
value: ["wow", "lots of bubbles", "itchen", "bathroom"],
});
export const JustText = make({
value: "hello",
});
export const JustText: ComponentStory<typeof InputTextBubble> = args => {
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,
export const ManyOptions = make({
value: "hello",
options: [
'sensor.humidity_bathroom',
'sensor.humidity_bedroom',
'sensor.humidity_laundry',
'sensor.temp_bathroom',
'sensor.temp_bedroom',
'switch.living_room',
'switch.bathroom',
'light.bedroom_main',
'light.bedroom_second',
]
}
"sensor.humidity_bathroom",
"sensor.humidity_bedroom",
"sensor.humidity_laundry",
"sensor.temp_bathroom",
"sensor.temp_bedroom",
"switch.living_room",
"switch.bathroom",
"light.bedroom_main",
"light.bedroom_second",
],
});
@@ -4,17 +4,11 @@ import InputText from "./Base/InputText";
import { InputTextView } from "./InputTextView";
export default {
title: "Inputs/InputTextView",
component: InputTextView,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {
value: "example",
},
} as ComponentMeta<typeof InputTextView>;
import { makeStory } from "devUtils";
export const Basic: ComponentStory<typeof InputTextView> = (args) => (
<Page>
const { make, componentMeta } = makeStory({
Component: InputTextView,
BaseTemplate: (args) => (
<div
style={{
display: "flex",
@@ -26,5 +20,15 @@ export const Basic: ComponentStory<typeof InputTextView> = (args) => (
<InputTextView {...args} />
<InputText {...args} />
</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 ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip";
import { useLang } from "lang";
export type InputTextViewProps = {
className?: string;
@@ -12,11 +14,15 @@ export type InputTextViewProps = {
initialViewMode?: boolean;
placeholder?: string;
disabled?: boolean;
borderless?: boolean;
titleSlug?: string;
titleParams?: Record<string, string>;
};
export const InputTextView: FC<PropsWithChildren<InputTextViewProps>> = (
props
) => {
const langStore = useLang();
const [viewMode, setViewMode] = useState(props.initialViewMode ?? true);
const [text, setText] = useState(props.value);
const className = [
@@ -27,24 +33,33 @@ export const InputTextView: FC<PropsWithChildren<InputTextViewProps>> = (
if (viewMode) {
return (
<div
className={className}
onClick={() => !props.disabled && setViewMode(false)}
<Tooltip
title={
props.titleSlug
? langStore.get(props.titleSlug, props.titleParams)
: ""
}
describeChild
>
{!!props.value ? (
<div className="input-text-view--text text-ellipsis">
<span>{props.value}</span>
</div>
) : (
<div className="input-text-view--text input-text-view--placeholder text-ellipsis">
<span>{props.placeholder}</span>
</div>
)}
{!props.disabled && (
<ModeEditOutlineOutlinedIcon className="input-text-view--edit" />
)}
{props.children}
</div>
<div
className={className}
onClick={() => !props.disabled && setViewMode(false)}
>
{!!props.value ? (
<div className="input-text-view--text text-ellipsis">
<span>{props.value}</span>
</div>
) : (
<div className="input-text-view--text input-text-view--placeholder text-ellipsis">
<span>{props.placeholder}</span>
</div>
)}
{!props.disabled && (
<ModeEditOutlineOutlinedIcon className="input-text-view--edit" />
)}
{props.children}
</div>
</Tooltip>
);
} else {
return (
+3 -2
View File
@@ -9,14 +9,15 @@ export interface ModalStyleProps {
}
export interface Props extends ModalStyleProps {
children: ReactNode;
className?: string;
}
export const Modal: FC<Props> = ({ children, open }) => {
export const Modal: FC<Props> = ({ children, open, className }) => {
const { isMobile } = useWindowSize();
return (
<MuiModal open={open}>
<div className={["modal--root", isMobile ? "mobile" : ""].join(" ")}>
<Card variant="outlined">
<CardContent>{children}</CardContent>
<CardContent className={className}>{children}</CardContent>
</Card>
</div>
</MuiModal>
@@ -13,6 +13,7 @@ import { getDescriptionFromAutomationNode } from "utils/formatting";
import { useHA } from "haService";
import { Generic } from "./Generic";
import { getNodeTypeAndValidate } from "utils/automations";
import { useLang } from "lang";
type UseState = <S>(s: S) => [S, Dispatch<SetStateAction<S>>];
@@ -23,6 +24,7 @@ export const useEditorNodeState = (
uState: UseState = useState
) => {
// state
const langStore = useLang();
const [allState, setAllState] = uState({
yamlMode: false,
isModified: false,
@@ -77,7 +79,9 @@ export const useEditorNodeState = (
isErrored: allState.isErrored,
get prettyNodeType() {
if (nodeType) {
return `${nodeType.slice(0, 1).toUpperCase()}${nodeType.slice(1)} Type`;
return `${langStore.get(nodeType.toUpperCase())} ${langStore.get(
"TYPE"
)}`;
} else {
return "n/a";
}
@@ -100,7 +104,7 @@ export const useEditorNodeState = (
aliasEditor = (
<InputText
key="alias"
label="Trigger ID"
label={langStore.get("TRIGGER_ID")}
value={(allState.node as any).id}
onChange={(id) =>
setState({
@@ -115,7 +119,7 @@ export const useEditorNodeState = (
aliasEditor = (
<InputText
key="alias"
label="Alias"
label={langStore.get("ALIAS")}
value={getDescriptionFromAutomationNode(
allState.node,
ha.namer,
@@ -2,11 +2,10 @@ import React from "react";
import { ComponentStory } from "@storybook/react";
import { NodeEditor, NodeEditorProps } from ".";
import { AutomationCondition } from "types/automations/conditions";
import { Button } from "components/Inputs/Buttons/Button";
import { useState } from "react";
import { Modal } from "components/Modal";
import { Page } from "components/Page";
import { MockPage } from "components/Page";
import { makeStory } from "devUtils";
const { componentMeta, make } = makeStory({
@@ -23,16 +22,14 @@ const { componentMeta, make } = makeStory({
Component: (props: NodeEditorProps) => {
const [state, setState] = useState(props.node);
return (
<Page>
<NodeEditor
{...props}
node={state}
onSave={(s) => {
setState(s);
props.onSave && props.onSave(s);
}}
/>
</Page>
<NodeEditor
{...props}
node={state}
onSave={(s) => {
setState(s);
props.onSave && props.onSave(s);
}}
/>
);
},
});
@@ -77,12 +74,12 @@ export const DeviceTriggerExample = make({
export const InAModal: ComponentStory<typeof NodeEditor> = (props) => {
const [open, setOpen] = useState(false);
return (
<Page>
<MockPage>
<Button onClick={() => setOpen(!open)}>Open Editor</Button>
<Modal open={open}>
<NodeEditor {...props} onClose={() => setOpen(!open)} />
</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 { useConfirm } from "material-ui-confirm";
import { getNodeSubTypeDescription } from "./utils";
import { useLang } from "lang";
export interface NodeEditorProps {
node: AutomationNode;
@@ -29,6 +30,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
children,
}) => {
// state
const langStore = useLang();
const state = useEditorNodeState(node, allowedTypes, saveBtnCreateText);
const confirm = useConfirm();
@@ -41,19 +43,19 @@ export const NodeEditor: FC<NodeEditorProps> = ({
) => {
const notes: string[] = [];
if (!isReady) {
notes.push("This node is missing some values");
notes.push(langStore.get("VALIDATION_MISSING_VALUES_FOR_NODE"));
}
if (state.isErrored) {
notes.push("This node contains errors");
notes.push(langStore.get("VALIDATION_ERROR_VALUES_IN_NODE"));
}
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) {
try {
await confirm({
confirmationText: "Yes",
title: `Are you sure you want to ${what}?`,
title: langStore.get("CONFIRM_EXIT", { what }),
description: (
<ul>
{notes.map((n, i) => (
@@ -85,11 +87,11 @@ export const NodeEditor: FC<NodeEditorProps> = ({
<div className="node-editor--body-title">
{allowedTypes.length > 1 ? (
<InputList
label="Type"
label={langStore.get("TYPE")}
current={state.nodeType}
options={allowedTypes}
onChange={state.setNodeType}
prettyOptionLabels
prettyOptionLabels={false}
/>
) : (
<></>
@@ -101,7 +103,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
getDescription={getNodeSubTypeDescription}
options={state.subTypes}
onChange={state.setSubType}
prettyOptionLabels
prettyOptionLabels={false}
/>
) : (
<></>
@@ -115,7 +117,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
/>
<InputBoolean
className="enabled-flag"
label="Enabled"
label={langStore.get("ENABLED")}
value={state.data.enabled ?? true}
onChange={state.setEnabled}
/>
@@ -140,9 +142,11 @@ export const NodeEditor: FC<NodeEditorProps> = ({
onClick={() =>
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>
{children}
</div>
+7
View File
@@ -7,6 +7,8 @@
overflow: hidden;
max-width: 100vw;
max-height: 100vh;
min-width: 100vw;
min-height: 100vh;
/* font */
font-size: 16px;
@@ -15,4 +17,9 @@
/* background */
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 { createRef, FC, ReactNode, useEffect, useRef } from "react";
import { createRef, FC, PropsWithChildren, useEffect, useRef } from "react";
import {
createTheme,
Palette,
@@ -7,23 +7,21 @@ import {
ThemeProvider,
useTheme,
} from "@mui/material/styles";
import { VersionBox } from "components/VersionBox";
import { BottomBar } from "components/BottomBar";
import { SnackbarKey, SnackbarProvider, useSnackbar } from "notistack";
import Button from "@mui/material/Button";
import { useHAConnection } from "haService/connection";
import { ConfirmProvider } from "material-ui-confirm";
import { Color } from "@mui/material";
import useWindowSize from "utils/useWindowSize";
import { ApiService } from "apiService/core";
import { ApiStateProvider, useMockApiService } from "apiService";
const theme = createTheme({
palette: {
mode: "dark",
},
});
export type PageProps = PropsWithChildren<{
api: ApiService;
}>;
export const InternalPage: FC<{
children: ReactNode;
}> = ({ children }) => {
export const InternalPage: FC<PageProps> = ({ children, api }) => {
const conn = useHAConnection();
const theme = useTheme();
const snackbar = useSnackbar();
@@ -62,25 +60,31 @@ export const InternalPage: FC<{
}, [conn, snackbar]);
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>
{`:root {
${convertPaletteToCss(theme.palette)}
}`}
</style>
<VersionBox />
{children}
</main>
);
};
export const Page: FC<{
children: ReactNode;
}> = ({ children }) => {
export const Page: FC<PageProps> = (props) => {
const notistackRef = createRef<any>();
const onClickDismiss = (key: SnackbarKey) => () => {
notistackRef.current.closeSnackbar(key);
};
const theme = createTheme({
palette: {
mode: props.api.state.theme,
},
});
return (
<ThemeProvider theme={theme}>
<ConfirmProvider>
@@ -96,13 +100,20 @@ export const Page: FC<{
dense
preventDuplicate
>
<InternalPage>{children}</InternalPage>
<ApiStateProvider value={props.api.state}>
<InternalPage {...props} />
</ApiStateProvider>
</SnackbarProvider>
</ConfirmProvider>
</ThemeProvider>
);
};
export const MockPage: FC<PropsWithChildren<{}>> = (props) => {
const api = useMockApiService([]);
return <Page api={api} {...props} />;
};
export const convertPaletteToCss = (p: Palette): string => {
let out = ``;
for (const k of [
@@ -1,21 +1,15 @@
import React, { FC, useEffect, useState } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import React, { useState } from "react";
import { ServiceEditor } from ".";
import { TypedHassService } from "haService/fieldTypes";
import InputYaml from "components/Inputs/Base/InputYaml";
export default {
title: "Services/ServiceEditor",
component: ServiceEditor,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof ServiceEditor>;
import { makeStory } from "devUtils";
const Template: ComponentStory<typeof ServiceEditor> = (props) => {
const [state, setState] = useState(props.data);
return (
<Page>
const { make, componentMeta } = makeStory({
Component: ServiceEditor,
BaseTemplate: (props) => {
const [state, setState] = useState(props.data);
return (
<div
style={{
maxHeight: "99vh",
@@ -63,22 +57,24 @@ const Template: ComponentStory<typeof ServiceEditor> = (props) => {
/>
</div>
</div>
</Page>
);
};
);
},
meta: {
title: "Services/ServiceEditor",
},
});
const makeExample = (service: TypedHassService) => {
const Eg = Template.bind({});
Eg.args = {
...Eg,
export default componentMeta;
export const Example = make({});
const makeExample = (service: TypedHassService) =>
make({
service,
data: {
target: {},
field: {},
},
};
return Eg;
};
});
export const NumberSetValue = makeExample({
name: "Set",
@@ -6,26 +6,27 @@ import SettingsApplicationsIcon from "@mui/icons-material/SettingsApplications";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { DeleteForeverOutlined } from "@mui/icons-material";
import EditIcon from "@mui/icons-material/Edit";
import { makeStory } from "devUtils";
export default {
title: "Nav/SpeedDial",
component: SpeedDial,
};
const { make, componentMeta } = makeStory({
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> = () => {
return (
<Page>
<div
style={{
maxWidth: "10em",
maxHeight: "10em",
}}
>
<SpeedDial icon={<SettingsApplicationsIcon />}>
<ButtonIcon icon={<DeleteForeverOutlined />} />
<ButtonIcon icon={<EditIcon />} />
</SpeedDial>
</div>
</Page>
);
};
export default componentMeta;
export const IconList = make({});
@@ -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 { Page } from "components/Page";
import { ComponentProps, JSXElementConstructor } from "react";
import { ApiService } from "apiService/core";
import { useConnectedApiService, useMockApiService } from "apiService";
export type MakeStoryArgs<
T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>
@@ -9,6 +11,7 @@ export type MakeStoryArgs<
Component: T;
BaseTemplate?: ComponentStory<T>;
meta: Partial<ComponentMeta<T>> & { title: string };
useLiveApi?: boolean;
};
export const makeStory = <
T extends keyof JSX.IntrinsicElements | JSXElementConstructor<any>
@@ -16,6 +19,7 @@ export const makeStory = <
BaseTemplate,
Component,
meta,
useLiveApi = false,
}: MakeStoryArgs<T>) => {
const componentMeta: ComponentMeta<T> = {
component: Component as any,
@@ -24,8 +28,15 @@ export const makeStory = <
...meta,
};
const Template: ComponentStory<T> = (args) => {
let api: ApiService;
if (useLiveApi) {
api = useConnectedApiService();
} else {
api = useMockApiService([]);
}
return (
<Page>
<Page api={api}>
{BaseTemplate ? <BaseTemplate {...args} /> : <Component {...args} />}
</Page>
);
+10 -13
View File
@@ -78,17 +78,14 @@ const Test: FC = () => {
);
};
export default {
title: "Services/HA Service",
component: Test,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof Test>;
import { makeStory } from "devUtils";
export const AutomationCall: ComponentStory<typeof Test> = (props) => {
return (
<Page>
<Test {...props} />
</Page>
);
};
const { make, componentMeta } = makeStory({
Component: Test,
meta: {
title: "Services/HA Service",
},
});
export default componentMeta;
export const AutomationCall = make({});
+9 -15
View File
@@ -1,8 +1,7 @@
import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useHADeviceRegistry } from "haService";
import InputYaml from "components/Inputs/Base/InputYaml";
import { makeStory } from "devUtils";
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
const conn = useHADeviceRegistry();
@@ -35,17 +34,12 @@ const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
return <code>Loading...</code>;
};
export default {
title: "Services/Device Registry",
component: Test,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof Test>;
const { make, componentMeta } = makeStory({
Component: Test,
meta: {
title: "Services/Device Registry",
},
});
export const Base: ComponentStory<typeof Test> = (props) => {
return (
<Page>
<Test {...props} />
</Page>
);
};
export default componentMeta;
export const Basic = make({});
+3 -3
View File
@@ -1,6 +1,6 @@
import React, { FC, useState } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { MockPage } from "components/Page";
import { useHAEntities } from "haService/HAEntities";
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
@@ -50,8 +50,8 @@ export default {
export const Base: ComponentStory<typeof Test> = (props) => {
return (
<Page>
<MockPage>
<Test {...props} />
</Page>
</MockPage>
);
};
+3 -3
View File
@@ -1,6 +1,6 @@
import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { MockPage } from "components/Page";
import { useHAEntityRegistry } from "haService";
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
@@ -43,8 +43,8 @@ export default {
export const Base: ComponentStory<typeof Test> = (props) => {
return (
<Page>
<MockPage>
<Test {...props} />
</Page>
</MockPage>
);
};
+23 -7
View File
@@ -12,6 +12,7 @@ import { TypedHassService } from "./fieldTypes";
import { Option } from "components/Inputs/AutoComplete/InputAutoComplete";
import { getDeviceExtraWsCalls } from "./extras";
import { useHAEntities } from "./HAEntities";
import { useLang } from "lang";
export type ServiceOption = Option<{
domain: string;
@@ -137,6 +138,7 @@ export const useHAEntityRegistry = () => {
export type HAService = ReturnType<typeof useHA>;
export const useHA = () => {
const langStore = useLang();
const entities = useHAEntities();
const devices = useHADeviceRegistry();
const services = useHAServices();
@@ -158,9 +160,14 @@ export const useHA = () => {
target,
service_data: data,
});
snackbr.enqueueSnackbar(`Successfully called ${domain}.${service}`, {
variant: "success",
});
snackbr.enqueueSnackbar(
langStore.get("INFO_SUCCESS_CALL", {
entityId: `${domain}.${service}`,
}),
{
variant: "success",
}
);
return result;
} catch (err: any) {
let msg = JSON.stringify(err);
@@ -168,7 +175,10 @@ export const useHA = () => {
msg = err.message;
}
snackbr.enqueueSnackbar(
`Failed to call ${domain}.${service} because '${msg}'`,
langStore.get("ERROR_FAILED_CALLING", {
entityId: `${domain}.${service}`,
msg,
}),
{
variant: "error",
}
@@ -178,14 +188,20 @@ export const useHA = () => {
}
if (conn.status === "error") {
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",
}
);
} else {
snackbr.enqueueSnackbar(
`Failed to call service because connection is '${conn.status}'`,
langStore.get("ERROR_FAILED_CALLING_BC_CONNECTION", {
connStatus: conn.status,
connError: "",
}),
{
variant: "error",
}
@@ -210,7 +226,7 @@ export const useHA = () => {
.map(entities.getLabel)
.join(", ");
if (entity_id.length > maxEntities) {
return out + " and more";
return out + " " + langStore.get("AND_MORE");
}
return out;
}
+3 -3
View File
@@ -1,6 +1,6 @@
import React, { FC, useEffect, useState } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { MockPage } from "components/Page";
import { useHA } from "haService";
import InputYaml from "components/Inputs/Base/InputYaml";
import { InputList } from "components/Inputs/InputList";
@@ -89,8 +89,8 @@ export default {
export const ServiceCall: ComponentStory<typeof Test> = (props) => {
return (
<Page>
<MockPage>
<Test {...props} />
</Page>
</MockPage>
);
};
+5 -11
View File
@@ -1,24 +1,18 @@
import React from "react";
import ReactDOM from "react-dom";
import "./styles/root.css";
import App from "./App";
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>
<App />
</React.StrictMode>,
document.getElementById("root")
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.info))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
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