Compare commits

...
26 Commits
Author SHA1 Message Date
ari 7020c6aee9 silent 2022-09-07 12:10:25 -04:00
ari 41dc77ff4f silencing invalid errors 2022-09-06 20:53:49 -04:00
ari c5cf8edfd6 update notice 2022-09-06 20:38:18 -04:00
ari 2dca59fa3f update notice 2022-09-06 20:38:07 -04:00
ari df95265af0 update notice 2022-09-06 20:38:00 -04:00
ari 78057939da clean up 2022-09-05 15:11:59 -04:00
ari a4a607768a rename 2022-09-05 15:09:41 -04:00
ari a9b2bdb775 minor refactor 2022-09-05 15:06:28 -04:00
ari eee37346ab v0.7.5 2022-09-02 16:06:34 -04:00
ari 6ee7ce8f70 ignoring non yaml 2022-09-02 15:45:16 -04:00
ari 2dfbc31b5d v0.7.3 2022-09-02 10:36:55 -04:00
ari ab4997494d lint 2022-09-02 10:34:16 -04:00
ari 83b1c85043 correct fix 2022-09-02 10:33:52 -04:00
ari 7526b578ba fixed return values from backend 2022-09-02 10:11:38 -04:00
ari c461640957 fixed storybook 2022-09-02 09:45:32 -04:00
ari fd0a0aa0c4 v0.7.1 2022-09-01 21:23:49 -04:00
ari 3aad35fbce fixed up linting 2022-09-01 17:25:56 -04:00
ari 774ebe482a handling missing ids better + more tranlsations 2022-09-01 17:21:00 -04:00
ari 69a9805c02 added random media player to package 2022-09-01 15:29:37 -04:00
ari 418b9704e7 added desc to dockerfile 2022-09-01 15:29:16 -04:00
ari 6dcbf4d0ed fixed up centering bug 2022-09-01 15:29:16 -04:00
awashingmachineandAri Sosnovsky df2e926711 Adds italian translation (#155)
* Adds italian translation

Adds ita.json

* added to userprofile

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

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

* Update fra.json

small changes
2022-09-01 11:17:34 -04:00
Ari Sosnovsky be5f73bcc7 Update bug_report.md 2022-08-31 22:23:58 -04:00
Ari Sosnovsky 7e9a7061b1 Update bug_report.md 2022-08-31 22:23:49 -04:00
ari 65c0ed1b69 v0.7.0 2022-08-31 22:16:07 -04:00
139 changed files with 1358 additions and 545 deletions

No files matched your search

+10
View File
@@ -36,4 +36,14 @@ If applicable, add screenshots to help explain your problem.
- Version [e.g. 22] - Version [e.g. 22]
**Additional context** **Additional context**
- Home Assistant Version: [e.g. core-2022.5.4]
- Shortumation Version: [e.g. v0.7.0]
- Homeassistant server type: [e.g. raspberry pi 4 / intel nuc]
Add any other context about the problem here. Add any other context about the problem here.
**Shortumation Logs**
```log
<--- copy here --->
```
+21 -137
View File
@@ -1,5 +1,26 @@
# Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge) # Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge)
## [0.7.4] Bugfixes
- Backend now correctly returns unset alias + description
## [0.7.1] Bugfixes + Italian!
- Added support for automations that do not have an `id`
- Added Italian
- Merged grammar fixes for french
- Fixed up strange centering styling bug
- Replaced more non-multilingual texts with multilingual text
## [0.7.0] Configuration Menu / Light Mode / Lang Support
- Added configuration menu
![image](https://user-images.githubusercontent.com/7451445/187817636-311b5a83-4e08-4b6b-b3b8-2e7086ace136.png)
- Experimental light mode
![image](https://user-images.githubusercontent.com/7451445/187817711-c7a8e23c-b9a4-472b-a348-c1492f3c5d56.png)
- First attempt at a french translation
- No longer using sqllite for automation db
## [0.6.3] - Packages Support & Minor UI improvements ## [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) - Full split config support for packages and all advance include directives (i.e. !include_dir_named, !include_dir_merge_list etc)
@@ -8,12 +29,6 @@
![image](https://user-images.githubusercontent.com/7451445/187043147-15cea23b-0b64-4484-9c87-747998ea9fe6.png) ![image](https://user-images.githubusercontent.com/7451445/187043147-15cea23b-0b64-4484-9c87-747998ea9fe6.png)
## [0.6.2] - Patches
- Attempting to increasing websocket file limit
- Support for all !include directives
## [0.6.1] - v0.6.0 Split Config Support & Better Error handling! ## [0.6.1] - v0.6.0 Split Config Support & Better Error handling!
- Added visual support for split config (this was a heavy refactor!) - Added visual support for split config (this was a heavy refactor!)
@@ -29,11 +44,6 @@
- Better global error capture - Better global error capture
![image](https://user-images.githubusercontent.com/7451445/185441268-9dbde36e-b28b-4a13-bd7f-45ae23834e78.png) ![image](https://user-images.githubusercontent.com/7451445/185441268-9dbde36e-b28b-4a13-bd7f-45ae23834e78.png)
## [0.5.3] - Bug Fixes
- Redirecting `/` to `/web` to resolve container install strangeness reported in https://github.com/asosnovsky/Shortumation/issues/125
- Fixed missing flag that caused the automation to explode in https://github.com/asosnovsky/Shortumation/issues/124
## [0.5.2] - Better Controls ## [0.5.2] - Better Controls
- Add automation trigger - Add automation trigger
@@ -54,11 +64,6 @@
- Websockets now live-refresh when updates occur - Websockets now live-refresh when updates occur
## [0.4.0] - Depedency update
- Core dependency updates
- Python port is now dynamically set
## [0.3.4] - Condition/Trigger Editor Upgrades! ## [0.3.4] - Condition/Trigger Editor Upgrades!
- Many condition editor fixes - Many condition editor fixes
@@ -75,19 +80,6 @@
![image](https://user-images.githubusercontent.com/7451445/180238004-4b04f13a-77a2-4c4c-9144-963dbc394bf4.png) ![image](https://user-images.githubusercontent.com/7451445/180238004-4b04f13a-77a2-4c4c-9144-963dbc394bf4.png)
## [0.3.2] - Fixed Addon Image for arm-based devices
- Using hypercon instead of uvicorn (this losses the rust dependency which makes it easier to install on arm)
- Pre-building web assets outside of docker (this takes the image size down and speeds up instaltion of addon)
- Updated build scripts to actually fail installation when build/prep steps fail
- Ensured that builds for all architecture run successfully
- Re-worked github actions (quicker test phases)
## [0.3.1] - Increased Pagination + Restricted Repeat Node
- Increased pagination to display up to 10,000 autos for now
- Repeat node now has types
## [0.3.0] - Complete Refactor of Graphs ## [0.3.0] - Complete Refactor of Graphs
- Added visual support for - Added visual support for
@@ -106,113 +98,5 @@
![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png) ![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png)
## [0.1.22] - Many Visual improvements
- Deprecated several custom components in favor of mui.com
- Device Editor now has support for 99% of diplay types
- Condition Device is implemented
- Improved naming autogen for trigger & choose
## [0.1.21] - Service Editor
- first version of service editor
- reloading automations on save
## [0.1.20] - UI Bugfixes
- Using MUI elements for input time
- Added delay action / wait_on_triggers action
- Added enabled/disabled flag in node editor
- Optional flip vertical during desktop mode
- Fixed up modal clipping
## [0.1.19] - Vertical mobile mode
- in mobile mode we draw the graphs vertically now
## [0.1.17] - Websockets
- Connected to HA main websocket -- now we retrieve real-time information about
- Device names
- Entity names/ids
- Autocomplete for devices and entities
## [0.1.14] - Material UI + Autocomplete
- Brought some Material UI elements for input and text
- Autocomplete for tags
- Using 'id' as alias for trigger (as it seems to break HA otherwise)
- Not using 'alias' for conditions, always auto-generating it (again, this used to break HA)
- Added missing `data` object to service-actions
## [0.1.13] - YAML
- Better YAML
- Rewrote yaml parser/loader to use pyyaml and safe mode
- Cleaned up description vs alias
## [0.1.12] - Less Intense Error Messages
- Added more node-based errors (this way it's easier to see where validations failed)
- Made the validators less strict in order to capture more edge cases that HA supports
- Nicer auto-generated descriptions for some trigger nodes
## [0.1.10] - More Bug Fixes
- Allowing null or undefined values for metadata fields
- Trigger.platform==time will now have the .at property better supported
## [0.1.9] - Fixed up invalid types for various triggers
- Some triggers had invalid types and were causing a false-positive validation
## [0.1.8] - Support for Malformed Automations
- API will no longer error out on missing values or invalid lists
- Frontend has support for displaying bad automations
## [0.1.6] - Mobile Mode
- Improved mobile mode
- Fixed up arrow styles due to typos
- Added selection color
## [0.1.2] - Docker Hub Images
- Publishing images to docker hub is now stable
## [0.0.15] - Publish to dockerhub
- Publishing images to docker hub
## [0.0.14] - Using vanila ha yaml
- Supporing vanilla out of the box HA yaml as oppose to parsing them (no more $smType)
- Conditions have now a more a explicit node
## [0.0.13] - Better Styling with react-flow
- Fixed up styling (using react-flow)
- cleaned up some button styles
## [0.0.12] - Tags
- Added tag management system for automations
## [0.0.11] - Zoom
- Added lazy saving
## [0.0.10] - Zoom
- Introducing Zoom!
## [0.0.9] - First Working Version
- Instalable verion via github
- Initial POC done
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+1
View File
@@ -46,3 +46,4 @@ ENTRYPOINT [ "/app/bin/run.sh" ]
CMD [ "/app" ] CMD [ "/app" ]
LABEL org.opencontainers.image.source https://github.com/asosnovsky/Shortumation LABEL org.opencontainers.image.source https://github.com/asosnovsky/Shortumation
LABEL org.opencontainers.image.description "A better way to write automations in home-assistant without having to install and run a seperate automation engine!"
+5 -1
View File
@@ -11,7 +11,7 @@ from src.hass_config.loader import HassConfig
def make_automation_router(hass_config: HassConfig) -> APIRouter: def make_automation_router(hass_config: HassConfig) -> APIRouter:
router = APIRouter() router = APIRouter()
@router.post("/list") @router.post("/list", response_model_exclude_unset=True, response_model_exclude_none=True)
def list_autos(body: ListParams) -> ListData[ExtenededAutomation]: def list_autos(body: ListParams) -> ListData[ExtenededAutomation]:
automations = AutomationManager(hass_config) automations = AutomationManager(hass_config)
try: try:
@@ -29,11 +29,15 @@ def make_automation_router(hass_config: HassConfig) -> APIRouter:
@router.post("/item") @router.post("/item")
def insert_auto(body: Automation): def insert_auto(body: Automation):
if body.id is None:
raise HTTPException(status_code=400, detail={"msg": "must contain an id"})
automations = AutomationManager(hass_config) automations = AutomationManager(hass_config)
automations.create(body) automations.create(body)
@router.put("/item") @router.put("/item")
def update_auto(body: ExtenededAutomation): def update_auto(body: ExtenededAutomation):
if body.id is None:
raise HTTPException(status_code=400, detail={"msg": "must contain an id"})
automations = AutomationManager(hass_config) automations = AutomationManager(hass_config)
automations.update(body) automations.update(body)
+6 -2
View File
@@ -11,14 +11,18 @@ logger = get_logger(__file__)
class AutomationDBConnection: class AutomationDBConnection:
def __init__(self) -> None: def __init__(self) -> None:
self.db: dict[str, ExtenededAutomation] = {} self.db: dict[str, ExtenededAutomation] = {}
self.missing_id_db: list[ExtenededAutomation] = []
def reset(self): def reset(self):
self.db = {} self.db = {}
self.missing_id_db = []
def insert_automations(self, automations: list[ExtenededAutomation]): def insert_automations(self, automations: list[ExtenededAutomation]):
repeated_automations = [] repeated_automations = []
for automation in automations: for automation in automations:
if self.db.get(automation.id, None) is None: if automation.id is None:
self.missing_id_db.append(automation)
elif self.db.get(automation.id, None) is None:
self.db[automation.id] = automation self.db[automation.id] = automation
else: else:
repeated_automations.append( repeated_automations.append(
@@ -33,7 +37,7 @@ class AutomationDBConnection:
raise DBNoAutomationFound(automation_id) raise DBNoAutomationFound(automation_id)
def list_automations(self, offset: int, limit: int) -> Iterable[ExtenededAutomation]: def list_automations(self, offset: int, limit: int) -> Iterable[ExtenededAutomation]:
for i, auto in enumerate(self.db.values()): for i, auto in enumerate([*self.missing_id_db, *self.db.values()]):
if i >= offset and i < limit + offset: if i >= offset and i < limit + offset:
yield auto yield auto
+4
View File
@@ -17,6 +17,10 @@ class FailedDeletion(AutomationLoaderException):
pass pass
class InvalidPackage(AutomationLoaderException):
pass
class DBError(Exception): class DBError(Exception):
pass pass
+69 -51
View File
@@ -1,4 +1,3 @@
from itertools import chain
from pathlib import Path from pathlib import Path
from typing import Any, Iterator, Tuple, Union from typing import Any, Iterator, Tuple, Union
@@ -16,7 +15,7 @@ from src.yaml_serializer import (
) )
from ..hass_config.loader import HassConfig from ..hass_config.loader import HassConfig
from .errors import InvalidAutomationFile from .errors import InvalidAutomationFile, InvalidPackage
from .tags import TagManager from .tags import TagManager
from .types import ( from .types import (
AutomationExtractedIter, AutomationExtractedIter,
@@ -46,7 +45,9 @@ def load_and_iter_automations(
elif isinstance(ref, InlineAutomation): elif isinstance(ref, InlineAutomation):
yield from load_automation_inline_ref(hass_config.root_path, tag_manager, ref) yield from load_automation_inline_ref(hass_config.root_path, tag_manager, ref)
else: else:
raise AssertionError(f"ref has an invalid type of {type(ref)} = {ref}") raise logger.error(
AssertionError(f"ref has an invalid type of {type(ref)} = {ref}")
)
except InvalidAutomationFile as e: except InvalidAutomationFile as e:
logger.error(e) logger.error(e)
@@ -56,12 +57,17 @@ def extract_automation_refs(
) -> AutomationExtractedIter: ) -> AutomationExtractedIter:
found = False found = False
for ref in chain( for ref in extract_automation_root_refs(hass_config):
extract_automation_root_refs(hass_config), extract_automation_package_refs(hass_config)
):
found = True found = True
yield ref yield ref
try:
for ref in extract_automation_package_refs(hass_config):
found = True
yield ref
except InvalidPackage as err:
logger.fatal(err)
if not found: if not found:
yield IncludedAutoamtion([""], IncludedYaml(hass_config.root_path / "automations.yaml")) yield IncludedAutoamtion([""], IncludedYaml(hass_config.root_path / "automations.yaml"))
@@ -80,7 +86,7 @@ def extract_automation_root_refs(
source_file=hass_config.get_configuration_path(), source_file=hass_config.get_configuration_path(),
) )
else: else:
logger.warning(f"found an invalid type in {key}!") logger.error(f"found an invalid type in {key}!")
def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtractedIter: def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtractedIter:
@@ -93,7 +99,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
packages, packages,
) )
elif isinstance(packages_config, IncludedYamlDirList): elif isinstance(packages_config, IncludedYamlDirList):
raise AssertionError("cannot configure packages with 'included_dir_list' directive") raise InvalidPackage("cannot configure packages with 'included_dir_list' directive")
elif isinstance(packages_config, IncludedYamlDirNamed): elif isinstance(packages_config, IncludedYamlDirNamed):
packages = packages_config.to_normalized_json(use_path_as_keys=True) packages = packages_config.to_normalized_json(use_path_as_keys=True)
for package_path, package in packages.items(): for package_path, package in packages.items():
@@ -109,7 +115,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
package_set, package_set,
) in iter(packages_config): ) in iter(packages_config):
if not isinstance(package_set, dict): if not isinstance(package_set, dict):
raise AssertionError( raise InvalidPackage(
f"expected {pacakge_set_path} to be a dictionary but got {type(package_set)}" f"expected {pacakge_set_path} to be a dictionary but got {type(package_set)}"
) )
yield from extract_automation_inline_package_refs( yield from extract_automation_inline_package_refs(
@@ -124,7 +130,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
packages_config, packages_config,
) )
else: else:
raise AssertionError("configurations.homeassistant.packages must be a dictionary!") raise InvalidPackage("configurations.homeassistant.packages must be a dictionary!")
def extract_automation_inline_package_refs( def extract_automation_inline_package_refs(
@@ -134,44 +140,48 @@ def extract_automation_inline_package_refs(
ignore_package_name=False, ignore_package_name=False,
) -> AutomationExtractedIter: ) -> AutomationExtractedIter:
for package_name, package_data in packages_config.items(): for package_name, package_data in packages_config.items():
if isinstance(package_data, IncludedYaml): logger.info(f"Loading package={package_name}:{type(package_data)} from {package_data}")
package_mapping = package_data.to_normalized_json() try:
yield from extract_automation_from_package( if isinstance(package_data, IncludedYaml):
package_data=package_mapping, package_mapping = package_data.to_normalized_json()
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif isinstance(package_data, IncludedYamlDirList):
raise NotImplementedError(package_data)
elif isinstance(package_data, IncludedYamlDirNamed):
for package_key_path in package_data.to_normalized_json(True).keys():
if package_key_path.stem == "automation":
yield IncludedAutoamtion(
configuration_key=[package_name], ref=IncludedYaml(package_key_path)
)
elif isinstance(package_data, IncludedYamlDirMergedNamed):
for data_path, data_set in iter(package_data):
yield from extract_automation_from_package( yield from extract_automation_from_package(
package_data=package_mapping,
package_name=package_name, package_name=package_name,
package_data=data_set, source_file=source_file,
source_file=data_path, prefix_config_keys=prefix_config_keys,
prefix_config_keys=[], ignore_package_name=ignore_package_name,
ignore_package_name=True,
) )
elif isinstance(package_data, dict): elif isinstance(package_data, IncludedYamlDirList):
yield from extract_automation_from_package( raise NotImplementedError(package_data)
package_data=package_data, elif isinstance(package_data, IncludedYamlDirNamed):
package_name=package_name, for package_key_path in package_data.to_normalized_json(True).keys():
source_file=source_file, if package_key_path.stem == "automation":
prefix_config_keys=prefix_config_keys, yield IncludedAutoamtion(
ignore_package_name=ignore_package_name, configuration_key=[package_name], ref=IncludedYaml(package_key_path)
) )
else: elif isinstance(package_data, IncludedYamlDirMergedNamed):
raise AssertionError( for data_path, data_set in iter(package_data):
f"configurations.homeassistant.packages[{package_name}] must be a dictionary!" yield from extract_automation_from_package(
) package_name=package_name,
package_data=data_set,
source_file=data_path,
prefix_config_keys=[],
ignore_package_name=True,
)
elif isinstance(package_data, dict):
yield from extract_automation_from_package(
package_data=package_data,
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif package_data is not None:
raise InvalidPackage(
f"configurations.homeassistant.packages.{package_name} must be a dictionary but got {type(package_data)}!"
)
except InvalidPackage as err:
logger.error(err)
def extract_automation_from_package( def extract_automation_from_package(
@@ -236,9 +246,11 @@ def load_automation_inline_ref(
) -> Iterator[ExtenededAutomation]: ) -> Iterator[ExtenededAutomation]:
for auto in inline_automation.automations: for auto in inline_automation.automations:
try: try:
cleaned_automation = clean_automation(auto)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(auto), **cleaned_automation,
tags=tag_manager.get(auto["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=inline_automation.configuration_key, configuration_key=inline_automation.configuration_key,
source_file=str(inline_automation.source_file.resolve().relative_to(root_path)), source_file=str(inline_automation.source_file.resolve().relative_to(root_path)),
source_file_type="inline", source_file_type="inline",
@@ -286,9 +298,11 @@ def load_automation_path(
if isinstance(automations, dict): if isinstance(automations, dict):
try: try:
cleaned_automation = clean_automation(automations)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(automations), **cleaned_automation,
tags=tag_manager.get(automations["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key, configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)), source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="obj", source_file_type="obj",
@@ -305,9 +319,11 @@ def load_automation_path(
return return
for automation in automations: for automation in automations:
try: try:
cleaned_automation = clean_automation(automation)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(automation), **cleaned_automation,
tags=tag_manager.get(automation["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key, configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)), source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="list", source_file_type="list",
@@ -324,6 +340,8 @@ def load_automation_path(
def clean_automation(auto_raw: dict): def clean_automation(auto_raw: dict):
return { return {
**auto_raw, **auto_raw,
"alias": auto_raw.get("alias", "") or "",
"description": auto_raw.get("description", "") or "",
"condition": ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))), "condition": ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))),
"action": ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))), "action": ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))),
"trigger": ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))), "trigger": ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))),
+4
View File
@@ -84,6 +84,8 @@ class AutomationManager:
) )
def update(self, automation: ExtenededAutomation, create_if_not_found: bool = False): def update(self, automation: ExtenededAutomation, create_if_not_found: bool = False):
if automation.id is None:
raise AssertionError("automation.id must be defined to update!")
automation_path = self.hass_config.root_path / automation.source_file automation_path = self.hass_config.root_path / automation.source_file
if not automation_path.parent.exists(): if not automation_path.parent.exists():
automation_path.parent.mkdir(parents=True) automation_path.parent.mkdir(parents=True)
@@ -150,6 +152,8 @@ class AutomationManager:
self.tag_manager.save(self.tag_path) self.tag_manager.save(self.tag_path)
def delete(self, automation: ExtenededAutomation): def delete(self, automation: ExtenededAutomation):
if automation.id is None:
raise AssertionError("automation.id must be defined to update!")
automation_path = self.hass_config.root_path / automation.source_file automation_path = self.hass_config.root_path / automation.source_file
if automation.source_file_type == "obj": if automation.source_file_type == "obj":
automation_path.unlink(missing_ok=True) automation_path.unlink(missing_ok=True)
+3 -3
View File
@@ -32,9 +32,9 @@ AutomationExtractedIter = Iterator[ExtractedAutomation]
class BaseAutomation(BaseModel): class BaseAutomation(BaseModel):
id: str id: Optional[str]
alias: Optional[str] = None alias: str = ""
description: Optional[str] = None description: str = ""
trigger_variables: Optional[dict[str, Union[str, int, bool, float]]] = None trigger_variables: Optional[dict[str, Union[str, int, bool, float]]] = None
mode: str = "single" mode: str = "single"
trigger: list[dict] = [] trigger: list[dict] = []
+10 -3
View File
@@ -1,21 +1,28 @@
from pathlib import Path from pathlib import Path
from typing import Iterator, NamedTuple, Tuple, Union from typing import Iterator, NamedTuple, Tuple
from yaml.nodes import Node from yaml.nodes import Node
from src.logger import get_logger
from .manager import YamlManager from .manager import YamlManager
dump_yaml = YamlManager.dump_yaml dump_yaml = YamlManager.dump_yaml
load_yaml = YamlManager.load_yaml load_yaml = YamlManager.load_yaml
logger = get_logger(__file__)
def load_dir_yaml(folder_or_file: Path) -> Iterator[Tuple[Path, dict | list]]: def load_dir_yaml(folder_or_file: Path) -> Iterator[Tuple[Path, dict | list]]:
if folder_or_file.is_dir(): if folder_or_file.is_dir():
for file in folder_or_file.iterdir(): for file in folder_or_file.iterdir():
yield from load_dir_yaml(file) yield from load_dir_yaml(file)
else: else:
with folder_or_file.open("r") as fp: if folder_or_file.suffix.lower() == ".yaml":
yield folder_or_file, load_yaml(fp, root_path=folder_or_file.parent) with folder_or_file.open("r") as fp:
yield folder_or_file, load_yaml(fp, root_path=folder_or_file.parent)
else:
logger.info(f"Ignoring the file {folder_or_file}")
@YamlManager.as_constructor("!include") @YamlManager.as_constructor("!include")
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -1 +1,38 @@
automation: !include ../automations/ui.yaml automation: !include ../automations/ui.yaml
media_player:
- platform: template
media_players:
receiver:
friendly_name: Receiver
current_source_template: "{{ states('input_text.selected_source') }}"
value_template: >
{% if is_state("input_boolean.receiver_on", "on") -%}
on
{%- else -%}
off
{%- endif %}
turn_on:
service: switch.turn_on
data_template:
entity_id: switch.receiver_on
turn_off:
service: switch.turn_on
data_template:
entity_id: switch.receiver_off
volume_up:
service: switch.turn_on
data_template:
entity_id: switch.volume_up
volume_down:
service: switch.turn_on
data_template:
entity_id: switch.vol
input_templates:
source 1:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_1
source 2:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_2
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,30 @@
# Loads default set of integrations. Do not remove.
default_config:
# Text to speech
tts:
- platform: google_translate
# automation manual: !include_dir_list ./automations/include_dir_list
# automation ui: !include automations/ui.yaml
# automation: !include automations/base.yaml
# automation cools: !include_dir_merge_list automations/include_dir_merge_list
script: !include scripts.yaml
scene: !include scenes.yaml
automation:
- alias: inline-auto
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
homeassistant:
packages: !include packages.yaml
+16
View File
@@ -0,0 +1,16 @@
ha: !include packages/ha.yaml
sub: !include_dir_merge_named packages/sub
secret_ones:
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
@@ -0,0 +1 @@
automation: !include ../automations/ui.yaml
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,13 @@
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
Whitespace-only changes.
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
media_player: !include_dir_list ../entities/media_players
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
# media_player: !include_dir_list ../entities/media_players
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
media_player:
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
- platform: media
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1,16 @@
- platform: ping
host: 192.168.0.119
name: "Ping Pc Tv"
scan_interval: 10
- platform: ping
host: 192.168.0.181
name: "Ping Living Room Tv"
scan_interval: 10
- platform: ping
host: 192.168.0.100
name: "Ping Printer"
scan_interval: 15
- platform: ping
host: 192.168.0.177
name: "Ping Broadlink"
scan_interval: 15
@@ -0,0 +1 @@
media_player: !include_dir_list ../entities/media_players
+2 -2
View File
@@ -249,7 +249,7 @@ class automation_update_tests(BaseTestCase):
) )
autos = resp.json()["data"] autos = resp.json()["data"]
self.assertEqual(resp.json()["totalItems"], self.test_params["total"]) self.assertEqual(resp.json()["totalItems"], self.test_params["total"])
self.assertNotIn("i am new", set([a["id"] for a in autos])) self.assertNotIn("i am new", set([a.get("id", "") for a in autos]))
resp = self.client.post( resp = self.client.post(
"/automations/item", "/automations/item",
json=Automation( json=Automation(
@@ -262,7 +262,7 @@ class automation_update_tests(BaseTestCase):
) )
data = resp.json() data = resp.json()
self.assertEqual(data["totalItems"], self.test_params["total"] + 1) self.assertEqual(data["totalItems"], self.test_params["total"] + 1)
self.assertIn("i am new", set([a["id"] for a in data["data"]])) self.assertIn("i am new", set([a.get("id", "") for a in data["data"]]))
def test_update_some(self): def test_update_some(self):
resp = self.client.post( resp = self.client.post(
@@ -21,6 +21,11 @@ from tests.utils import (
HA_CONFIG10_EXAMPLE, HA_CONFIG10_EXAMPLE,
HA_CONFIG11_EXAMPLE, HA_CONFIG11_EXAMPLE,
HA_CONFIG12_EXAMPLE, HA_CONFIG12_EXAMPLE,
HA_CONFIG13_EXAMPLE,
HA_CONFIG14_EXAMPLE,
HA_CONFIG15_EXAMPLE,
HA_CONFIG16_EXAMPLE,
HA_CONFIG17_EXAMPLE,
HA_CONFIG_EXAMPLE, HA_CONFIG_EXAMPLE,
) )
@@ -160,6 +165,11 @@ class loader_tests(TestCase):
(HA_CONFIG10_EXAMPLE, 3), (HA_CONFIG10_EXAMPLE, 3),
(HA_CONFIG11_EXAMPLE, 3), (HA_CONFIG11_EXAMPLE, 3),
(HA_CONFIG12_EXAMPLE, 4), (HA_CONFIG12_EXAMPLE, 4),
(HA_CONFIG13_EXAMPLE, 4),
(HA_CONFIG14_EXAMPLE, 1),
(HA_CONFIG15_EXAMPLE, 1),
(HA_CONFIG16_EXAMPLE, 1),
(HA_CONFIG17_EXAMPLE, 1),
]: ]:
with self.subTest(config_name=ha_path.name, expected=expected): with self.subTest(config_name=ha_path.name, expected=expected):
hass_config = HassConfig(ha_path) hass_config = HassConfig(ha_path)
@@ -65,6 +65,52 @@ class dumping_yamls_tests(TestCase):
}, },
) )
def test_load_template_in_yaml(self):
yaml_obj = load_yaml(
io.StringIO(
"""
- id: '1652069225859'
alias: 'Lower the volume'
description: ''
mode: single
trigger:
- platform: state
entity_id: input_number.preferred_temperature
condition: []
action:
- service: media_player.volume_set
data_template:
entity_id: media_player.denon_avr_x2500h
volume_level: '{{ ((states(''input_number.volume_video'')|int)+80)/100 }}'
"""
),
Path.cwd(),
)
self.assertIsInstance(yaml_obj, list)
self.assertEqual(len(yaml_obj), 1)
self.assertDictEqual(
dict(yaml_obj[0]),
{
"id": "1652069225859",
"alias": "Lower the volume",
"description": "",
"mode": "single",
"trigger": [
{"platform": "state", "entity_id": "input_number.preferred_temperature"}
],
"condition": [],
"action": [
{
"service": "media_player.volume_set",
"data_template": {
"entity_id": "media_player.denon_avr_x2500h",
"volume_level": "{{ ((states('input_number.volume_video')|int)+80)/100 }}",
},
}
],
},
)
def test_load_stub(self): def test_load_stub(self):
yaml_obj = load_yaml( yaml_obj = load_yaml(
io.StringIO( io.StringIO(
+5
View File
@@ -22,6 +22,11 @@ HA_CONFIG9_EXAMPLE = SAMPLES_FOLDER / "config-9"
HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10" HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10"
HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11" HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11"
HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12" HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12"
HA_CONFIG13_EXAMPLE = SAMPLES_FOLDER / "config-13"
HA_CONFIG14_EXAMPLE = SAMPLES_FOLDER / "config-14"
HA_CONFIG15_EXAMPLE = SAMPLES_FOLDER / "config-15"
HA_CONFIG16_EXAMPLE = SAMPLES_FOLDER / "config-16"
HA_CONFIG17_EXAMPLE = SAMPLES_FOLDER / "config-17"
def get_example_automation_loader( def get_example_automation_loader(
+2 -2
View File
@@ -1,7 +1,7 @@
name: Shortumation name: Shortumation
version: v0.6.3 version: v0.7.4
slug: shortumation slug: shortumation
image: asosnovsky/shortumation-{arch} image: "asosnovsky/shortumation-{arch}"
url: "https://github.com/asosnovsky/Shortumation" url: "https://github.com/asosnovsky/Shortumation"
description: "A homeassitant addon which provides better UI for automations & scripts." description: "A homeassitant addon which provides better UI for automations & scripts."
arch: arch:
+1 -1
View File
@@ -1,7 +1,7 @@
import "./App.css"; import "./App.css";
import { Routes, Route, BrowserRouter } from "react-router-dom"; import { Routes, Route, BrowserRouter } from "react-router-dom";
import { AutomationRoute } from "routes/automation"; import { AutomationRoute } from "routes/automation";
import { useConnectedApiService } from "apiService"; import { useConnectedApiService } from "services/api";
import { ErrorBoundary } from "components/ErrorBoundary"; import { ErrorBoundary } from "components/ErrorBoundary";
import { CookiesProvider } from "react-cookie"; import { CookiesProvider } from "react-cookie";
import { Page } from "components/Page"; import { Page } from "components/Page";
@@ -14,7 +14,7 @@ const { componentMeta, make } = makeStory({
}) => { }) => {
const [[metadata, tags], setState] = useState([args.metadata, args.tags]); const [[metadata, tags], setState] = useState([args.metadata, args.tags]);
const tagDB = useTagDB( const tagDB = useTagDB(
[{ id: metadata.id, tags: Object.fromEntries(tags) }], metadata.id ? [{ id: metadata.id, tags: Object.fromEntries(tags) }] : [],
(_, t) => setState([metadata, Object.entries(t)]) (_, t) => setState([metadata, Object.entries(t)])
); );
@@ -10,7 +10,7 @@ import { AddIcon, TrashIcon } from "components/Icons";
import InputAutoText from "components/Inputs/InputAutoText"; import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "components/AutomationManager/TagDB"; import { TagDB } from "components/AutomationManager/TagDB";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang"; import { useLang } from "services/lang";
export interface AutoInfoBoxProps { export interface AutoInfoBoxProps {
metadata: AutomationMetadata & Partial<AutomationShortumationMetadata>; metadata: AutomationMetadata & Partial<AutomationShortumationMetadata>;
@@ -104,7 +104,7 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div className="automation-editor--info-box-inner"> <div className="automation-editor--info-box-inner">
<InputText <InputText
label={langStore.get("ID")} label={langStore.get("ID")}
value={metadata.id} value={metadata.id ?? langStore.get("N/A")}
onChange={onUpdateMetadata("id")} onChange={onUpdateMetadata("id")}
/> />
<InputText <InputText
@@ -125,7 +125,7 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
options={["parallel", "single", "queued", "restart"]} options={["parallel", "single", "queued", "restart"]}
/> />
<div className="automation-editor--info-box--tags"> <div className="automation-editor--info-box--tags">
<h1>Tags</h1> <h1>{langStore.get("TAGS")}</h1>
<div className="automation-editor--info-box--tag-list"> <div className="automation-editor--info-box--tag-list">
{tags.map(([tagName, tagValue], tagIndex) => ( {tags.map(([tagName, tagValue], tagIndex) => (
<div key={tagIndex} className="automation-editor--info-box--tag"> <div key={tagIndex} className="automation-editor--info-box--tag">
@@ -1,7 +1,7 @@
import "./index.css"; import "./index.css";
import { AutomationNode, AutomationNodeMapping } from "types/automations"; import { AutomationNode, AutomationNodeMapping } from "types/automations";
import { useHA } from "haService"; import { useHA } from "services/ha";
import { CollectionNodeElement } from "components/DAGGraph/nodes/CollectionNode/CollectionNodeElement"; import { CollectionNodeElement } from "components/DAGGraph/nodes/CollectionNode/CollectionNodeElement";
import { getDescriptionFromAutomationNode } from "utils/formatting"; import { getDescriptionFromAutomationNode } from "utils/formatting";
import { Size } from "components/DAGGraph/elements/types"; import { Size } from "components/DAGGraph/elements/types";
@@ -19,7 +19,7 @@ const { make, componentMeta } = makeStory({
<AutomationEditor <AutomationEditor
{...args} {...args}
tagDB={useTagDB( tagDB={useTagDB(
state ? [{ id: state.id, tags: state.tags }] : [], state && state.id ? [{ id: state.id, tags: state.tags }] : [],
() => {} () => {}
)} )}
automation={state} automation={state}
@@ -31,7 +31,9 @@ import { MiniFailure } from "types/validators/helper";
import { AutoInfoBox } from "./AutoInfoBox"; import { AutoInfoBox } from "./AutoInfoBox";
import { useAutomatioEditorState, EditorData } from "./state"; import { useAutomatioEditorState, EditorData } from "./state";
import { useLang } from "lang"; import { useLang } from "services/lang";
import { useSnackbar } from "notistack";
import { Alert } from "@mui/material";
interface Props { interface Props {
automation?: AutomationData | BareAutomationData; automation?: AutomationData | BareAutomationData;
@@ -41,6 +43,8 @@ interface Props {
onDelete: () => void; onDelete: () => void;
tagDB: TagDB; tagDB: TagDB;
isNew?: boolean; isNew?: boolean;
readonly: boolean;
issue?: string;
} }
export const AutomationEditor: FC<Props> = ({ export const AutomationEditor: FC<Props> = ({
dims, dims,
@@ -49,10 +53,12 @@ export const AutomationEditor: FC<Props> = ({
onDelete, onDelete,
onTrigger, onTrigger,
tagDB, tagDB,
isNew, readonly,
issue,
}) => { }) => {
// state // state
const langStore = useLang(); const langStore = useLang();
const snackbr = useSnackbar();
const { const {
state, state,
updateSequence, updateSequence,
@@ -63,7 +69,15 @@ export const AutomationEditor: FC<Props> = ({
save, save,
saveAndUpdate, saveAndUpdate,
undo, undo,
} = useAutomatioEditorState(propsAutos, propsOnUpdate); } = useAutomatioEditorState(propsAutos, (auto) => {
if (readonly) {
snackbr.enqueueSnackbar(langStore.get("READONLY_CANNOT_UPDATE"), {
color: "warning",
});
} else {
propsOnUpdate(auto);
}
});
const [infoBoxOpen, setInfoBox] = useState(false); const [infoBoxOpen, setInfoBox] = useState(false);
const [ const [
{ ckFlipped }, { ckFlipped },
@@ -95,7 +109,13 @@ export const AutomationEditor: FC<Props> = ({
); );
} }
return ( return (
<div className={["automation-editor", state.status].join(" ")}> <div
className={[
"automation-editor",
state.status,
readonly ? "readonly" : "",
].join(" ")}
>
{state.status === "saving" && ( {state.status === "saving" && (
<LinearProgress className="linear-loader" /> <LinearProgress className="linear-loader" />
)} )}
@@ -112,13 +132,15 @@ export const AutomationEditor: FC<Props> = ({
state.status, state.status,
].join(" ")} ].join(" ")}
> >
<Button onClick={() => setInfoBox(false)}>Close</Button> <Button onClick={() => setInfoBox(false)}>
{langStore.get("CLOSE")}
</Button>
<Button <Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"} className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save} onClick={save}
disabled={state.status !== "changed"} disabled={state.status !== "changed" || readonly}
> >
Save <CheckMarkIcon color="#bf4" /> {langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button> </Button>
</div> </div>
</AutoInfoBox> </AutoInfoBox>
@@ -220,6 +242,11 @@ export const AutomationEditor: FC<Props> = ({
{langStore.get("SAVE")} <CheckMarkIcon color="#bf4" /> {langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button> </Button>
</div> </div>
{readonly && (
<Alert color="warning">
{langStore.get("READONLY_MODE")} - {issue}
</Alert>
)}
<DAGAutomationGraph <DAGAutomationGraph
action={state.data.action} action={state.data.action}
trigger={state.data.trigger} trigger={state.data.trigger}
@@ -306,16 +333,14 @@ export const ValidationBox: FC<{
<div className="automation-editor-failures"> <div className="automation-editor-failures">
<ul> <ul>
{failures.map((f, i) => ( {failures.map((f, i) => (
<> <li key={i}>
<li key={i}> <b>{f.path}</b>:
<b>{f.path}</b>: <ul>
<ul> {f.message.map((m, j) => (
{f.message.map((m, j) => ( <li key={j}>{m}</li>
<li key={j}>{m}</li> ))}
))} </ul>
</ul> </li>
</li>
</>
))} ))}
</ul> </ul>
<span>{langStore.get("VALIDATION_PLEASE_CORRECT_FILE")}</span> <span>{langStore.get("VALIDATION_PLEASE_CORRECT_FILE")}</span>
@@ -23,6 +23,7 @@ const { make, componentMeta } = makeStory({
id: "1", id: "1",
title: "Example", title: "Example",
entityId: "automation.1", entityId: "automation.1",
readonly: false,
description: "Amazing automation!", description: "Amazing automation!",
tags: {}, tags: {},
state: "on", state: "on",
@@ -38,6 +39,7 @@ const { make, componentMeta } = makeStory({
id: "2", id: "2",
title: "Example 2", title: "Example 2",
entityId: "automation.2", entityId: "automation.2",
readonly: false,
description: "Cool!", description: "Cool!",
state: "on", state: "on",
source_file: "automation.yaml", source_file: "automation.yaml",
@@ -89,6 +91,7 @@ export const Nested = make({
entityId: "automation.1", entityId: "automation.1",
description: "", description: "",
title: "Automation #1", title: "Automation #1",
readonly: false,
state: "on", state: "on",
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
@@ -102,6 +105,7 @@ export const Nested = make({
{ {
id: "2", id: "2",
entityId: "automation.2", entityId: "automation.2",
readonly: false,
description: "another one", description: "another one",
title: "Automation #2", title: "Automation #2",
state: "off", state: "off",
@@ -117,6 +121,7 @@ export const Nested = make({
{ {
id: "3", id: "3",
entityId: "automation.3", entityId: "automation.3",
readonly: false,
description: "bad one", description: "bad one",
title: "Automation #3", title: "Automation #3",
state: "offing", state: "offing",
@@ -153,6 +158,7 @@ export const Nested = make({
}, },
data: [ data: [
{ {
readonly: false,
id: "4", id: "4",
entityId: "automation.4", entityId: "automation.4",
description: "Cool thing", description: "Cool thing",
@@ -1,5 +1,5 @@
import { HassEntities } from "home-assistant-js-websocket"; import { HassEntities } from "home-assistant-js-websocket";
import { LangStore, useLang } from "lang"; import { LangStore, useLang } from "services/lang";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { AutomationData, BareAutomationData } from "types/automations"; import { AutomationData, BareAutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults"; import { defaultAutomation } from "utils/defaults";
@@ -52,6 +52,7 @@ export const useAutomationDB = (
const auto = defaultAutomation(String(Date.now())); const auto = defaultAutomation(String(Date.now()));
setNewAuto([ setNewAuto([
{ {
readonly: false,
id: auto.id, id: auto.id,
entityId: "", entityId: "",
title: auto.alias ?? "", title: auto.alias ?? "",
@@ -77,13 +78,18 @@ const genMapping = (
tagsDB: TagDB, tagsDB: TagDB,
langStore: LangStore langStore: LangStore
) => { ) => {
const configData: Record<string, AutomationData> = configAutomations.reduce( const configDataNoId: AutomationData[] = [];
(all, n) => ({ const configData: Record<string, AutomationData & { id: string }> =
...all, configAutomations.reduce((all, n) => {
[n.id]: n, if (n.id) {
}), return {
{} ...all,
); [n.id]: n,
};
}
configDataNoId.push(n);
return all;
}, {});
const automatioinMap: Record< const automatioinMap: Record<
string, string,
[AutomationManagerAuto, AutomationData | null] [AutomationManagerAuto, AutomationData | null]
@@ -91,7 +97,7 @@ const genMapping = (
Object.entries(haEntities) Object.entries(haEntities)
.filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation.")) .filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation."))
.forEach(([entityId, entityData], i) => { .forEach(([entityId, entityData], i) => {
const autoId = entityData.attributes.id ?? `${entityData.state}-${i}`; const autoId = entityData.attributes.id ?? entityId.split(".")[1];
let title = entityData.attributes.friendly_name ?? ""; let title = entityData.attributes.friendly_name ?? "";
let description = ""; let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state) let issue: string | undefined = ["on", "off"].includes(entityData.state)
@@ -127,12 +133,13 @@ const genMapping = (
source_file_type, source_file_type,
configuration_key, configuration_key,
issue, issue,
readonly: found == null,
}, },
found, found,
]; ];
}); });
Object.values(configData).forEach((auto) => { Object.values(configData).forEach((auto, i) => {
automatioinMap[auto.id] = [ automatioinMap[auto.id] = [
{ {
id: auto.id, id: auto.id,
@@ -145,10 +152,55 @@ const genMapping = (
source_file_type: auto.source_file_type, source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key, configuration_key: auto.configuration_key,
issue: langStore.get("ISSUES_NO_LOAD_AUTOMATION"), issue: langStore.get("ISSUES_NO_LOAD_AUTOMATION"),
readonly: false,
}, },
auto, auto,
]; ];
}); });
let failedGeneration: number = 0;
configDataNoId.forEach((auto) => {
let generatedAutoId = `automation_${failedGeneration + 1}`;
if (auto.alias) {
generatedAutoId = auto.alias
.toLowerCase()
.replaceAll(/\W/g, " ")
.trim()
.replaceAll(" ", "_");
} else {
failedGeneration += 1;
}
if (automatioinMap[generatedAutoId]) {
automatioinMap[generatedAutoId] = [
{
...automatioinMap[generatedAutoId][0],
issue: langStore.get("ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT", {
sourceFile: auto.source_file,
}),
readonly: true,
},
auto,
];
} else {
automatioinMap[generatedAutoId] = [
{
id: generatedAutoId,
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: {},
source_file: auto.source_file,
source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key,
issue: langStore.get("ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT", {
sourceFile: auto.source_file,
}),
readonly: true,
},
auto,
];
}
});
return automatioinMap; return automatioinMap;
}; };
@@ -10,7 +10,7 @@ import {
} from "./state"; } from "./state";
import Alert from "@mui/material/Alert"; import Alert from "@mui/material/Alert";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & { export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
onAutomationDelete: (aid: string, eid: string) => void; onAutomationDelete: (aid: string, eid: string) => void;
@@ -50,6 +50,8 @@ export const AutomationManagerLoaded: FC<
{state.currentAutomationId !== null ? ( {state.currentAutomationId !== null ? (
state.currentAutomation ? ( state.currentAutomation ? (
<AutomationEditor <AutomationEditor
readonly={state.currentAutomationIsReadOnly}
issue={state.currentAutomationIssue}
dims={{ dims={{
...DEFAULT_DIMS, ...DEFAULT_DIMS,
flipped: true, flipped: true,
@@ -7,7 +7,7 @@ import { useAutomationDB } from "./automationDB";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { AutomationManagerAutoUpdatable } from "../types"; import { AutomationManagerAutoUpdatable } from "../types";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type UseAutomationManagerStateArgs = { export type UseAutomationManagerStateArgs = {
configAutomations: AutomationData[]; configAutomations: AutomationData[];
@@ -37,7 +37,11 @@ export const useAutomationManagerState = ({
.map(({ id, tags = {} }) => ({ .map(({ id, tags = {} }) => ({
id, id,
tags, tags,
})), }))
.filter(({ id }) => typeof id === "string") as Array<{
id: string;
tags: Record<string, string>;
}>,
onUpdateTags onUpdateTags
); );
const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB); const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB);
@@ -78,6 +82,14 @@ export const useAutomationManagerState = ({
get currentAutomationEntityId(): string | null { get currentAutomationEntityId(): string | null {
return currentAutomation === null ? null : currentAutomation[0].entityId; return currentAutomation === null ? null : currentAutomation[0].entityId;
}, },
get currentAutomationIsReadOnly(): boolean {
return currentAutomation === null ? true : currentAutomation[0].readonly;
},
get currentAutomationIssue(): string | undefined {
return currentAutomation === null
? undefined
: currentAutomation[0].issue;
},
async setSelectedAutomationId(i: string | null, force: boolean = false) { async setSelectedAutomationId(i: string | null, force: boolean = false) {
if (methods.currentAutomationIsNew && !force) { if (methods.currentAutomationIsNew && !force) {
if (!(await stillHaveNewAreYouSure())) { if (!(await stillHaveNewAreYouSure())) {
@@ -94,7 +106,9 @@ export const useAutomationManagerState = ({
} }
} }
const auto = automationDB.addNew(); const auto = automationDB.addNew();
methods.setSelectedAutomationId(auto.id, true); if (auto.id) {
methods.setSelectedAutomationId(auto.id, true);
}
}, },
editorUpdateAutomation(auto: AutomationData | BareAutomationData) { editorUpdateAutomation(auto: AutomationData | BareAutomationData) {
if (methods.currentAutomationIsNew) { if (methods.currentAutomationIsNew) {
@@ -12,7 +12,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import InputAutoText from "components/Inputs/InputAutoText"; import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "../TagDB"; import { TagDB } from "../TagDB";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type TagsProps = { export type TagsProps = {
automationId: string; automationId: string;
@@ -18,7 +18,7 @@ import { ButtonIcon } from "components/Icons/ButtonIcons";
import { AutomationManagerAuto } from "../types"; import { AutomationManagerAuto } from "../types";
import { Tags } from "./Tags"; import { Tags } from "./Tags";
import { TagDB } from "../TagDB"; import { TagDB } from "../TagDB";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type MetadataBoxProps = AutomationManagerAuto & { export type MetadataBoxProps = AutomationManagerAuto & {
onDelete: () => void; onDelete: () => void;
@@ -71,6 +71,7 @@ const story = makeStory({
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
configuration_key: ["automation"], configuration_key: ["automation"],
readonly: false,
}, },
]); ]);
setSelAutoId(id); setSelAutoId(id);
@@ -100,6 +101,7 @@ const makeAuto = (
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
configuration_key: ["automation"], configuration_key: ["automation"],
readonly: false,
...data, ...data,
}; };
}; };
@@ -18,7 +18,7 @@ import {
} from "../types"; } from "../types";
import { Button } from "components/Inputs/Buttons/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type AutomationManagerSidebarProps = { export type AutomationManagerSidebarProps = {
tagsDB: TagDB; tagsDB: TagDB;
@@ -38,10 +38,11 @@ const automations: AutomationManagerAuto[] = [
description: a.description ?? "", description: a.description ?? "",
state: "on", state: "on",
tags: a.tags, tags: a.tags,
id: a.id, id: a.id as string,
isSelected: false, isSelected: false,
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
readonly: false,
configuration_key: ["automation"], configuration_key: ["automation"],
})); }));
@@ -51,7 +52,8 @@ const bigList = bigMockAutoList.map<AutomationManagerAuto>((a) => ({
description: a.description ?? "", description: a.description ?? "",
state: "on", state: "on",
tags: a.tags, tags: a.tags,
id: a.id, id: a.id as string,
readonly: false,
isSelected: false, isSelected: false,
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
@@ -1,10 +1,10 @@
import { makeStory } from "devUtils"; import { makeStory } from "devUtils";
import { useMockApiService } from "apiService"; import { useMockApiService } from "services/api";
import { AutomationManager } from "."; import { AutomationManager } from ".";
import { import {
MockHAEntitiesProps, MockHAEntitiesProps,
useMockHAEntities, useMockHAEntities,
} from "haService/HAEntities.mock"; } from "services/ha/HAEntities.mock";
import { AutomationData } from "types/automations"; import { AutomationData } from "types/automations";
import { createMockAuto } from "utils/mocks"; import { createMockAuto } from "utils/mocks";
import { useState } from "react"; import { useState } from "react";
@@ -109,7 +109,7 @@ export const MissingAutoInConfig = make({
entity_id: `automation.${auto1.id}`, entity_id: `automation.${auto1.id}`,
attributes: { attributes: {
id: auto1.id, id: auto1.id,
friendly_name: auto1.alias, friendly_name: auto1.alias ?? auto1.id ?? "",
}, },
context: { id: "", parent_id: null, user_id: null }, context: { id: "", parent_id: null, user_id: null },
last_changed: "", last_changed: "",
@@ -4,8 +4,8 @@ import { FC, useEffect, useRef, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress"; import LinearProgress from "@mui/material/LinearProgress";
import Skeleton from "@mui/material/Skeleton"; import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "apiService/core"; import { ApiService } from "services/api/core";
import { HAEntitiesState } from "haService/HAEntities"; import { HAEntitiesState } from "services/ha/HAEntities";
import { AutomationManagerLoaded } from "./Loaded"; import { AutomationManagerLoaded } from "./Loaded";
import { Alert } from "@mui/material"; import { Alert } from "@mui/material";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
@@ -14,8 +14,8 @@ import { getFailures } from "types/validators/helper";
import * as av from "types/validators/autmation"; import * as av from "types/validators/autmation";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { APIResponse } from "apiService/types"; import { APIResponse } from "services/api/types";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type AutomationManagerProps = { export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => Promise<any>; onAutomationStateChange: (eid: string, on: boolean) => Promise<any>;
@@ -12,6 +12,7 @@ export type AutomationManagerAuto = AutomationManagerAutoUpdatable & {
source_file: string; source_file: string;
source_file_type: string; source_file_type: string;
configuration_key: string[]; configuration_key: string[];
readonly: boolean;
}; };
export type AutomationManagerAutoItem = AutomationManagerAuto & { export type AutomationManagerAutoItem = AutomationManagerAuto & {
flags: AutomationManagerItemFlags; flags: AutomationManagerItemFlags;
@@ -1,9 +1,9 @@
import Alert from "@mui/material/Alert"; import Alert from "@mui/material/Alert";
import Skeleton from "@mui/material/Skeleton"; import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "apiService/core"; import { ApiService } from "services/api/core";
import { UserProfile } from "apiService/types"; import { UserProfile } from "services/api/types";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import { useLang } from "lang"; import { useLang } from "services/lang";
import { FC, useState } from "react"; import { FC, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress"; import LinearProgress from "@mui/material/LinearProgress";
@@ -53,7 +53,7 @@ export const UserProfileEditor: FC<UserProfileProps> = ({ api }) => {
/> />
<InputList <InputList
label={lang.get("LANGUAGE")} label={lang.get("LANGUAGE")}
options={["eng", "fra"]} options={["eng", "fra", "ita"]}
current={profile.data.lang} current={profile.data.lang}
onChange={update("lang")} onChange={update("lang")}
/> />
+5 -4
View File
@@ -1,17 +1,18 @@
import "./index.css"; import "./index.css";
import { FC, useState } from "react"; import { FC, useState } from "react";
import { useHAConnection } from "haService/connection"; import { useHAConnection } from "services/ha/connection";
import { Button } from "components/Inputs/Buttons/Button"; import { Button } from "components/Inputs/Buttons/Button";
import SettingsSuggestOutlinedIcon from "@mui/icons-material/SettingsSuggestOutlined"; import SettingsSuggestOutlinedIcon from "@mui/icons-material/SettingsSuggestOutlined";
import { useLang } from "lang"; import { useLang } from "services/lang";
import { Modal } from "components/Modal"; import { Modal } from "components/Modal";
import { UserProfileEditor, UserProfileProps } from "./UserProfile"; import { UserProfileEditor, UserProfileProps } from "./UserProfile";
import { useVersioner } from "services/versioner";
export type BottomBarProps = UserProfileProps; export type BottomBarProps = UserProfileProps;
export const BottomBar: FC<BottomBarProps> = ({ api }) => { export const BottomBar: FC<BottomBarProps> = ({ api }) => {
const lang = useLang(); const lang = useLang();
const ha = useHAConnection(); const ha = useHAConnection();
const version = process.env.REACT_APP_BUILD_VERSION ?? "n/a"; const versionMgr = useVersioner();
const [isOpen, setOpen] = useState(false); const [isOpen, setOpen] = useState(false);
return ( return (
@@ -31,7 +32,7 @@ export const BottomBar: FC<BottomBarProps> = ({ api }) => {
🟢 🟢
</b> </b>
</span> </span>
<span>version: {version}</span> <span>version: {versionMgr.current}</span>
<Button className="settings" onClick={() => setOpen(!isOpen)}> <Button className="settings" onClick={() => setOpen(!isOpen)}>
<SettingsSuggestOutlinedIcon /> <SettingsSuggestOutlinedIcon />
{lang.get("USER_PRERENCES")} {lang.get("USER_PRERENCES")}
@@ -6,13 +6,13 @@ import { FC, useState } from "react";
import { AutomationCondition } from "types/automations/conditions"; import { AutomationCondition } from "types/automations/conditions";
import { getSubTypeList } from "utils/automations"; import { getSubTypeList } from "utils/automations";
import { getConditionDefaultValues } from "utils/defaults"; import { getConditionDefaultValues } from "utils/defaults";
import { useHA } from "haService"; import { useHA } from "services/ha";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { getViewer } from "./viewRender"; import { getViewer } from "./viewRender";
import { getEditor } from "./editorRender"; import { getEditor } from "./editorRender";
import useWindowSize from "utils/useWindowSize"; import useWindowSize from "utils/useWindowSize";
import { ConditionNodeSettings } from "./ConditionNodeSettings"; import { ConditionNodeSettings } from "./ConditionNodeSettings";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type ConditionNodeBaseProps = { export type ConditionNodeBaseProps = {
condition: AutomationCondition; condition: AutomationCondition;
@@ -20,7 +20,7 @@ import {
import { genUpdateMethods } from "./nestedUpdater"; import { genUpdateMethods } from "./nestedUpdater";
import { InputTime } from "components/Inputs/Base/InputTime"; import { InputTime } from "components/Inputs/Base/InputTime";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { HAService } from "haService"; import { HAService } from "services/ha";
import { DeviceEditor } from "components/DeviceEditor"; import { DeviceEditor } from "components/DeviceEditor";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import AddIcon from "@mui/icons-material/Add"; import AddIcon from "@mui/icons-material/Add";
@@ -31,7 +31,7 @@ import { prettyName } from "utils/formatting";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Buttons/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { RemoveCircle } from "@mui/icons-material"; import { RemoveCircle } from "@mui/icons-material";
import { LangStore } from "lang"; import { LangStore } from "services/lang";
interface Editor<C extends AutomationCondition> interface Editor<C extends AutomationCondition>
extends FC<{ extends FC<{
@@ -271,7 +271,7 @@ export const StateEditor: Editor<StateCondition> = ({
} }
/> />
<InputTime <InputTime
label="For" label={langStore.get("FOR")}
value={condition.for} value={condition.for}
onChange={(_for) => onChange={(_for) =>
onChange({ onChange({
@@ -3,7 +3,7 @@ import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { Page } from "components/Page";
import { DAGGraphBoard } from "components/DAGGraph/board"; import { DAGGraphBoard } from "components/DAGGraph/board";
import { useAutomationNodes } from "./index"; import { useAutomationNodes } from "./index";
import { useHA } from "haService"; import { useHA } from "services/ha";
import { AutomationActionData } from "types/automations"; import { AutomationActionData } from "types/automations";
import { createUpdaterFromAutomationData } from "../updater"; import { createUpdaterFromAutomationData } from "../updater";
import { ModalState } from "../board/types"; import { ModalState } from "../board/types";
+1 -1
View File
@@ -1,6 +1,6 @@
import { FC, useState, ReactNode } from "react"; import { FC, useState, ReactNode } from "react";
import { AutomationSequenceNode } from "types/automations"; import { AutomationSequenceNode } from "types/automations";
import { useHA } from "haService"; import { useHA } from "services/ha";
import { ModalState } from "./board/types"; import { ModalState } from "./board/types";
import { createUpdater } from "./updater"; import { createUpdater } from "./updater";
import { useAutomationNodes } from "./elements"; import { useAutomationNodes } from "./elements";
@@ -13,7 +13,7 @@ import { prettyName } from "utils/formatting";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { useLang } from "lang"; import { useLang } from "services/lang";
export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> = export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
({ ({
@@ -16,7 +16,7 @@ import InputBoolean from "components/Inputs/Base/InputBoolean";
import { SpeedDial } from "components/SpeedDial"; import { SpeedDial } from "components/SpeedDial";
import { SequenceNodeElementProps } from "./types"; import { SequenceNodeElementProps } from "./types";
import { useSequenceNodeColor } from "./util"; import { useSequenceNodeColor } from "./util";
import { useLang } from "lang"; import { useLang } from "services/lang";
export const SequenceNodeElement: FC< export const SequenceNodeElement: FC<
PropsWithChildren<SequenceNodeElementProps> PropsWithChildren<SequenceNodeElementProps>
+2 -2
View File
@@ -6,9 +6,9 @@ import { InputDevice } from "components/Inputs/AutoComplete/InputDevice";
import { InputDeviceCapabilties } from "components/Inputs/AutoComplete/InputDeviceCapabilties"; import { InputDeviceCapabilties } from "components/Inputs/AutoComplete/InputDeviceCapabilties";
import { InputEntity } from "components/Inputs/AutoComplete/InputEntities"; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { cleanUpUndefined } from "utils/helpers"; import { cleanUpUndefined } from "utils/helpers";
import { DeviceBaseType, DeviceTypeCapability } from "haService/types"; import { DeviceBaseType, DeviceTypeCapability } from "services/ha/types";
import { AutomationDeviceState } from "types/automations/common"; import { AutomationDeviceState } from "types/automations/common";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type DeviceEditorProps<DBT extends DeviceBaseType> = { export type DeviceEditorProps<DBT extends DeviceBaseType> = {
type: "action" | "condition" | "trigger"; type: "action" | "condition" | "trigger";
+1 -1
View File
@@ -2,7 +2,7 @@ import "./ButtonIcons.css";
import Tooltip from "@mui/material/Tooltip"; import Tooltip from "@mui/material/Tooltip";
import { FC, ReactNode } from "react"; import { FC, ReactNode } from "react";
import IconButton, { IconButtonTypeMap } from "@mui/material/IconButton"; import IconButton, { IconButtonTypeMap } from "@mui/material/IconButton";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type ButtonIconProps = { export type ButtonIconProps = {
icon: ReactNode; icon: ReactNode;
@@ -3,7 +3,8 @@ import {
InputAutoComplete, InputAutoComplete,
InputAutoCompletePropsBase, InputAutoCompletePropsBase,
} from "./InputAutoComplete"; } from "./InputAutoComplete";
import { useHAAreas } from "haService/AreaRegistry"; import { useHAAreas } from "services/ha/AreaRegistry";
import { useLang } from "services/lang";
export type InputAreaProps = InputAutoCompletePropsBase & { export type InputAreaProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[]; restrictToDomain?: string[];
@@ -11,12 +12,13 @@ export type InputAreaProps = InputAutoCompletePropsBase & {
}; };
export const InputArea: FC<InputAreaProps> = (props) => { export const InputArea: FC<InputAreaProps> = (props) => {
const lang = useLang();
// state // state
const areas = useHAAreas(); const areas = useHAAreas();
return ( return (
<InputAutoComplete <InputAutoComplete
{...props} {...props}
label={props.label ?? "Area"} label={props.label ?? lang.get("AREA")}
getID={areas.getID} getID={areas.getID}
getLabel={areas.getLabel} getLabel={areas.getLabel}
options={areas.getOptions()} options={areas.getOptions()}
@@ -7,6 +7,7 @@ import Popper from "@mui/material/Popper";
import { SearchItem } from "./extras"; import { SearchItem } from "./extras";
import { ReactNode } from "react"; import { ReactNode } from "react";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { useLang } from "services/lang";
export type BaseOption<T = {}> = { export type BaseOption<T = {}> = {
id: string; id: string;
@@ -65,6 +66,7 @@ export function computeSimilarity(
export function InputAutoComplete<T extends Option>( export function InputAutoComplete<T extends Option>(
props: InputAutoCompleteProps<T> props: InputAutoCompleteProps<T>
) { ) {
const lang = useLang();
// aliases // aliases
const getID = (opt: T): string => { const getID = (opt: T): string => {
if (props.getID) { if (props.getID) {
@@ -212,7 +214,7 @@ export function InputAutoComplete<T extends Option>(
}} }}
variant="filled" variant="filled"
required={props.required} required={props.required}
label={props.label ?? "Entity ID"} label={props.label ?? lang.get("ENTITY_ID")}
helperText={helperText} helperText={helperText}
disabled={props.disabled} disabled={props.disabled}
error={error} error={error}
@@ -1,5 +1,6 @@
import { FC } from "react"; import { FC } from "react";
import { useHADeviceRegistry } from "haService"; import { useHADeviceRegistry } from "services/ha";
import { useLang } from "services/lang";
import { import {
InputAutoComplete, InputAutoComplete,
InputAutoCompletePropsBase, InputAutoCompletePropsBase,
@@ -9,11 +10,12 @@ export type InputDeviceProps = InputAutoCompletePropsBase;
export const InputDevice: FC<InputDeviceProps> = (props) => { export const InputDevice: FC<InputDeviceProps> = (props) => {
// state // state
const lang = useLang();
const dr = useHADeviceRegistry(); const dr = useHADeviceRegistry();
return ( return (
<InputAutoComplete <InputAutoComplete
{...props} {...props}
label={props.label ?? "Device"} label={props.label ?? lang.get("DEVICE")}
getID={dr.getID} getID={dr.getID}
getLabel={dr.getLabel} getLabel={dr.getLabel}
options={dr.getOptions()} options={dr.getOptions()}
@@ -1,5 +1,5 @@
import "./InputDeviceCapabilties.css"; import "./InputDeviceCapabilties.css";
import { HaFormSchema } from "haService/types"; import { HaFormSchema } from "services/ha/types";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { useRef } from "react"; import { useRef } from "react";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
@@ -1,5 +1,5 @@
import { FC } from "react"; import { FC } from "react";
import { useHAEntities } from "haService/HAEntities"; import { useHAEntities } from "services/ha/HAEntities";
import { import {
InputAutoComplete, InputAutoComplete,
InputAutoCompletePropsBase, InputAutoCompletePropsBase,
@@ -1,19 +1,27 @@
import { FC } from "react"; import { FC } from "react";
import { useHAServices } from 'haService'; import { useHAServices } from "services/ha";
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete'; import {
import { prettyName } from 'utils/formatting'; InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { prettyName } from "utils/formatting";
import { useLang } from "services/lang";
export type InputServiceProps = InputAutoCompletePropsBase & { multiple?: false }; export type InputServiceProps = InputAutoCompletePropsBase & {
multiple?: false;
};
export const InputService: FC<InputServiceProps> = props => { export const InputService: FC<InputServiceProps> = (props) => {
const services = useHAServices(); const services = useHAServices();
return <InputAutoComplete const lang = useLang();
{...props} return (
label={props.label ?? "Service"} <InputAutoComplete
options={services.getOptions()} {...props}
getID={services.getID} label={props.label ?? lang.get("SERVICE")}
getLabel={services.getLabel} options={services.getOptions()}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''} getID={services.getID}
getLabel={services.getLabel}
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
/> />
} );
};
@@ -12,6 +12,7 @@ import {
} from "utils/time"; } from "utils/time";
import { InputEntity } from "./InputEntities"; import { InputEntity } from "./InputEntities";
import { InputTime } from "components/Inputs/Base/InputTime"; import { InputTime } from "components/Inputs/Base/InputTime";
import { useLang } from "services/lang";
export type InputTimeEntityProps = { export type InputTimeEntityProps = {
value: string; value: string;
@@ -23,6 +24,7 @@ export const InputTimeEntity: FC<InputTimeEntityProps> = ({
onChange, onChange,
className = "", className = "",
}) => { }) => {
const lang = useLang();
const is24Hour = isAutomationTimeString24Hours(value); const is24Hour = isAutomationTimeString24Hours(value);
let editor: ReactNode; let editor: ReactNode;
if (is24Hour) { if (is24Hour) {
@@ -39,7 +41,7 @@ export const InputTimeEntity: FC<InputTimeEntityProps> = ({
} else { } else {
editor = ( editor = (
<InputEntity <InputEntity
label="Time Entity" label={lang.get("TIME_ENTITY")}
restrictMode="or" restrictMode="or"
restrictedDeviceClass={["timestamp"]} restrictedDeviceClass={["timestamp"]}
restrictToDomain={["input_datetime"]} restrictToDomain={["input_datetime"]}
@@ -1,5 +1,4 @@
import React, { ReactNode, useState } from "react"; import { ReactNode, useState } from "react";
import { useToolTip } from "tooltip/context";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
export interface Props { export interface Props {
@@ -22,19 +21,16 @@ export default function InputText({
label, label,
title, title,
helperText, helperText,
textBoxFor,
value = "", value = "",
onChange, onChange,
endAdornment, endAdornment,
onEnter = () => {}, onEnter = () => {},
additionalTooltipFilters = {},
multiline = false, multiline = false,
maxRows = 4, maxRows = 4,
className, className,
placeholder, placeholder,
required, required,
}: Props) { }: Props) {
const tooltip = useToolTip();
const [isFocused, setIsFocused] = useState(false); const [isFocused, setIsFocused] = useState(false);
return ( return (
<TextField <TextField
@@ -68,17 +64,6 @@ export default function InputText({
}} }}
onFocus={(e) => { onFocus={(e) => {
setIsFocused(true); setIsFocused(true);
if (textBoxFor) {
tooltip.setFocus(
e.target.getBoundingClientRect(),
{
searchObject: textBoxFor,
searchText: value,
filterObjects: additionalTooltipFilters,
},
onChange
);
}
}} }}
/> />
); );
+22 -15
View File
@@ -12,6 +12,7 @@ import {
} from "utils/time"; } from "utils/time";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "services/lang";
// constants // constants
const fields: Array<keyof AutomationTimeObject> = [ const fields: Array<keyof AutomationTimeObject> = [
@@ -29,6 +30,7 @@ export type InputTimeProps = {
}; };
export const InputTime: FC<InputTimeProps> = (props) => { export const InputTime: FC<InputTimeProps> = (props) => {
// state // state
const lang = useLang();
const [disabled, setDisabled] = useState(!props.value); const [disabled, setDisabled] = useState(!props.value);
const [displayValue, setDisplayValue] = useState( const [displayValue, setDisplayValue] = useState(
convertAutomationTimeToTimeObject(props.value) convertAutomationTimeToTimeObject(props.value)
@@ -127,21 +129,26 @@ export const InputTime: FC<InputTimeProps> = (props) => {
<div className={["input-time", props.className ?? ""].join(" ")}> <div className={["input-time", props.className ?? ""].join(" ")}>
{/* <InputLabel >{props.label}</InputLabel> */} {/* <InputLabel >{props.label}</InputLabel> */}
<div className="input-time--inner"> <div className="input-time--inner">
{fields.map((name) => ( {fields.map((name) => {
<TextField const label = prettyName(
key={name} lang.get(`TIME_UNITS_${name}`.toUpperCase())
variant="filled" );
label={prettyName(name)} return (
defaultValue="00" <TextField
InputProps={{ key={name}
disabled, variant="filled"
type: "number", label={label}
title: prettyName(name), defaultValue="00"
}} InputProps={{
value={displayValue[name] ?? 0} disabled,
onChange={(e) => updateOne(name)(e.target.value)} type: "number",
/> title: label,
))} }}
value={displayValue[name] ?? 0}
onChange={(e) => updateOne(name)(e.target.value)}
/>
);
})}
{!props.restrictEmpty && ( {!props.restrictEmpty && (
<ButtonIcon <ButtonIcon
onClick={() => setDisabled(!disabled)} onClick={() => setDisabled(!disabled)}
@@ -9,7 +9,7 @@ import FormHelperText from "@mui/material/FormHelperText";
import InputAdornment from "@mui/material/InputAdornment"; import InputAdornment from "@mui/material/InputAdornment";
import { Save } from "@mui/icons-material"; import { Save } from "@mui/icons-material";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang"; import { useLang } from "services/lang";
export interface Props<T extends {}> { export interface Props<T extends {}> {
label: string; label: string;
+1 -1
View File
@@ -7,7 +7,7 @@ import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select"; import Select from "@mui/material/Select";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { ReactNode } from "react"; import { ReactNode } from "react";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type Props<T extends string | Object> = { export type Props<T extends string | Object> = {
current?: T; current?: T;
@@ -5,7 +5,7 @@ import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import Checkbox from "@mui/material/Checkbox"; import Checkbox from "@mui/material/Checkbox";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { useLang } from "lang"; import { useLang } from "services/lang";
export interface Props<T extends string> { export interface Props<T extends string> {
label: string; label: string;
@@ -5,7 +5,7 @@ import CheckCircleOutlineOutlinedIcon from "@mui/icons-material/CheckCircleOutli
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined"; import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip"; import Tooltip from "@mui/material/Tooltip";
import { useLang } from "lang"; import { useLang } from "services/lang";
export type InputTextViewProps = { export type InputTextViewProps = {
className?: string; className?: string;
@@ -10,18 +10,18 @@ export const ActionEventState: OptionManager<FireEventAction> = {
event_data: {}, event_data: {},
}), }),
isReady: ({ alias, event }) => alias !== "" && event !== "", isReady: ({ alias, event }) => alias !== "" && event !== "",
renderOptionList: (state, setState) => { Component: ({ state, setState, langStore }) => {
const update = updateActionData(state, setState); const update = updateActionData(state, setState);
return ( return (
<> <>
<InputText <InputText
textBoxFor="event" textBoxFor="event"
label="Event" label={langStore.get("EVENT")}
value={state.event} value={state.event}
onChange={(event) => update({ event })} onChange={(event) => update({ event })}
/> />
<InputYaml <InputYaml
label="Event Data" label={langStore.get("EVENT_DATA")}
value={state.event_data} value={state.event_data}
onChange={(event_data) => update({ event_data })} onChange={(event_data) => update({ event_data })}
/> />
@@ -15,12 +15,12 @@ export const ActionRepeatState: OptionManager<RepeatAction> = {
}, },
}), }),
isReady: () => true, isReady: () => true,
Component: ({ state, setState }) => { Component: ({ state, setState, langStore }) => {
const repeatType = determineType(state.repeat); const repeatType = determineType(state.repeat);
return ( return (
<> <>
<InputAutoComplete <InputAutoComplete
label="Type" label={langStore.get("TYPE")}
value={repeatType} value={repeatType}
options={["while", "until", "count"]} options={["while", "until", "count"]}
onChange={(v) => { onChange={(v) => {
@@ -53,7 +53,7 @@ export const ActionRepeatState: OptionManager<RepeatAction> = {
/> />
{"count" in state.repeat && ( {"count" in state.repeat && (
<InputNumber <InputNumber
label="How many times?" label={langStore.get("HOW_MANY_TIMES")}
value={state.repeat.count} value={state.repeat.count}
onChange={(count = 1) => onChange={(count = 1) =>
setState({ setState({
@@ -7,11 +7,11 @@ export const ActionSceneState: OptionManager<SceneAction> = {
scene: "", scene: "",
}), }),
isReady: () => true, isReady: () => true,
Component: ({ state, setState }) => { Component: ({ state, setState, langStore }) => {
return ( return (
<> <>
<InputEntity <InputEntity
label="Scene" label={langStore.get("SCENE")}
restrictToDomain={["scene"]} restrictToDomain={["scene"]}
value={state.scene ?? ""} value={state.scene ?? ""}
onChange={(d) => setState({ ...state, scene: d ?? "" })} onChange={(d) => setState({ ...state, scene: d ?? "" })}
@@ -8,11 +8,11 @@ export const ActionStopState: OptionManager<StopAction> = {
stop: "", stop: "",
}), }),
isReady: () => true, isReady: () => true,
Component: ({ state, setState }) => { Component: ({ state, setState, langStore }) => {
return ( return (
<> <>
<InputText <InputText
label="Stop Reason" label={langStore.get("STOP_REASON")}
value={state.stop ?? []} value={state.stop ?? []}
onChange={(d) => setState({ ...state, stop: d })} onChange={(d) => setState({ ...state, stop: d })}
/> />
@@ -24,7 +24,7 @@ export const ActionWaitState: OptionManager<ThisAction> = {
delay: "", delay: "",
}), }),
isReady: () => true, isReady: () => true,
Component: ({ state, setState }) => { Component: ({ state, setState, langStore }) => {
// state // state
const update = updateActionData(state, setState); const update = updateActionData(state, setState);
const [current, _setCurrent] = useState(getCurrentOption(state)); const [current, _setCurrent] = useState(getCurrentOption(state));
@@ -63,7 +63,7 @@ export const ActionWaitState: OptionManager<ThisAction> = {
<> <>
<InputTime <InputTime
className="for" className="for"
label="for" label={langStore.get("FOR")}
value={(state as any).delay} value={(state as any).delay}
onChange={(delay) => update({ delay })} onChange={(delay) => update({ delay })}
/> />
@@ -87,7 +87,7 @@ export const ActionWaitState: OptionManager<ThisAction> = {
<> <>
<InputYaml <InputYaml
className="triggers" className="triggers"
label="Triggers" label={langStore.get("TRIGGERS")}
value={state.wait_for_trigger ?? []} value={state.wait_for_trigger ?? []}
onChange={(wait_for_trigger) => update({ wait_for_trigger })} onChange={(wait_for_trigger) => update({ wait_for_trigger })}
/> />
@@ -100,7 +100,7 @@ export const ActionWaitState: OptionManager<ThisAction> = {
<div className="node-editor--action-wait"> <div className="node-editor--action-wait">
<InputList <InputList
className="wait-type" className="wait-type"
label="Wait Type" label={langStore.get("WAIT_TYPE")}
prettyOptionLabels prettyOptionLabels
options={["template", "trigger", "delay"]} options={["template", "trigger", "delay"]}
current={current} current={current}
@@ -110,7 +110,7 @@ export const ActionWaitState: OptionManager<ThisAction> = {
{current !== "delay" ? ( {current !== "delay" ? (
<div className="wait-options"> <div className="wait-options">
<InputNumber <InputNumber
label="Timeout" label={langStore.get("TIMEOUT")}
value={ value={
(state as any).timeout (state as any).timeout
? Number((state as any).timeout) ? Number((state as any).timeout)
@@ -123,7 +123,7 @@ export const ActionWaitState: OptionManager<ThisAction> = {
} }
/> />
<InputBoolean <InputBoolean
label="Continue on Timeout" label={langStore.get("CONTINUTE_ON_TIMEOUT")}
value={(state as any).continue_on_timeout ?? false} value={(state as any).continue_on_timeout ?? false}
onChange={(continue_on_timeout) => onChange={(continue_on_timeout) =>
update({ continue_on_timeout }) update({ continue_on_timeout })
@@ -1,5 +1,6 @@
import { HAService } from "haService"; import { HAService } from "services/ha";
import { HAEntitiesState } from "haService/HAEntities"; import { HAEntitiesState } from "services/ha/HAEntities";
import { LangStore } from "services/lang";
import { FC } from "react"; import { FC } from "react";
import { AutomationAction } from "types/automations/actions"; import { AutomationAction } from "types/automations/actions";
import { AutomationCondition } from "types/automations/conditions"; import { AutomationCondition } from "types/automations/conditions";
@@ -21,6 +22,7 @@ export type OptionManager<T> = {
setState: (s: T) => void; setState: (s: T) => void;
ha: HAService; ha: HAService;
createMode: boolean; createMode: boolean;
langStore: LangStore;
}>; }>;
} }
); );
@@ -15,6 +15,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import { useState } from "react"; import { useState } from "react";
import AddIcon from "@mui/icons-material/Add"; import AddIcon from "@mui/icons-material/Add";
import { InputTimeEntity } from "components/Inputs/AutoComplete/InputTimeEntity"; import { InputTimeEntity } from "components/Inputs/AutoComplete/InputTimeEntity";
import { useLang } from "services/lang";
export const TriggerTime: OptionManager<AutomationTriggerTime> = { export const TriggerTime: OptionManager<AutomationTriggerTime> = {
defaultState: () => ({ defaultState: () => ({
@@ -115,10 +116,11 @@ export const TriggerTimePattern: FC<{
state: AutomationTriggerTimePattern; state: AutomationTriggerTimePattern;
setState: (t: AutomationTriggerTimePattern) => void; setState: (t: AutomationTriggerTimePattern) => void;
}> = ({ state, setState }) => { }> = ({ state, setState }) => {
const lang = useLang();
return ( return (
<div className="trigger-time--pattern"> <div className="trigger-time--pattern">
<InputText <InputText
label="Hours" label={lang.get("TIME_UNITS_HOURS")}
value={state.hours ?? ""} value={state.hours ?? ""}
onChange={(hours) => onChange={(hours) =>
setState({ setState({
@@ -128,7 +130,7 @@ export const TriggerTimePattern: FC<{
} }
/> />
<InputText <InputText
label="Minutes" label={lang.get("TIME_UNITS_MINUTES")}
value={state.minutes ?? ""} value={state.minutes ?? ""}
onChange={(minutes) => onChange={(minutes) =>
setState({ setState({
@@ -138,7 +140,7 @@ export const TriggerTimePattern: FC<{
} }
/> />
<InputText <InputText
label="Seconds" label={lang.get("TIME_UNITS_SECONDS")}
value={state.seconds ?? ""} value={state.seconds ?? ""}
onChange={(seconds) => onChange={(seconds) =>
setState({ setState({
@@ -10,10 +10,10 @@ import {
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import InputText from "components/Inputs/Base/InputText"; import InputText from "components/Inputs/Base/InputText";
import { getDescriptionFromAutomationNode } from "utils/formatting"; import { getDescriptionFromAutomationNode } from "utils/formatting";
import { useHA } from "haService"; import { useHA } from "services/ha";
import { Generic } from "./Generic"; import { Generic } from "./Generic";
import { getNodeTypeAndValidate } from "utils/automations"; import { getNodeTypeAndValidate } from "utils/automations";
import { useLang } from "lang"; import { useLang } from "services/lang";
type UseState = <S>(s: S) => [S, Dispatch<SetStateAction<S>>]; type UseState = <S>(s: S) => [S, Dispatch<SetStateAction<S>>];
@@ -158,6 +158,7 @@ export const useEditorNodeState = (
setState={setState} setState={setState}
ha={ha} ha={ha}
createMode={createMode} createMode={createMode}
langStore={langStore}
/> />
)} )}
</> </>
+2 -2
View File
@@ -8,7 +8,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import InputBoolean from "components/Inputs/Base/InputBoolean"; import InputBoolean from "components/Inputs/Base/InputBoolean";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { getNodeSubTypeDescription } from "./utils"; import { getNodeSubTypeDescription } from "./utils";
import { useLang } from "lang"; import { useLang } from "services/lang";
export interface NodeEditorProps { export interface NodeEditorProps {
node: AutomationNode; node: AutomationNode;
@@ -134,7 +134,7 @@ export const NodeEditor: FC<NodeEditorProps> = ({
areYouSureNotReady("close", true).then((ok) => ok && onClose()) areYouSureNotReady("close", true).then((ok) => ok && onClose())
} }
> >
Close {langStore.get("CLOSE")}
</Button> </Button>
<Button <Button
className="node-editor--footer--save" className="node-editor--footer--save"
+58 -40
View File
@@ -10,23 +10,28 @@ import {
import { BottomBar } from "components/BottomBar"; import { BottomBar } from "components/BottomBar";
import { SnackbarKey, SnackbarProvider, useSnackbar } from "notistack"; import { SnackbarKey, SnackbarProvider, useSnackbar } from "notistack";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import { useHAConnection } from "haService/connection"; import { useHAConnection } from "services/ha/connection";
import { ConfirmProvider } from "material-ui-confirm"; import { ConfirmProvider } from "material-ui-confirm";
import { Color } from "@mui/material"; import { Color, Skeleton, Theme } from "@mui/material";
import useWindowSize from "utils/useWindowSize"; import useWindowSize from "utils/useWindowSize";
import { ApiService } from "apiService/core"; import { ApiService } from "services/api/core";
import { ApiStateProvider, useMockApiService } from "apiService"; import { ApiStateProvider, useMockApiService } from "services/api";
import { LangProvider, LangStore, useLang } from "services/lang";
export type PageProps = PropsWithChildren<{ export type PageProps = PropsWithChildren<{
api: ApiService; api: ApiService;
}>; }>;
export const InternalPage: FC<PageProps> = ({ children, api }) => { export const BareInternalPage: FC<
PageProps & {
isMobile: boolean;
theme: Theme;
lang: LangStore;
}
> = ({ children, api, isMobile, theme, lang }) => {
const conn = useHAConnection(); const conn = useHAConnection();
const theme = useTheme();
const snackbar = useSnackbar(); const snackbar = useSnackbar();
const snackbarKeyHAConKey = useRef<SnackbarKey | null>(null); const snackbarKeyHAConKey = useRef<SnackbarKey | null>(null);
const { isMobile } = useWindowSize();
useEffect(() => { useEffect(() => {
if (conn.status === "error") { if (conn.status === "error") {
@@ -46,12 +51,6 @@ export const InternalPage: FC<PageProps> = ({ children, api }) => {
if (snackbarKeyHAConKey.current) { if (snackbarKeyHAConKey.current) {
snackbar.closeSnackbar(snackbarKeyHAConKey.current); snackbar.closeSnackbar(snackbarKeyHAConKey.current);
} }
snackbarKeyHAConKey.current = snackbar.enqueueSnackbar(
`Connecting to websocket...`,
{
variant: "info",
}
);
} else if (conn.status === "loaded") { } else if (conn.status === "loaded") {
if (snackbarKeyHAConKey.current) { if (snackbarKeyHAConKey.current) {
snackbar.closeSnackbar(snackbarKeyHAConKey.current); snackbar.closeSnackbar(snackbarKeyHAConKey.current);
@@ -60,17 +59,38 @@ export const InternalPage: FC<PageProps> = ({ children, api }) => {
}, [conn, snackbar]); }, [conn, snackbar]);
return ( return (
<main <ConfirmProvider
className={["page", "center column", isMobile ? "mobile" : ""].join(" ")} defaultOptions={{
cancellationText: lang.get("CLOSE"),
confirmationText: lang.get("CONFIRM"),
}}
> >
<div className="page-contents column">{children}</div> <main className={["page", "column", isMobile ? "mobile" : ""].join(" ")}>
<BottomBar api={api} /> <div className="page-contents column">{children}</div>
<style> <BottomBar api={api} />
{`:root { <style>
${convertPaletteToCss(theme.palette)} {`:root {
}`} ${convertPaletteToCss(theme.palette)}
</style> }`}
</main> </style>
</main>
</ConfirmProvider>
);
};
export const InternalPage: FC<PageProps> = ({ children, api }) => {
const theme = useTheme();
const { isMobile } = useWindowSize();
const lang = useLang();
if (!lang.ready) {
return <Skeleton />;
}
return (
<BareInternalPage api={api} isMobile={isMobile} theme={theme} lang={lang}>
{children}
</BareInternalPage>
); );
}; };
@@ -87,24 +107,22 @@ export const Page: FC<PageProps> = (props) => {
return ( return (
<ThemeProvider theme={theme}> <ThemeProvider theme={theme}>
<ConfirmProvider> <SnackbarProvider
<SnackbarProvider anchorOrigin={{
anchorOrigin={{ vertical: "bottom",
vertical: "bottom", horizontal: "center",
horizontal: "center", }}
}} ref={notistackRef}
ref={notistackRef} action={(key) => <Button onClick={onClickDismiss(key)}>Dismiss</Button>}
action={(key) => ( dense
<Button onClick={onClickDismiss(key)}>Dismiss</Button> preventDuplicate
)} >
dense <ApiStateProvider value={props.api.state}>
preventDuplicate <LangProvider>
>
<ApiStateProvider value={props.api.state}>
<InternalPage {...props} /> <InternalPage {...props} />
</ApiStateProvider> </LangProvider>
</SnackbarProvider> </ApiStateProvider>
</ConfirmProvider> </SnackbarProvider>
</ThemeProvider> </ThemeProvider>
); );
}; };
@@ -10,7 +10,7 @@ import {
} from "components/Inputs/AutoComplete/InputAutoComplete"; } from "components/Inputs/AutoComplete/InputAutoComplete";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import InputBoolean from "components/Inputs/Base/InputBoolean"; import InputBoolean from "components/Inputs/Base/InputBoolean";
import { SelectorNumber, SelectorText } from "haService/fieldTypes"; import { SelectorNumber, SelectorText } from "services/ha/fieldTypes";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { InputEntity } from "components/Inputs/AutoComplete/InputEntities"; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
@@ -1,7 +1,7 @@
import "./ServiceEditorTarget.css"; import "./ServiceEditorTarget.css";
import { InputDevice } from "components/Inputs/AutoComplete/InputDevice"; import { InputDevice } from "components/Inputs/AutoComplete/InputDevice";
import { InputEntity } from "components/Inputs/AutoComplete/InputEntities"; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { Targets } from "haService/fieldTypes"; import { Targets } from "services/ha/fieldTypes";
import { FC } from "react"; import { FC } from "react";
import { InputArea } from "components/Inputs/AutoComplete/InputArea"; import { InputArea } from "components/Inputs/AutoComplete/InputArea";
@@ -1,6 +1,6 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { ServiceEditor } from "."; import { ServiceEditor } from ".";
import { TypedHassService } from "haService/fieldTypes"; import { TypedHassService } from "services/ha/fieldTypes";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { makeStory } from "devUtils"; import { makeStory } from "devUtils";
@@ -1,7 +1,7 @@
import "./index.css"; import "./index.css";
import { cleanUpUndefined } from "utils/helpers"; import { cleanUpUndefined } from "utils/helpers";
import { TypedHassService } from "haService/fieldTypes"; import { TypedHassService } from "services/ha/fieldTypes";
import { FC, useState } from "react"; import { FC, useState } from "react";
import { import {
ServiceEditorOption, ServiceEditorOption,
@@ -1,5 +1,5 @@
import { BaseOption } from "components/Inputs/AutoComplete/InputAutoComplete"; import { BaseOption } from "components/Inputs/AutoComplete/InputAutoComplete";
import { FieldData, TypedHassService } from "haService/fieldTypes"; import { FieldData, TypedHassService } from "services/ha/fieldTypes";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
export type ServiceEditorData = { export type ServiceEditorData = {
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more