Compare commits

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

Adds ita.json

* added to userprofile

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

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

* Update fra.json

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

No files matched your search

+10
View File
@@ -36,4 +36,14 @@ If applicable, add screenshots to help explain your problem.
- Version [e.g. 22]
**Additional context**
- Home Assistant Version: [e.g. core-2022.5.4]
- Shortumation Version: [e.g. v0.7.0]
- Homeassistant server type: [e.g. raspberry pi 4 / intel nuc]
Add any other context about the problem here.
**Shortumation Logs**
```log
<--- copy here --->
```
+26 -137
View File
@@ -1,5 +1,31 @@
# Changelog ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge)
## [0.7.6] Bugfixes
- Less deadly error for invalid packages with better logs
- Update notification
## [0.7.4] Bugfixes
- Backend now correctly returns unset alias + description
## [0.7.1] Bugfixes + Italian!
- Added support for automations that do not have an `id`
- Added Italian
- Merged grammar fixes for french
- Fixed up strange centering styling bug
- Replaced more non-multilingual texts with multilingual text
## [0.7.0] Configuration Menu / Light Mode / Lang Support
- Added configuration menu
![image](https://user-images.githubusercontent.com/7451445/187817636-311b5a83-4e08-4b6b-b3b8-2e7086ace136.png)
- Experimental light mode
![image](https://user-images.githubusercontent.com/7451445/187817711-c7a8e23c-b9a4-472b-a348-c1492f3c5d56.png)
- First attempt at a french translation
- No longer using sqllite for automation db
## [0.6.3] - Packages Support & Minor UI improvements
- Full split config support for packages and all advance include directives (i.e. !include_dir_named, !include_dir_merge_list etc)
@@ -8,12 +34,6 @@
![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!
- Added visual support for split config (this was a heavy refactor!)
@@ -29,11 +49,6 @@
- Better global error capture
![image](https://user-images.githubusercontent.com/7451445/185441268-9dbde36e-b28b-4a13-bd7f-45ae23834e78.png)
## [0.5.3] - Bug Fixes
- Redirecting `/` to `/web` to resolve container install strangeness reported in https://github.com/asosnovsky/Shortumation/issues/125
- Fixed missing flag that caused the automation to explode in https://github.com/asosnovsky/Shortumation/issues/124
## [0.5.2] - Better Controls
- Add automation trigger
@@ -54,11 +69,6 @@
- Websockets now live-refresh when updates occur
## [0.4.0] - Depedency update
- Core dependency updates
- Python port is now dynamically set
## [0.3.4] - Condition/Trigger Editor Upgrades!
- Many condition editor fixes
@@ -75,19 +85,6 @@
![image](https://user-images.githubusercontent.com/7451445/180238004-4b04f13a-77a2-4c4c-9144-963dbc394bf4.png)
## [0.3.2] - Fixed Addon Image for arm-based devices
- Using hypercon instead of uvicorn (this losses the rust dependency which makes it easier to install on arm)
- Pre-building web assets outside of docker (this takes the image size down and speeds up instaltion of addon)
- Updated build scripts to actually fail installation when build/prep steps fail
- Ensured that builds for all architecture run successfully
- Re-worked github actions (quicker test phases)
## [0.3.1] - Increased Pagination + Restricted Repeat Node
- Increased pagination to display up to 10,000 autos for now
- Repeat node now has types
## [0.3.0] - Complete Refactor of Graphs
- Added visual support for
@@ -106,113 +103,5 @@
![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png)
## [0.1.22] - Many Visual improvements
- Deprecated several custom components in favor of mui.com
- Device Editor now has support for 99% of diplay types
- Condition Device is implemented
- Improved naming autogen for trigger & choose
## [0.1.21] - Service Editor
- first version of service editor
- reloading automations on save
## [0.1.20] - UI Bugfixes
- Using MUI elements for input time
- Added delay action / wait_on_triggers action
- Added enabled/disabled flag in node editor
- Optional flip vertical during desktop mode
- Fixed up modal clipping
## [0.1.19] - Vertical mobile mode
- in mobile mode we draw the graphs vertically now
## [0.1.17] - Websockets
- Connected to HA main websocket -- now we retrieve real-time information about
- Device names
- Entity names/ids
- Autocomplete for devices and entities
## [0.1.14] - Material UI + Autocomplete
- Brought some Material UI elements for input and text
- Autocomplete for tags
- Using 'id' as alias for trigger (as it seems to break HA otherwise)
- Not using 'alias' for conditions, always auto-generating it (again, this used to break HA)
- Added missing `data` object to service-actions
## [0.1.13] - YAML
- Better YAML
- Rewrote yaml parser/loader to use pyyaml and safe mode
- Cleaned up description vs alias
## [0.1.12] - Less Intense Error Messages
- Added more node-based errors (this way it's easier to see where validations failed)
- Made the validators less strict in order to capture more edge cases that HA supports
- Nicer auto-generated descriptions for some trigger nodes
## [0.1.10] - More Bug Fixes
- Allowing null or undefined values for metadata fields
- Trigger.platform==time will now have the .at property better supported
## [0.1.9] - Fixed up invalid types for various triggers
- Some triggers had invalid types and were causing a false-positive validation
## [0.1.8] - Support for Malformed Automations
- API will no longer error out on missing values or invalid lists
- Frontend has support for displaying bad automations
## [0.1.6] - Mobile Mode
- Improved mobile mode
- Fixed up arrow styles due to typos
- Added selection color
## [0.1.2] - Docker Hub Images
- Publishing images to docker hub is now stable
## [0.0.15] - Publish to dockerhub
- Publishing images to docker hub
## [0.0.14] - Using vanila ha yaml
- Supporing vanilla out of the box HA yaml as oppose to parsing them (no more $smType)
- Conditions have now a more a explicit node
## [0.0.13] - Better Styling with react-flow
- Fixed up styling (using react-flow)
- cleaned up some button styles
## [0.0.12] - Tags
- Added tag management system for automations
## [0.0.11] - Zoom
- Added lazy saving
## [0.0.10] - Zoom
- Introducing Zoom!
## [0.0.9] - First Working Version
- Instalable verion via github
- Initial POC done
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+1
View File
@@ -46,3 +46,4 @@ ENTRYPOINT [ "/app/bin/run.sh" ]
CMD [ "/app" ]
LABEL org.opencontainers.image.source https://github.com/asosnovsky/Shortumation
LABEL org.opencontainers.image.description "A better way to write automations in home-assistant without having to install and run a seperate automation engine!"
+3
View File
@@ -1,3 +1,6 @@
:no_entry: [DEPRECATED] Due to lack of time on my part, this project is no longer being worked on. :( :no_entry: [DEPRECATED]
----
# <img src="logo.png" height="40x"/> Shortumation ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=platsic)
[![Test](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml) [![Build](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml)
+5 -4
View File
@@ -1,8 +1,8 @@
get_index # unused function (src/api/app.py:41)
list_autos # unused function (src/api/routes/automations.py:14)
insert_auto # unused function (src/api/routes/automations.py:30)
update_auto # unused function (src/api/routes/automations.py:35)
delete_auto # unused function (src/api/routes/automations.py:45)
update_auto # unused function (src/api/routes/automations.py:37)
delete_auto # unused function (src/api/routes/automations.py:49)
read_details # unused function (src/api/routes/details.py:12)
read_profile # unused function (src/api/routes/details.py:24)
save_profile # unused function (src/api/routes/details.py:28)
@@ -26,5 +26,6 @@ _.automation_tags # unused property (src/hass_config/loader.py:28)
json_dumps # unused function (src/json_serializer.py:5)
theme # unused variable (src/user_profile.py:10)
lang # unused variable (src/user_profile.py:11)
SecretValue # unused class (src/yaml_serializer/__init__.py:48)
EnvVar # unused class (src/yaml_serializer/__init__.py:186)
flags # unused variable (src/user_profile.py:12)
SecretValue # unused class (src/yaml_serializer/__init__.py:55)
EnvVar # unused class (src/yaml_serializer/__init__.py:193)
+3 -3
View File
@@ -5,8 +5,8 @@ setuptools.setup(
python_requires=">=3.10",
install_requires=[
"PyYAML==6.0",
"fastapi==0.78.0",
"pydantic==1.9.1",
"fastapi==0.109.1",
"pydantic==1.10.13",
"hypercorn==0.13.2",
"python-decouple==3.6",
"websockets==10.3",
@@ -22,7 +22,7 @@ setuptools.setup(
"pre-commit==2.20.0",
"vulture==2.5",
"types-requests==2.28.4",
"types-PyYAML==6.0.11",
"types-PyYAML==6.0.12.20240311",
"requests==2.28.1",
],
},
+5 -1
View File
@@ -11,7 +11,7 @@ from src.hass_config.loader import HassConfig
def make_automation_router(hass_config: HassConfig) -> APIRouter:
router = APIRouter()
@router.post("/list")
@router.post("/list", response_model_exclude_unset=True, response_model_exclude_none=True)
def list_autos(body: ListParams) -> ListData[ExtenededAutomation]:
automations = AutomationManager(hass_config)
try:
@@ -29,11 +29,15 @@ def make_automation_router(hass_config: HassConfig) -> APIRouter:
@router.post("/item")
def insert_auto(body: Automation):
if body.id is None:
raise HTTPException(status_code=400, detail={"msg": "must contain an id"})
automations = AutomationManager(hass_config)
automations.create(body)
@router.put("/item")
def update_auto(body: ExtenededAutomation):
if body.id is None:
raise HTTPException(status_code=400, detail={"msg": "must contain an id"})
automations = AutomationManager(hass_config)
automations.update(body)
+6 -2
View File
@@ -11,14 +11,18 @@ logger = get_logger(__file__)
class AutomationDBConnection:
def __init__(self) -> None:
self.db: dict[str, ExtenededAutomation] = {}
self.missing_id_db: list[ExtenededAutomation] = []
def reset(self):
self.db = {}
self.missing_id_db = []
def insert_automations(self, automations: list[ExtenededAutomation]):
repeated_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
else:
repeated_automations.append(
@@ -33,7 +37,7 @@ class AutomationDBConnection:
raise DBNoAutomationFound(automation_id)
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:
yield auto
+4
View File
@@ -17,6 +17,10 @@ class FailedDeletion(AutomationLoaderException):
pass
class InvalidPackage(AutomationLoaderException):
pass
class DBError(Exception):
pass
+69 -51
View File
@@ -1,4 +1,3 @@
from itertools import chain
from pathlib import Path
from typing import Any, Iterator, Tuple, Union
@@ -16,7 +15,7 @@ from src.yaml_serializer import (
)
from ..hass_config.loader import HassConfig
from .errors import InvalidAutomationFile
from .errors import InvalidAutomationFile, InvalidPackage
from .tags import TagManager
from .types import (
AutomationExtractedIter,
@@ -46,7 +45,9 @@ def load_and_iter_automations(
elif isinstance(ref, InlineAutomation):
yield from load_automation_inline_ref(hass_config.root_path, tag_manager, ref)
else:
raise AssertionError(f"ref has an invalid type of {type(ref)} = {ref}")
raise logger.error(
AssertionError(f"ref has an invalid type of {type(ref)} = {ref}")
)
except InvalidAutomationFile as e:
logger.error(e)
@@ -56,12 +57,17 @@ def extract_automation_refs(
) -> AutomationExtractedIter:
found = False
for ref in chain(
extract_automation_root_refs(hass_config), extract_automation_package_refs(hass_config)
):
for ref in extract_automation_root_refs(hass_config):
found = True
yield ref
try:
for ref in extract_automation_package_refs(hass_config):
found = True
yield ref
except InvalidPackage as err:
logger.fatal(err)
if not found:
yield IncludedAutoamtion([""], IncludedYaml(hass_config.root_path / "automations.yaml"))
@@ -80,7 +86,7 @@ def extract_automation_root_refs(
source_file=hass_config.get_configuration_path(),
)
else:
logger.warning(f"found an invalid type in {key}!")
logger.error(f"found an invalid type in {key}!")
def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtractedIter:
@@ -93,7 +99,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
packages,
)
elif isinstance(packages_config, IncludedYamlDirList):
raise AssertionError("cannot configure packages with 'included_dir_list' directive")
raise InvalidPackage("cannot configure packages with 'included_dir_list' directive")
elif isinstance(packages_config, IncludedYamlDirNamed):
packages = packages_config.to_normalized_json(use_path_as_keys=True)
for package_path, package in packages.items():
@@ -109,7 +115,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
package_set,
) in iter(packages_config):
if not isinstance(package_set, dict):
raise AssertionError(
raise InvalidPackage(
f"expected {pacakge_set_path} to be a dictionary but got {type(package_set)}"
)
yield from extract_automation_inline_package_refs(
@@ -124,7 +130,7 @@ def extract_automation_package_refs(hass_config: HassConfig) -> AutomationExtrac
packages_config,
)
else:
raise AssertionError("configurations.homeassistant.packages must be a dictionary!")
raise InvalidPackage("configurations.homeassistant.packages must be a dictionary!")
def extract_automation_inline_package_refs(
@@ -134,44 +140,48 @@ def extract_automation_inline_package_refs(
ignore_package_name=False,
) -> AutomationExtractedIter:
for package_name, package_data in packages_config.items():
if isinstance(package_data, IncludedYaml):
package_mapping = package_data.to_normalized_json()
yield from extract_automation_from_package(
package_data=package_mapping,
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif isinstance(package_data, IncludedYamlDirList):
raise NotImplementedError(package_data)
elif isinstance(package_data, IncludedYamlDirNamed):
for package_key_path in package_data.to_normalized_json(True).keys():
if package_key_path.stem == "automation":
yield IncludedAutoamtion(
configuration_key=[package_name], ref=IncludedYaml(package_key_path)
)
elif isinstance(package_data, IncludedYamlDirMergedNamed):
for data_path, data_set in iter(package_data):
logger.info(f"Loading package={package_name}:{type(package_data)} from {package_data}")
try:
if isinstance(package_data, IncludedYaml):
package_mapping = package_data.to_normalized_json()
yield from extract_automation_from_package(
package_data=package_mapping,
package_name=package_name,
package_data=data_set,
source_file=data_path,
prefix_config_keys=[],
ignore_package_name=True,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif isinstance(package_data, dict):
yield from extract_automation_from_package(
package_data=package_data,
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
else:
raise AssertionError(
f"configurations.homeassistant.packages[{package_name}] must be a dictionary!"
)
elif isinstance(package_data, IncludedYamlDirList):
raise NotImplementedError(package_data)
elif isinstance(package_data, IncludedYamlDirNamed):
for package_key_path in package_data.to_normalized_json(True).keys():
if package_key_path.stem == "automation":
yield IncludedAutoamtion(
configuration_key=[package_name], ref=IncludedYaml(package_key_path)
)
elif isinstance(package_data, IncludedYamlDirMergedNamed):
for data_path, data_set in iter(package_data):
yield from extract_automation_from_package(
package_name=package_name,
package_data=data_set,
source_file=data_path,
prefix_config_keys=[],
ignore_package_name=True,
)
elif isinstance(package_data, dict):
yield from extract_automation_from_package(
package_data=package_data,
package_name=package_name,
source_file=source_file,
prefix_config_keys=prefix_config_keys,
ignore_package_name=ignore_package_name,
)
elif package_data is not None:
raise InvalidPackage(
f"configurations.homeassistant.packages.{package_name} must be a dictionary but got {type(package_data)}!"
)
except InvalidPackage as err:
logger.error(err)
def extract_automation_from_package(
@@ -236,9 +246,11 @@ def load_automation_inline_ref(
) -> Iterator[ExtenededAutomation]:
for auto in inline_automation.automations:
try:
cleaned_automation = clean_automation(auto)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation(
**clean_automation(auto),
tags=tag_manager.get(auto["id"], {}),
**cleaned_automation,
tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=inline_automation.configuration_key,
source_file=str(inline_automation.source_file.resolve().relative_to(root_path)),
source_file_type="inline",
@@ -286,9 +298,11 @@ def load_automation_path(
if isinstance(automations, dict):
try:
cleaned_automation = clean_automation(automations)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation(
**clean_automation(automations),
tags=tag_manager.get(automations["id"], {}),
**cleaned_automation,
tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="obj",
@@ -305,9 +319,11 @@ def load_automation_path(
return
for automation in automations:
try:
cleaned_automation = clean_automation(automation)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation(
**clean_automation(automation),
tags=tag_manager.get(automation["id"], {}),
**cleaned_automation,
tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="list",
@@ -324,6 +340,8 @@ def load_automation_path(
def clean_automation(auto_raw: dict):
return {
**auto_raw,
"alias": auto_raw.get("alias", "") or "",
"description": auto_raw.get("description", "") or "",
"condition": ifempty_or_null_then_list(load_conditions(auto_raw.get("condition", []))),
"action": ifempty_or_null_then_list(load_conditions(auto_raw.get("action", []))),
"trigger": ifempty_or_null_then_list(normalize_obj(auto_raw.get("trigger", []))),
+4
View File
@@ -84,6 +84,8 @@ class AutomationManager:
)
def update(self, automation: ExtenededAutomation, create_if_not_found: bool = False):
if automation.id is None:
raise AssertionError("automation.id must be defined to update!")
automation_path = self.hass_config.root_path / automation.source_file
if not automation_path.parent.exists():
automation_path.parent.mkdir(parents=True)
@@ -150,6 +152,8 @@ class AutomationManager:
self.tag_manager.save(self.tag_path)
def delete(self, automation: ExtenededAutomation):
if automation.id is None:
raise AssertionError("automation.id must be defined to update!")
automation_path = self.hass_config.root_path / automation.source_file
if automation.source_file_type == "obj":
automation_path.unlink(missing_ok=True)
+3 -3
View File
@@ -32,9 +32,9 @@ AutomationExtractedIter = Iterator[ExtractedAutomation]
class BaseAutomation(BaseModel):
id: str
alias: Optional[str] = None
description: Optional[str] = None
id: Optional[str]
alias: str = ""
description: str = ""
trigger_variables: Optional[dict[str, Union[str, int, bool, float]]] = None
mode: str = "single"
trigger: list[dict] = []
+3 -2
View File
@@ -1,6 +1,6 @@
from typing import Literal
from typing import Dict, Literal
from pydantic import BaseModel
from pydantic import BaseModel, Field
from src.hass_config import HassConfig
from src.yaml_serializer import dump_yaml, load_yaml
@@ -9,6 +9,7 @@ from src.yaml_serializer import dump_yaml, load_yaml
class UserProfile(BaseModel):
theme: Literal["dark", "light"] = "dark"
lang: str = "eng"
flags: Dict[str, bool] = Field(default_factory=dict)
@classmethod
def from_hass_config(cls, hass_config: HassConfig):
+10 -3
View File
@@ -1,21 +1,28 @@
from pathlib import Path
from typing import Iterator, NamedTuple, Tuple, Union
from typing import Iterator, NamedTuple, Tuple
from yaml.nodes import Node
from src.logger import get_logger
from .manager import YamlManager
dump_yaml = YamlManager.dump_yaml
load_yaml = YamlManager.load_yaml
logger = get_logger(__file__)
def load_dir_yaml(folder_or_file: Path) -> Iterator[Tuple[Path, dict | list]]:
if folder_or_file.is_dir():
for file in folder_or_file.iterdir():
yield from load_dir_yaml(file)
else:
with folder_or_file.open("r") as fp:
yield folder_or_file, load_yaml(fp, root_path=folder_or_file.parent)
if folder_or_file.suffix.lower() == ".yaml":
with folder_or_file.open("r") as fp:
yield folder_or_file, load_yaml(fp, root_path=folder_or_file.parent)
else:
logger.info(f"Ignoring the file {folder_or_file}")
@YamlManager.as_constructor("!include")
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -1 +1,38 @@
automation: !include ../automations/ui.yaml
media_player:
- platform: template
media_players:
receiver:
friendly_name: Receiver
current_source_template: "{{ states('input_text.selected_source') }}"
value_template: >
{% if is_state("input_boolean.receiver_on", "on") -%}
on
{%- else -%}
off
{%- endif %}
turn_on:
service: switch.turn_on
data_template:
entity_id: switch.receiver_on
turn_off:
service: switch.turn_on
data_template:
entity_id: switch.receiver_off
volume_up:
service: switch.turn_on
data_template:
entity_id: switch.volume_up
volume_down:
service: switch.turn_on
data_template:
entity_id: switch.vol
input_templates:
source 1:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_1
source 2:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_2
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,30 @@
# Loads default set of integrations. Do not remove.
default_config:
# Text to speech
tts:
- platform: google_translate
# automation manual: !include_dir_list ./automations/include_dir_list
# automation ui: !include automations/ui.yaml
# automation: !include automations/base.yaml
# automation cools: !include_dir_merge_list automations/include_dir_merge_list
script: !include scripts.yaml
scene: !include scenes.yaml
automation:
- alias: inline-auto
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
homeassistant:
packages: !include packages.yaml
+16
View File
@@ -0,0 +1,16 @@
ha: !include packages/ha.yaml
sub: !include_dir_merge_named packages/sub
secret_ones:
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
@@ -0,0 +1 @@
automation: !include ../automations/ui.yaml
@@ -0,0 +1,7 @@
# all the packages!
This is really cool :)
- A list item!
<<more thisngs!>>
@@ -0,0 +1,13 @@
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
Whitespace-only changes.
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
media_player: !include_dir_list ../entities/media_players
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
# media_player: !include_dir_list ../entities/media_players
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1 @@
media_player:
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,2 @@
homeassistant:
packages: !include_dir_named integrations
@@ -0,0 +1 @@
- platform: media
@@ -0,0 +1 @@
automation: !include ../automations.yaml
@@ -0,0 +1,16 @@
- platform: ping
host: 192.168.0.119
name: "Ping Pc Tv"
scan_interval: 10
- platform: ping
host: 192.168.0.181
name: "Ping Living Room Tv"
scan_interval: 10
- platform: ping
host: 192.168.0.100
name: "Ping Printer"
scan_interval: 15
- platform: ping
host: 192.168.0.177
name: "Ping Broadlink"
scan_interval: 15
@@ -0,0 +1 @@
media_player: !include_dir_list ../entities/media_players
+2 -2
View File
@@ -249,7 +249,7 @@ class automation_update_tests(BaseTestCase):
)
autos = resp.json()["data"]
self.assertEqual(resp.json()["totalItems"], self.test_params["total"])
self.assertNotIn("i am new", set([a["id"] for a in autos]))
self.assertNotIn("i am new", set([a.get("id", "") for a in autos]))
resp = self.client.post(
"/automations/item",
json=Automation(
@@ -262,7 +262,7 @@ class automation_update_tests(BaseTestCase):
)
data = resp.json()
self.assertEqual(data["totalItems"], self.test_params["total"] + 1)
self.assertIn("i am new", set([a["id"] for a in data["data"]]))
self.assertIn("i am new", set([a.get("id", "") for a in data["data"]]))
def test_update_some(self):
resp = self.client.post(
@@ -21,6 +21,11 @@ from tests.utils import (
HA_CONFIG10_EXAMPLE,
HA_CONFIG11_EXAMPLE,
HA_CONFIG12_EXAMPLE,
HA_CONFIG13_EXAMPLE,
HA_CONFIG14_EXAMPLE,
HA_CONFIG15_EXAMPLE,
HA_CONFIG16_EXAMPLE,
HA_CONFIG17_EXAMPLE,
HA_CONFIG_EXAMPLE,
)
@@ -160,6 +165,11 @@ class loader_tests(TestCase):
(HA_CONFIG10_EXAMPLE, 3),
(HA_CONFIG11_EXAMPLE, 3),
(HA_CONFIG12_EXAMPLE, 4),
(HA_CONFIG13_EXAMPLE, 4),
(HA_CONFIG14_EXAMPLE, 1),
(HA_CONFIG15_EXAMPLE, 1),
(HA_CONFIG16_EXAMPLE, 1),
(HA_CONFIG17_EXAMPLE, 1),
]:
with self.subTest(config_name=ha_path.name, expected=expected):
hass_config = HassConfig(ha_path)
@@ -65,6 +65,52 @@ class dumping_yamls_tests(TestCase):
},
)
def test_load_template_in_yaml(self):
yaml_obj = load_yaml(
io.StringIO(
"""
- id: '1652069225859'
alias: 'Lower the volume'
description: ''
mode: single
trigger:
- platform: state
entity_id: input_number.preferred_temperature
condition: []
action:
- service: media_player.volume_set
data_template:
entity_id: media_player.denon_avr_x2500h
volume_level: '{{ ((states(''input_number.volume_video'')|int)+80)/100 }}'
"""
),
Path.cwd(),
)
self.assertIsInstance(yaml_obj, list)
self.assertEqual(len(yaml_obj), 1)
self.assertDictEqual(
dict(yaml_obj[0]),
{
"id": "1652069225859",
"alias": "Lower the volume",
"description": "",
"mode": "single",
"trigger": [
{"platform": "state", "entity_id": "input_number.preferred_temperature"}
],
"condition": [],
"action": [
{
"service": "media_player.volume_set",
"data_template": {
"entity_id": "media_player.denon_avr_x2500h",
"volume_level": "{{ ((states('input_number.volume_video')|int)+80)/100 }}",
},
}
],
},
)
def test_load_stub(self):
yaml_obj = load_yaml(
io.StringIO(
+5
View File
@@ -22,6 +22,11 @@ HA_CONFIG9_EXAMPLE = SAMPLES_FOLDER / "config-9"
HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10"
HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11"
HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12"
HA_CONFIG13_EXAMPLE = SAMPLES_FOLDER / "config-13"
HA_CONFIG14_EXAMPLE = SAMPLES_FOLDER / "config-14"
HA_CONFIG15_EXAMPLE = SAMPLES_FOLDER / "config-15"
HA_CONFIG16_EXAMPLE = SAMPLES_FOLDER / "config-16"
HA_CONFIG17_EXAMPLE = SAMPLES_FOLDER / "config-17"
def get_example_automation_loader(
+2 -2
View File
@@ -1,7 +1,7 @@
name: Shortumation
version: v0.6.3
version: v0.7.6
slug: shortumation
image: asosnovsky/shortumation-{arch}
image: "asosnovsky/shortumation-{arch}"
url: "https://github.com/asosnovsky/Shortumation"
description: "A homeassitant addon which provides better UI for automations & scripts."
arch:
+5 -5
View File
@@ -6,19 +6,19 @@
"dependencies": {
"@emotion/react": "11.9.3",
"@emotion/styled": "11.9.3",
"@mui/icons-material": "5.8.4",
"@mui/material": "5.8.6",
"@mui/icons-material": "5.10.6",
"@mui/material": "5.10.6",
"@mui/styles": "5.8.6",
"@types/jest": "28.1.8",
"@types/node": "17.0.36",
"@types/react": "18.0.18",
"@types/react-dom": "18.0.6",
"@types/react": "18.0.25",
"@types/react-dom": "18.0.8",
"@types/ws": "8.5.3",
"@uiw/react-codemirror": "4.10.4",
"autosuggest-highlight": "3.3.4",
"home-assistant-js-websocket": "7.1.0",
"jss": "10.9.2",
"material-ui-confirm": "3.0.4",
"material-ui-confirm": "3.0.6",
"notistack": "2.0.5",
"react": "18.2.0",
"react-cookie": "4.1.1",
+1 -1
View File
@@ -1,7 +1,7 @@
import "./App.css";
import { Routes, Route, BrowserRouter } from "react-router-dom";
import { AutomationRoute } from "routes/automation";
import { useConnectedApiService } from "apiService";
import { useConnectedApiService } from "services/api";
import { ErrorBoundary } from "components/ErrorBoundary";
import { CookiesProvider } from "react-cookie";
import { Page } from "components/Page";
@@ -14,7 +14,7 @@ const { componentMeta, make } = makeStory({
}) => {
const [[metadata, tags], setState] = useState([args.metadata, args.tags]);
const tagDB = useTagDB(
[{ id: metadata.id, tags: Object.fromEntries(tags) }],
metadata.id ? [{ id: metadata.id, tags: Object.fromEntries(tags) }] : [],
(_, t) => setState([metadata, Object.entries(t)])
);
@@ -10,7 +10,7 @@ import { AddIcon, TrashIcon } from "components/Icons";
import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "components/AutomationManager/TagDB";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
import { useLang } from "services/lang";
export interface AutoInfoBoxProps {
metadata: AutomationMetadata & Partial<AutomationShortumationMetadata>;
@@ -104,7 +104,7 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
<div className="automation-editor--info-box-inner">
<InputText
label={langStore.get("ID")}
value={metadata.id}
value={metadata.id ?? langStore.get("N/A")}
onChange={onUpdateMetadata("id")}
/>
<InputText
@@ -125,7 +125,7 @@ export const AutoInfoBox: FC<AutoInfoBoxProps> = ({
options={["parallel", "single", "queued", "restart"]}
/>
<div className="automation-editor--info-box--tags">
<h1>Tags</h1>
<h1>{langStore.get("TAGS")}</h1>
<div className="automation-editor--info-box--tag-list">
{tags.map(([tagName, tagValue], tagIndex) => (
<div key={tagIndex} className="automation-editor--info-box--tag">
@@ -1,9 +0,0 @@
.automation-editor--nodes-row .collection-nodes--wrap {
--node-height: 12em !important;
--node-width: 100% !important;
}
.automation-editor--nodes-row .collection-nodes--wrap .collection-nodes {
min-width: 90%;
min-height: 10em;
}
@@ -1,40 +0,0 @@
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { makeStory } from "devUtils";
import { useState } from "react";
import { NodesRow } from ".";
const { make, componentMeta } = makeStory({
Component: NodesRow,
BaseTemplate: (props) => {
const [data, setData] = useState(props.data);
return (
<NodesRow
{...props}
data={data}
onUpdate={(up) => {
setData(up);
props.onUpdate(up);
}}
/>
);
},
meta: {
title: "App/AutomationEditor/NodesRow",
args: {
data: [],
sequenceNodeDims: DEFAULT_DIMS.node,
},
},
});
export default componentMeta;
export const Empty = make({});
export const One = make({
type: "trigger",
data: [
{
platform: "calendar",
event: "test",
},
],
});
@@ -1,42 +0,0 @@
import "./index.css";
import { AutomationNode, AutomationNodeMapping } from "types/automations";
import { useHA } from "haService";
import { CollectionNodeElement } from "components/DAGGraph/nodes/CollectionNode/CollectionNodeElement";
import { getDescriptionFromAutomationNode } from "utils/formatting";
import { Size } from "components/DAGGraph/elements/types";
export type NodesRowProps<
K extends keyof AutomationNodeMapping,
T extends AutomationNode<K>
> = {
type: K;
data: T[];
onUpdate: (d: T[]) => void;
sequenceNodeDims: Size;
};
export function NodesRow<
K extends keyof AutomationNodeMapping,
T extends AutomationNode<K>
>({ type: collectionType, data, sequenceNodeDims }: NodesRowProps<K, T>) {
const { namer } = useHA();
return (
<div className="automation-editor--nodes-row">
<CollectionNodeElement
width={0}
height={0}
nodes={data.map((node) => ({
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
onXClick: () => {},
}))}
onAddNode={() => {}}
collectionType={collectionType}
title="if"
sequenceNode={sequenceNodeDims}
flipped
/>
</div>
);
}
@@ -127,4 +127,13 @@
.automation-editor--info-box--buttons {
display: flex;
gap: 1em;
}
.automation-editor.fullscreen .automation-editor--flow-wrapper--toolbar--title {
display: none;
}
.automation-editor.fullscreen .automation-editor--flow-wrapper--toolbar {
justify-content: flex-end;
margin-top: 0.5em;
}
@@ -19,7 +19,7 @@ const { make, componentMeta } = makeStory({
<AutomationEditor
{...args}
tagDB={useTagDB(
state ? [{ id: state.id, tags: state.tags }] : [],
state && state.id ? [{ id: state.id, tags: state.tags }] : [],
() => {}
)}
automation={state}
@@ -2,7 +2,6 @@ import "./index.css";
import "./index.mobile.css";
import { FC, useState } from "react";
import { useCookies } from "react-cookie";
import Skeleton from "@mui/material/Skeleton";
import LinearProgress from "@mui/material/LinearProgress";
@@ -11,7 +10,6 @@ import SpeedDialAction from "@mui/material/SpeedDialAction";
import SpeedDialIcon from "@mui/icons-material/SettingsRounded";
import UndoIcon from "@mui/icons-material/UndoSharp";
import Icon from "@mui/material/Icon";
import EditIcon from "@mui/icons-material/ModeEditOutlineTwoTone";
import DeleteIcon from "@mui/icons-material/DeleteForever";
import { CheckMarkIcon } from "components/Icons";
@@ -31,8 +29,19 @@ import { MiniFailure } from "types/validators/helper";
import { AutoInfoBox } from "./AutoInfoBox";
import { useAutomatioEditorState, EditorData } from "./state";
import { useLang } from "lang";
import { useLang } from "services/lang";
import { useSnackbar } from "notistack";
import { Alert } from "@mui/material";
import { useUserProfile } from "services/api";
import {
ControlButton,
ReactFlowProvider,
useReactFlow,
} from "react-flow-renderer";
import FitInIcon from "@mui/icons-material/FitScreenRounded";
import FullscreenIcon from "@mui/icons-material/FullscreenRounded";
import FullscreenExitIcon from "@mui/icons-material/FullscreenExitRounded";
import { useEffect } from "react";
interface Props {
automation?: AutomationData | BareAutomationData;
dims: DAGDims;
@@ -41,18 +50,31 @@ interface Props {
onDelete: () => void;
tagDB: TagDB;
isNew?: boolean;
readonly: boolean;
issue?: string;
}
export const AutomationEditor: FC<Props> = ({
export const AutomationEditor: FC<Props> = (props) => {
return (
<ReactFlowProvider>
<AutomationEditorInner {...props} />
</ReactFlowProvider>
);
};
export const AutomationEditorInner: FC<Props> = ({
dims,
automation: propsAutos,
onUpdate: propsOnUpdate,
onDelete,
onTrigger,
tagDB,
isNew,
readonly,
issue,
}) => {
// state
const reactFlow = useReactFlow();
const userProfile = useUserProfile();
const langStore = useLang();
const snackbr = useSnackbar();
const {
state,
updateSequence,
@@ -63,17 +85,28 @@ export const AutomationEditor: FC<Props> = ({
save,
saveAndUpdate,
undo,
} = useAutomatioEditorState(propsAutos, propsOnUpdate);
} = useAutomatioEditorState(propsAutos, (auto) => {
if (readonly) {
snackbr.enqueueSnackbar(langStore.get("READONLY_CANNOT_UPDATE"), {
color: "warning",
});
} else {
propsOnUpdate(auto);
}
});
const [infoBoxOpen, setInfoBox] = useState(false);
const [
{ ckFlipped },
setCookies,
// eslint-disable-next-line
_,
] = useCookies(["ckFlipped"]);
const [fullScreenMode, setFullScreenMode] = useState(false);
// alias
const flipped = dims.flipped ? true : ckFlipped === "1";
const setFlipped = (v: boolean) => setCookies("ckFlipped", v ? "1" : "0");
const flipped = userProfile.flags.flipped ?? !dims.flipped;
const useNodesRow = userProfile.flags.useNodesRow !== false;
// effect
useEffect(() => {
if (reactFlow) {
setTimeout(() => {
reactFlow.fitView();
}, 500);
}
}, [flipped, fullScreenMode, reactFlow]);
// render
if (state.status === "loading") {
return (
@@ -95,7 +128,14 @@ export const AutomationEditor: FC<Props> = ({
);
}
return (
<div className={["automation-editor", state.status].join(" ")}>
<div
className={[
"automation-editor",
state.status,
readonly ? "readonly" : "",
fullScreenMode ? "fullscreen" : "",
].join(" ")}
>
{state.status === "saving" && (
<LinearProgress className="linear-loader" />
)}
@@ -112,13 +152,15 @@ export const AutomationEditor: FC<Props> = ({
state.status,
].join(" ")}
>
<Button onClick={() => setInfoBox(false)}>Close</Button>
<Button onClick={() => setInfoBox(false)}>
{langStore.get("CLOSE")}
</Button>
<Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save}
disabled={state.status !== "changed"}
disabled={state.status !== "changed" || readonly}
>
Save <CheckMarkIcon color="#bf4" />
{langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button>
</div>
</AutoInfoBox>
@@ -198,15 +240,6 @@ export const AutomationEditor: FC<Props> = ({
}
/>
</div>
{!dims.flipped && (
<Button
className={"automation-editor--flow-wrapper--toolbar--flip-btn"}
onClick={() => setFlipped(!flipped)}
>
<Icon>{flipped ? "flip_to_front" : "flip_to_back"}</Icon>
{langStore.get("FLIPP")}
</Button>
)}
{state.status === "changed" && (
<Button onClick={undo}>
<UndoIcon />
@@ -220,6 +253,11 @@ export const AutomationEditor: FC<Props> = ({
{langStore.get("SAVE")} <CheckMarkIcon color="#bf4" />
</Button>
</div>
{readonly && (
<Alert color="warning">
{langStore.get("READONLY_MODE")} - {issue}
</Alert>
)}
<DAGAutomationGraph
action={state.data.action}
trigger={state.data.trigger}
@@ -228,6 +266,17 @@ export const AutomationEditor: FC<Props> = ({
onTriggerUpdate={updateTrigger}
onConditionUpdate={updateCondition}
isFlipped={flipped}
useNodesRow={useNodesRow}
additionalControls={
<>
<ControlButton onClick={() => setFullScreenMode(!fullScreenMode)}>
{fullScreenMode ? <FullscreenExitIcon /> : <FullscreenIcon />}
</ControlButton>
<ControlButton onClick={() => reactFlow.fitView()}>
<FitInIcon />
</ControlButton>
</>
}
/>
<SpeedDial
ariaLabel="options label"
@@ -306,16 +355,14 @@ export const ValidationBox: FC<{
<div className="automation-editor-failures">
<ul>
{failures.map((f, i) => (
<>
<li key={i}>
<b>{f.path}</b>:
<ul>
{f.message.map((m, j) => (
<li key={j}>{m}</li>
))}
</ul>
</li>
</>
<li key={i}>
<b>{f.path}</b>:
<ul>
{f.message.map((m, j) => (
<li key={j}>{m}</li>
))}
</ul>
</li>
))}
</ul>
<span>{langStore.get("VALIDATION_PLEASE_CORRECT_FILE")}</span>
@@ -23,6 +23,7 @@ const { make, componentMeta } = makeStory({
id: "1",
title: "Example",
entityId: "automation.1",
readonly: false,
description: "Amazing automation!",
tags: {},
state: "on",
@@ -38,6 +39,7 @@ const { make, componentMeta } = makeStory({
id: "2",
title: "Example 2",
entityId: "automation.2",
readonly: false,
description: "Cool!",
state: "on",
source_file: "automation.yaml",
@@ -89,6 +91,7 @@ export const Nested = make({
entityId: "automation.1",
description: "",
title: "Automation #1",
readonly: false,
state: "on",
source_file: "automation.yaml",
source_file_type: "list",
@@ -102,6 +105,7 @@ export const Nested = make({
{
id: "2",
entityId: "automation.2",
readonly: false,
description: "another one",
title: "Automation #2",
state: "off",
@@ -117,6 +121,7 @@ export const Nested = make({
{
id: "3",
entityId: "automation.3",
readonly: false,
description: "bad one",
title: "Automation #3",
state: "offing",
@@ -153,6 +158,7 @@ export const Nested = make({
},
data: [
{
readonly: false,
id: "4",
entityId: "automation.4",
description: "Cool thing",
@@ -1,5 +1,5 @@
import { HassEntities } from "home-assistant-js-websocket";
import { LangStore, useLang } from "lang";
import { LangStore, useLang } from "services/lang";
import { useEffect, useState } from "react";
import { AutomationData, BareAutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults";
@@ -52,6 +52,7 @@ export const useAutomationDB = (
const auto = defaultAutomation(String(Date.now()));
setNewAuto([
{
readonly: false,
id: auto.id,
entityId: "",
title: auto.alias ?? "",
@@ -77,13 +78,18 @@ const genMapping = (
tagsDB: TagDB,
langStore: LangStore
) => {
const configData: Record<string, AutomationData> = configAutomations.reduce(
(all, n) => ({
...all,
[n.id]: n,
}),
{}
);
const configDataNoId: AutomationData[] = [];
const configData: Record<string, AutomationData & { id: string }> =
configAutomations.reduce((all, n) => {
if (n.id) {
return {
...all,
[n.id]: n,
};
}
configDataNoId.push(n);
return all;
}, {});
const automatioinMap: Record<
string,
[AutomationManagerAuto, AutomationData | null]
@@ -91,7 +97,7 @@ const genMapping = (
Object.entries(haEntities)
.filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation."))
.forEach(([entityId, entityData], i) => {
const autoId = entityData.attributes.id ?? `${entityData.state}-${i}`;
const autoId = entityData.attributes.id ?? entityId.split(".")[1];
let title = entityData.attributes.friendly_name ?? "";
let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state)
@@ -127,12 +133,13 @@ const genMapping = (
source_file_type,
configuration_key,
issue,
readonly: found == null,
},
found,
];
});
Object.values(configData).forEach((auto) => {
Object.values(configData).forEach((auto, i) => {
automatioinMap[auto.id] = [
{
id: auto.id,
@@ -145,10 +152,55 @@ const genMapping = (
source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key,
issue: langStore.get("ISSUES_NO_LOAD_AUTOMATION"),
readonly: false,
},
auto,
];
});
let failedGeneration: number = 0;
configDataNoId.forEach((auto) => {
let generatedAutoId = `automation_${failedGeneration + 1}`;
if (auto.alias) {
generatedAutoId = auto.alias
.toLowerCase()
.replaceAll(/\W/g, " ")
.trim()
.replaceAll(" ", "_");
} else {
failedGeneration += 1;
}
if (automatioinMap[generatedAutoId]) {
automatioinMap[generatedAutoId] = [
{
...automatioinMap[generatedAutoId][0],
issue: langStore.get("ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT", {
sourceFile: auto.source_file,
}),
readonly: true,
},
auto,
];
} else {
automatioinMap[generatedAutoId] = [
{
id: generatedAutoId,
entityId: "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: langStore.get("AUTOMATION_STATE_UNREGISTERED"),
tags: {},
source_file: auto.source_file,
source_file_type: auto.source_file_type,
configuration_key: auto.configuration_key,
issue: langStore.get("ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT", {
sourceFile: auto.source_file,
}),
readonly: true,
},
auto,
];
}
});
return automatioinMap;
};
@@ -10,7 +10,7 @@ import {
} from "./state";
import Alert from "@mui/material/Alert";
import { useConfirm } from "material-ui-confirm";
import { useLang } from "lang";
import { useLang } from "services/lang";
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
onAutomationDelete: (aid: string, eid: string) => void;
@@ -50,6 +50,8 @@ export const AutomationManagerLoaded: FC<
{state.currentAutomationId !== null ? (
state.currentAutomation ? (
<AutomationEditor
readonly={state.currentAutomationIsReadOnly}
issue={state.currentAutomationIssue}
dims={{
...DEFAULT_DIMS,
flipped: true,
@@ -7,7 +7,7 @@ import { useAutomationDB } from "./automationDB";
import { useConfirm } from "material-ui-confirm";
import { AutomationManagerAutoUpdatable } from "../types";
import { useSnackbar } from "notistack";
import { useLang } from "lang";
import { useLang } from "services/lang";
export type UseAutomationManagerStateArgs = {
configAutomations: AutomationData[];
@@ -37,7 +37,11 @@ export const useAutomationManagerState = ({
.map(({ id, tags = {} }) => ({
id,
tags,
})),
}))
.filter(({ id }) => typeof id === "string") as Array<{
id: string;
tags: Record<string, string>;
}>,
onUpdateTags
);
const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB);
@@ -78,6 +82,14 @@ export const useAutomationManagerState = ({
get currentAutomationEntityId(): string | null {
return currentAutomation === null ? null : currentAutomation[0].entityId;
},
get currentAutomationIsReadOnly(): boolean {
return currentAutomation === null ? true : currentAutomation[0].readonly;
},
get currentAutomationIssue(): string | undefined {
return currentAutomation === null
? undefined
: currentAutomation[0].issue;
},
async setSelectedAutomationId(i: string | null, force: boolean = false) {
if (methods.currentAutomationIsNew && !force) {
if (!(await stillHaveNewAreYouSure())) {
@@ -94,7 +106,9 @@ export const useAutomationManagerState = ({
}
}
const auto = automationDB.addNew();
methods.setSelectedAutomationId(auto.id, true);
if (auto.id) {
methods.setSelectedAutomationId(auto.id, true);
}
},
editorUpdateAutomation(auto: AutomationData | BareAutomationData) {
if (methods.currentAutomationIsNew) {
@@ -12,7 +12,7 @@ import { Button } from "components/Inputs/Buttons/Button";
import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "../TagDB";
import { useLang } from "lang";
import { useLang } from "services/lang";
export type TagsProps = {
automationId: string;
@@ -18,7 +18,7 @@ import { ButtonIcon } from "components/Icons/ButtonIcons";
import { AutomationManagerAuto } from "../types";
import { Tags } from "./Tags";
import { TagDB } from "../TagDB";
import { useLang } from "lang";
import { useLang } from "services/lang";
export type MetadataBoxProps = AutomationManagerAuto & {
onDelete: () => void;
@@ -6,6 +6,11 @@
position: relative;
height: 100%;
min-width: calc(min(max(25vw, 35em), 50vw));
transition: min-width ease-in-out 500ms,
min-height ease-in-out 500ms,
height ease-in-out 500ms,
width ease-in-out 500ms,
opacity ease-in-out 500ms;
}
.automation-manager--sidebar-box--nav {
@@ -35,10 +40,14 @@
}
.automation-manager--sidebar.hidden {
width: 2.5em;
width: 3em;
min-width: 0;
}
.automation-manager--sidebar.hidden .add-btn {
display: none;
}
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--nav,
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--list,
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--bottom-buttons .add-btn {
@@ -71,6 +71,7 @@ const story = makeStory({
source_file: "automation.yaml",
source_file_type: "list",
configuration_key: ["automation"],
readonly: false,
},
]);
setSelAutoId(id);
@@ -100,6 +101,7 @@ const makeAuto = (
source_file: "automation.yaml",
source_file_type: "list",
configuration_key: ["automation"],
readonly: false,
...data,
};
};
@@ -18,7 +18,7 @@ import {
} from "../types";
import { Button } from "components/Inputs/Buttons/Button";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
import { useLang } from "services/lang";
export type AutomationManagerSidebarProps = {
tagsDB: TagDB;
@@ -38,10 +38,11 @@ const automations: AutomationManagerAuto[] = [
description: a.description ?? "",
state: "on",
tags: a.tags,
id: a.id,
id: a.id as string,
isSelected: false,
source_file: "automation.yaml",
source_file_type: "list",
readonly: false,
configuration_key: ["automation"],
}));
@@ -51,7 +52,8 @@ const bigList = bigMockAutoList.map<AutomationManagerAuto>((a) => ({
description: a.description ?? "",
state: "on",
tags: a.tags,
id: a.id,
id: a.id as string,
readonly: false,
isSelected: false,
source_file: "automation.yaml",
source_file_type: "list",
@@ -1,10 +1,10 @@
import { makeStory } from "devUtils";
import { useMockApiService } from "apiService";
import { useMockApiService } from "services/api";
import { AutomationManager } from ".";
import {
MockHAEntitiesProps,
useMockHAEntities,
} from "haService/HAEntities.mock";
} from "services/ha/HAEntities.mock";
import { AutomationData } from "types/automations";
import { createMockAuto } from "utils/mocks";
import { useState } from "react";
@@ -109,7 +109,7 @@ export const MissingAutoInConfig = make({
entity_id: `automation.${auto1.id}`,
attributes: {
id: auto1.id,
friendly_name: auto1.alias,
friendly_name: auto1.alias ?? auto1.id ?? "",
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
@@ -4,8 +4,8 @@ import { FC, useEffect, useRef, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress";
import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "apiService/core";
import { HAEntitiesState } from "haService/HAEntities";
import { ApiService } from "services/api/core";
import { HAEntitiesState } from "services/ha/HAEntities";
import { AutomationManagerLoaded } from "./Loaded";
import { Alert } from "@mui/material";
import { useSnackbar } from "notistack";
@@ -14,8 +14,8 @@ import { getFailures } from "types/validators/helper";
import * as av from "types/validators/autmation";
import { useConfirm } from "material-ui-confirm";
import InputYaml from "components/Inputs/Base/InputYaml";
import { APIResponse } from "apiService/types";
import { useLang } from "lang";
import { APIResponse } from "services/api/types";
import { useLang } from "services/lang";
export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => Promise<any>;
@@ -12,6 +12,7 @@ export type AutomationManagerAuto = AutomationManagerAutoUpdatable & {
source_file: string;
source_file_type: string;
configuration_key: string[];
readonly: boolean;
};
export type AutomationManagerAutoItem = AutomationManagerAuto & {
flags: AutomationManagerItemFlags;
@@ -1,11 +1,12 @@
import Alert from "@mui/material/Alert";
import Skeleton from "@mui/material/Skeleton";
import { ApiService } from "apiService/core";
import { UserProfile } from "apiService/types";
import { ApiService } from "services/api/core";
import { UserProfile } from "services/api/types";
import { InputList } from "components/Inputs/InputList";
import { useLang } from "lang";
import { useLang } from "services/lang";
import { FC, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress";
import InputBoolean from "components/Inputs/Base/InputBoolean";
export type UserProfileProps = {
api: ApiService;
@@ -43,6 +44,26 @@ export const UserProfileEditor: FC<UserProfileProps> = ({ api }) => {
});
}
};
const updateFlag =
<K extends keyof UserProfile["flags"], D extends UserProfile["flags"][K]>(
key: K
) =>
(data: D) => {
if (profile.ready) {
setIsSaving(true);
api
.setProfile({
...profile.data,
flags: {
...profile.data.flags,
[key]: data,
},
})
.then(() => {
setIsSaving(false);
});
}
};
return (
<div className="user-profile">
<InputList
@@ -53,10 +74,20 @@ export const UserProfileEditor: FC<UserProfileProps> = ({ api }) => {
/>
<InputList
label={lang.get("LANGUAGE")}
options={["eng", "fra"]}
options={["eng", "fra", "ita"]}
current={profile.data.lang}
onChange={update("lang")}
/>
<InputBoolean
label={lang.get("FLIPP_GRAPH")}
value={profile.data.flags.flipped ?? false}
onChange={updateFlag("flipped")}
/>
<InputBoolean
label={lang.get("NODES_ROW")}
value={profile.data.flags.useNodesRow ?? true}
onChange={updateFlag("useNodesRow")}
/>
{saving && <LinearProgress />}
</div>
);
+5 -4
View File
@@ -1,17 +1,18 @@
import "./index.css";
import { FC, useState } from "react";
import { useHAConnection } from "haService/connection";
import { useHAConnection } from "services/ha/connection";
import { Button } from "components/Inputs/Buttons/Button";
import SettingsSuggestOutlinedIcon from "@mui/icons-material/SettingsSuggestOutlined";
import { useLang } from "lang";
import { useLang } from "services/lang";
import { Modal } from "components/Modal";
import { UserProfileEditor, UserProfileProps } from "./UserProfile";
import { useVersioner } from "services/versioner";
export type BottomBarProps = UserProfileProps;
export const BottomBar: FC<BottomBarProps> = ({ api }) => {
const lang = useLang();
const ha = useHAConnection();
const version = process.env.REACT_APP_BUILD_VERSION ?? "n/a";
const versionMgr = useVersioner();
const [isOpen, setOpen] = useState(false);
return (
@@ -31,7 +32,7 @@ export const BottomBar: FC<BottomBarProps> = ({ api }) => {
🟢
</b>
</span>
<span>version: {version}</span>
<span>version: {versionMgr.current}</span>
<Button className="settings" onClick={() => setOpen(!isOpen)}>
<SettingsSuggestOutlinedIcon />
{lang.get("USER_PRERENCES")}
@@ -6,13 +6,13 @@ import { FC, useState } from "react";
import { AutomationCondition } from "types/automations/conditions";
import { getSubTypeList } from "utils/automations";
import { getConditionDefaultValues } from "utils/defaults";
import { useHA } from "haService";
import { useHA } from "services/ha";
import InputYaml from "components/Inputs/Base/InputYaml";
import { getViewer } from "./viewRender";
import { getEditor } from "./editorRender";
import useWindowSize from "utils/useWindowSize";
import { ConditionNodeSettings } from "./ConditionNodeSettings";
import { useLang } from "lang";
import { useLang } from "services/lang";
export type ConditionNodeBaseProps = {
condition: AutomationCondition;
@@ -20,7 +20,7 @@ import {
import { genUpdateMethods } from "./nestedUpdater";
import { InputTime } from "components/Inputs/Base/InputTime";
import InputYaml from "components/Inputs/Base/InputYaml";
import { HAService } from "haService";
import { HAService } from "services/ha";
import { DeviceEditor } from "components/DeviceEditor";
import { ButtonIcon } from "components/Icons/ButtonIcons";
import AddIcon from "@mui/icons-material/Add";
@@ -31,7 +31,7 @@ import { prettyName } from "utils/formatting";
import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Buttons/Button";
import { RemoveCircle } from "@mui/icons-material";
import { LangStore } from "lang";
import { LangStore } from "services/lang";
interface Editor<C extends AutomationCondition>
extends FC<{
@@ -271,7 +271,7 @@ export const StateEditor: Editor<StateCondition> = ({
}
/>
<InputTime
label="For"
label={langStore.get("FOR")}
value={condition.for}
onChange={(_for) =>
onChange({
@@ -0,0 +1,92 @@
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { makeStory } from "devUtils";
import { NodesRow } from ".";
import { createUpdater } from "../updater/index";
const { make, componentMeta } = makeStory({
Component: NodesRow,
BaseTemplate: (props) => {
const updater = createUpdater({
openModal: () => {},
action: {
data: [],
onUpdate: () => {},
},
condition: {
data: [],
onUpdate: () => {},
},
trigger: {
data: [],
onUpdate: () => {},
},
});
return <NodesRow {...props} stateUpdater={updater} />;
},
meta: {
title: "DAGGraph/NodesRow/Single",
args: {
type: "trigger",
data: [],
sequenceNodeDims: DEFAULT_DIMS.node,
},
},
});
export default componentMeta;
export const Empty = make({});
export const One = make({
data: [
{
platform: "calendar",
event: "start",
},
],
});
export const Many = make({
data: [
{
platform: "calendar",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
].map((n, id) => ({
...n,
id: `Trigger ${id}`,
})),
});
@@ -0,0 +1,95 @@
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { makeStory } from "devUtils";
import { createUpdater } from "../updater";
import { TriggerConditionNodeRow } from ".";
const { make, componentMeta } = makeStory({
Component: TriggerConditionNodeRow,
BaseTemplate: (props) => {
const updater = createUpdater({
openModal: () => {},
action: {
data: [],
onUpdate: () => {},
},
condition: {
data: [],
onUpdate: () => {},
},
trigger: {
data: [],
onUpdate: () => {},
},
});
return <TriggerConditionNodeRow {...props} stateUpdater={updater} />;
},
meta: {
title: "DAGGraph/NodesRow/TriggerAndConditions",
args: {
condition: [],
trigger: [],
sequenceNodeDims: DEFAULT_DIMS.node,
},
},
});
export default componentMeta;
export const Empty = make({});
export const One = make({
trigger: [
{
platform: "calendar",
event: "start",
},
],
condition: [
{
condition: "and",
conditions: [],
},
],
});
export const Many = make({
trigger: [
{
platform: "calendar",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
{
platform: "homeassistant",
event: "start",
},
],
});
@@ -0,0 +1,87 @@
/* .nodes-row--outer {
--nodes-row-height: 10em;
min-width: 100%;
width: 100%;
max-width: 100%;
min-height: var(--nodes-row-height);
height: var(--nodes-row-height);
max-height: var(--nodes-row-height);
overflow: auto;
}
.nodes-row--inner {
max-width: calc(100% - 4em);
width: calc(100% - 4em);
min-height: calc(var(--nodes-row-height) - 2em);
max-height: calc(var(--nodes-row-height) - 2em);
gap: 2em;
padding-left: 1em;
padding-right: 1em;
border-style: solid;
border-top-width: 0.125em;
border-left-width: 1px;
border-right-width: 1px;
border-radius: 10px;
border-bottom-color: var(--mui-grey-500);
border-left-color: var(--mui-grey-700);
border-right-color: var(--mui-grey-700);
border-top-color: var(--sequence-node-color);
overflow: auto;
} */
.nodes-row--inner.collection-nodes--wrap {
--node-height: none !important;
--node-width: 100% !important;
margin: 0;
display: flex;
flex: 1;
min-width: 95%;
max-width: 95%;
}
.nodes-row--inner.collection-nodes--wrap .collection-nodes {
min-width: 90%;
min-height: 8em;
max-height: 8em;
overflow: hidden;
}
.trigger-condition-nodes-row {
gap: 0.25em;
}
.fullscreen .trigger-condition-nodes-row .nodes-row--inner {
opacity: 0;
height: 0;
z-index: -10;
}
.nodes-row--inner.collection-nodes--wrap .collection-nodes .collection-nodes--inner {
min-width: inherit;
width: inherit;
max-width: inherit;
padding-bottom: 0 !important;
padding-left: 0 !important;
min-height: 5em;
max-height: 7em;
}
.mobile .trigger-condition-nodes-row {
flex-direction: column;
}
.mobile .nodes-row.collection-nodes--wrap .collection-nodes {
width: 80%;
}
@@ -0,0 +1,85 @@
import "./index.css";
import { AutomationNode, AutomationNodeMapping } from "types/automations";
import { useHA } from "services/ha";
import { CollectionNodeElement } from "components/DAGGraph/nodes/CollectionNode/CollectionNodeElement";
import { Size } from "components/DAGGraph/elements/types";
import { DAGGraphUpdater } from "components/DAGGraph/updater";
import { makeCollectionNodeMakerChildProps } from "components/DAGGraph/elements/helpers";
import { AutomationCondition } from "types/automations/conditions";
import { AutomationTrigger } from "types/automations/triggers";
import { FC } from "react";
export type NodesRowProps<
K extends keyof AutomationNodeMapping,
T extends AutomationNode<K>
> = {
type: K;
data: T[];
stateUpdater: DAGGraphUpdater;
sequenceNodeDims: Size;
};
export function NodesRow<
K extends keyof AutomationNodeMapping,
T extends AutomationNode<K>
>({
type: collectionType,
data,
sequenceNodeDims,
stateUpdater,
}: NodesRowProps<K, T>) {
const { namer } = useHA();
return (
<div className="nodes-row--outer center row">
<CollectionNodeElement
className="nodes-row--inner"
width={0}
height={0}
nodes={data.map((node, i) =>
makeCollectionNodeMakerChildProps(
collectionType,
node,
i,
stateUpdater,
namer
)
)}
onAddNode={() => stateUpdater.basic[collectionType].addNode(null)}
collectionType={collectionType}
sequenceNode={sequenceNodeDims}
flipped
/>
</div>
);
}
export type TriggerConditionNodeRowProps = {
condition: AutomationCondition[];
trigger: AutomationTrigger[];
stateUpdater: DAGGraphUpdater;
sequenceNodeDims: Size;
};
export const TriggerConditionNodeRow: FC<TriggerConditionNodeRowProps> = ({
condition,
trigger,
stateUpdater,
sequenceNodeDims,
}) => {
return (
<div className={["trigger-condition-nodes-row column"].join(" ")}>
<NodesRow
data={trigger}
type="trigger"
stateUpdater={stateUpdater}
sequenceNodeDims={sequenceNodeDims}
/>
<NodesRow
data={condition}
type="condition"
stateUpdater={stateUpdater}
sequenceNodeDims={sequenceNodeDims}
/>
</div>
);
};
@@ -11,7 +11,6 @@ const { make, componentMeta } = makeStory({
});
export default componentMeta;
export const Example = make({});
export const Loading = make({
state: {
+9 -11
View File
@@ -2,7 +2,7 @@ import "./index.css";
import { FC } from "react";
import CircularProgress from "@mui/material/CircularProgress";
import ReactFlow, { Controls, ReactFlowProvider } from "react-flow-renderer";
import ReactFlow, { Controls } from "react-flow-renderer";
import { NodeEditor } from "components/NodeEditor";
import { Modal } from "components/Modal";
@@ -10,15 +10,7 @@ import { Modal } from "components/Modal";
import { nodeTypes } from "../nodes";
import { DAGGraphBoardProps } from "./types";
export const DAGGraphBoard: FC<DAGGraphBoardProps> = (props) => {
return (
<ReactFlowProvider>
<DAGGraphBoardInner {...props} />
</ReactFlowProvider>
);
};
export const DAGGraphBoardInner: FC<DAGGraphBoardProps> = ({
export const DAGGraphBoard: FC<DAGGraphBoardProps> = ({
modalState,
state,
closeModal,
@@ -37,6 +29,12 @@ export const DAGGraphBoardInner: FC<DAGGraphBoardProps> = ({
return <div className="dag-graphboard errored">{state.data.error}</div>;
}
// useEffect(() => {
// if (state.ready) {
// reactFlow.fitView();
// }
// }, [state.ready, reactFlow]);
// modal
let modalBody = <></>;
if (modalState) {
@@ -70,7 +68,7 @@ export const DAGGraphBoardInner: FC<DAGGraphBoardProps> = ({
nodesDraggable={false}
{...elements}
>
<Controls showInteractive={false} showFitView>
<Controls showInteractive={false} showFitView={false}>
{additionalControls}
</Controls>
</ReactFlow>
@@ -2,7 +2,7 @@ import { XYPosition } from "react-flow-renderer";
import AddBox from "@mui/icons-material/AddBox";
import { getDescriptionFromAutomationNode } from "utils/formatting";
import { getDescriptionFromAutomationNode, Namer } from "utils/formatting";
import { validateNode } from "utils/automations";
import { AutomationCondition } from "types/automations/conditions";
import { AutomationTrigger } from "types/automations/triggers";
@@ -13,6 +13,35 @@ import { convertFailuresToSequenceNodeDataProps } from "./util";
import { ButtonNodeMaker } from "../nodes/ButtonNode";
import { CollectionNodeMaker } from "../nodes/CollectionNode";
import { DAGGraphUpdater } from "../updater/index";
import { AutomationActionData } from "types/automations";
export function makeCollectionNodeMakerChildProps<
NodeType extends keyof AutomationActionData,
Node extends AutomationActionData[NodeType][0]
>(
nodeType: NodeType,
node: Node,
index: number,
stateUpdater: DAGGraphUpdater,
namer: Namer
) {
const failures = validateNode(node, [nodeType]);
if (failures) {
return {
enabled: node.enabled ?? true,
...stateUpdater.createNodeActions(nodeType, index, {}),
...convertFailuresToSequenceNodeDataProps(failures),
};
}
return {
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions(nodeType, index, {}),
};
}
export const makeTriggerNodes: ElementMaker<AutomationTrigger> = (
nodes,
@@ -24,23 +53,15 @@ export const makeTriggerNodes: ElementMaker<AutomationTrigger> = (
...dims.collection,
collectionType: "trigger",
onAddNode: () => stateUpdater.basic.trigger.addNode(null),
nodes: nodes.map((node, index) => {
const failures = validateNode(node, ["trigger"]);
if (failures) {
return {
enabled: node.enabled ?? true,
...stateUpdater.createNodeActions("trigger", index, {}),
...convertFailuresToSequenceNodeDataProps(failures),
};
}
return {
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("trigger", index, {}),
};
}),
nodes: nodes.map((node, index) =>
makeCollectionNodeMakerChildProps(
"trigger",
node,
index,
stateUpdater,
namer
)
),
})
);
return outputState;
@@ -57,23 +78,15 @@ export const makeConditionNodes: ElementMaker<AutomationCondition> = (
collectionType: "condition",
hasInput: !!lastNodeId,
onAddNode: () => stateUpdater.basic.condition.addNode(null),
nodes: nodes.map((node, index) => {
const failures = validateNode(node, ["condition"]);
if (failures) {
return {
enabled: node.enabled ?? true,
...stateUpdater.createNodeActions("condition", index, {}),
...convertFailuresToSequenceNodeDataProps(failures),
};
}
return {
enabled: node.enabled ?? true,
label: getDescriptionFromAutomationNode(node, namer, true),
...stateUpdater.createNodeActions("condition", index, {}),
};
}),
nodes: nodes.map((node, index) =>
makeCollectionNodeMakerChildProps(
"condition",
node,
index,
stateUpdater,
namer
)
),
})
);
if (lastNodeId && outputState.lastNodeId) {
@@ -3,7 +3,7 @@ import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { DAGGraphBoard } from "components/DAGGraph/board";
import { useAutomationNodes } from "./index";
import { useHA } from "haService";
import { useHA } from "services/ha";
import { AutomationActionData } from "types/automations";
import { createUpdaterFromAutomationData } from "../updater";
import { ModalState } from "../board/types";
@@ -24,15 +24,19 @@ const { make, componentMeta } = makeStory({
state,
setState
);
const elementData = useAutomationNodes(state, {
dims: {
...DEFAULT_DIMS,
flipped: props.flipped,
const elementData = useAutomationNodes(
state,
{
dims: {
...DEFAULT_DIMS,
flipped: props.flipped,
},
namer,
openModal: setModalState,
stateUpdater: updater,
},
namer,
openModal: setModalState,
stateUpdater: updater,
});
false
);
return (
<DAGGraphBoard
modalState={modalState}
@@ -28,52 +28,57 @@ import * as helpers from "./helpers";
export const useAutomationNodes = (
automation: AutomationActionData,
args: ElementMakerBaseProps
args: ElementMakerBaseProps,
hideConditionAndTriggers: boolean
) => {
const dims: DAGDims = {
...args.dims,
};
const state = useDAGElementsState();
const outputState = new DAGElementsOutputState(dims.position, dims);
outputState.extend(
helpers.makeTriggerNodes(automation.trigger, {
...args,
state,
let actionStartPos = dims.position;
if (!hideConditionAndTriggers) {
outputState.extend(
helpers.makeTriggerNodes(automation.trigger, {
...args,
state,
dims,
position: dims.position,
nodeId: `${dims.flipped}-trigger`,
nodeIndex: 0,
})
);
outputState.extend(
helpers.makeConditionNodes(automation.condition, {
...args,
state,
dims,
position: distance.moveFromTo(
"collection",
"collection",
outputState.getLastNodePos(),
dims
),
nodeId: `${dims.flipped}-condition`,
nodeIndex: 1,
lastNodeId: outputState.lastNodeId,
})
);
actionStartPos = distance.moveFromTo(
"collection",
"node",
outputState.getLastNodePos(),
dims,
position: dims.position,
nodeId: `${dims.flipped}-trigger`,
nodeIndex: 0,
})
);
outputState.extend(
helpers.makeConditionNodes(automation.condition, {
...args,
state,
dims,
position: distance.moveFromTo(
"collection",
"collection",
outputState.getLastNodePos(),
dims
),
nodeId: `${dims.flipped}-condition`,
nodeIndex: 1,
lastNodeId: outputState.lastNodeId,
})
);
true
);
}
outputState.extend(
makeSequenceNodes(automation.action, {
...args,
state,
dims,
position: distance.moveFromTo(
"collection",
"node",
outputState.getLastNodePos(),
dims,
true
),
position: actionStartPos,
nodeId: `${dims.flipped}-action`,
nodeIndex: 2,
lastNodeId: outputState.lastNodeId,
+31 -17
View File
@@ -1,6 +1,6 @@
import { FC, useState, ReactNode } from "react";
import { AutomationSequenceNode } from "types/automations";
import { useHA } from "haService";
import { useHA } from "services/ha";
import { ModalState } from "./board/types";
import { createUpdater } from "./updater";
import { useAutomationNodes } from "./elements";
@@ -8,6 +8,7 @@ import { DEFAULT_DIMS } from "./elements/constants";
import { DAGGraphBoard } from "./board";
import { AutomationTrigger } from "types/automations/triggers";
import { AutomationCondition } from "types/automations/conditions";
import { TriggerConditionNodeRow } from "./NodesRow";
export const DAGAutomationGraph: FC<{
action: AutomationSequenceNode[];
@@ -17,6 +18,7 @@ export const DAGAutomationGraph: FC<{
onTriggerUpdate: (t: AutomationTrigger[]) => void;
onConditionUpdate: (c: AutomationCondition[]) => void;
isFlipped: boolean;
useNodesRow: boolean;
additionalControls?: ReactNode;
}> = (props) => {
const { namer } = useHA();
@@ -37,6 +39,10 @@ export const DAGAutomationGraph: FC<{
onUpdate: props.onTriggerUpdate as any,
},
});
const dims = {
...DEFAULT_DIMS,
flipped: props.isFlipped,
};
const elementData = useAutomationNodes(
{
action: props.action,
@@ -44,26 +50,34 @@ export const DAGAutomationGraph: FC<{
trigger: props.trigger,
},
{
dims: {
...DEFAULT_DIMS,
flipped: props.isFlipped,
},
dims,
namer,
openModal: setModalState,
stateUpdater: updater,
}
},
props.useNodesRow
);
return (
<DAGGraphBoard
modalState={modalState}
closeModal={() => setModalState(undefined)}
state={{
ready: true,
data: {
elements: elementData,
},
}}
additionalControls={props.additionalControls}
/>
<>
{props.useNodesRow && (
<TriggerConditionNodeRow
trigger={props.trigger}
condition={props.condition}
stateUpdater={updater}
sequenceNodeDims={dims.node}
/>
)}
<DAGGraphBoard
modalState={modalState}
closeModal={() => setModalState(undefined)}
state={{
ready: true,
data: {
elements: elementData,
},
}}
additionalControls={props.additionalControls}
/>
</>
);
};
@@ -13,89 +13,91 @@ import { prettyName } from "utils/formatting";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import { useConfirm } from "material-ui-confirm";
import { useSnackbar } from "notistack";
import { useLang } from "lang";
import { useLang } from "services/lang";
export const CollectionNodeElement: FC<PropsWithChildren<CollectionNodeProps>> =
({
onAddNode,
nodes,
sequenceNode,
height,
width,
flipped,
collectionType,
onDelete,
title,
children,
}) => {
const lang = useLang();
const color = convertNodeTypeToSequenceNodeColor(collectionType);
const nodeColor = useSequenceNodeColor(color);
const confirm = useConfirm();
const snackbr = useSnackbar();
const trueTile = title ?? collectionType;
export const CollectionNodeElement: FC<
PropsWithChildren<CollectionNodeProps & { className?: string }>
> = ({
onAddNode,
nodes,
sequenceNode,
height,
width,
flipped,
collectionType,
onDelete,
title,
children,
className,
}) => {
const lang = useLang();
const color = convertNodeTypeToSequenceNodeColor(collectionType);
const nodeColor = useSequenceNodeColor(color);
const confirm = useConfirm();
const snackbr = useSnackbar();
const trueTile = title ?? collectionType;
return (
<div
className="collection-nodes--wrap"
style={
{
"--node-color": nodeColor,
"--node-height": `${height}px`,
"--node-width": `${width}px`,
} as any
}
>
<div className="collection-nodes">
{!!onDelete && (
<ButtonIcon
className="delete-icon"
icon={<DeleteForeverIcon />}
onClick={() => {
confirm({
description: `Are you sure you want to delete ${trueTile}?`,
return (
<div
className={["collection-nodes--wrap", className ?? ""].join(" ")}
style={
{
"--node-color": nodeColor,
"--node-height": `${height}px`,
"--node-width": `${width}px`,
} as any
}
>
<div className="collection-nodes">
{!!onDelete && (
<ButtonIcon
className="delete-icon"
icon={<DeleteForeverIcon />}
onClick={() => {
confirm({
description: `Are you sure you want to delete ${trueTile}?`,
})
.then(() => {
onDelete();
snackbr.enqueueSnackbar(lang.get("DELETED"), {
variant: "info",
});
})
.then(() => {
onDelete();
snackbr.enqueueSnackbar(lang.get("DELETED"), {
.catch(() =>
snackbr.enqueueSnackbar(
lang.get("NOT_DELETED_THING", {
item: trueTile,
}),
{
variant: "info",
});
})
.catch(() =>
snackbr.enqueueSnackbar(
lang.get("NOT_DELETED_THING", {
item: trueTile,
}),
{
variant: "info",
}
)
);
}}
borderless
color="secondary"
}
)
);
}}
borderless
color="secondary"
/>
)}
<span className="collection-nodes--title">
{prettyName(collectionType)}s
</span>
<div className="collection-nodes--inner">
{nodes.map((n, i) => (
<SequenceNodeElement
key={i}
color={color}
flipped={flipped}
{...n}
{...sequenceNode}
/>
)}
<span className="collection-nodes--title">
{prettyName(collectionType)}s
</span>
<div className="collection-nodes--inner">
{nodes.map((n, i) => (
<SequenceNodeElement
key={i}
color={color}
flipped={flipped}
{...n}
{...sequenceNode}
/>
))}
</div>
<ButtonIcon className="add" icon={<Add />} onClick={onAddNode} />
{children}
<span className="collection-nodes--total">
{nodes.length} node{nodes.length !== 1 ? "s" : ""}
</span>
))}
</div>
<ButtonIcon className="add" icon={<Add />} onClick={onAddNode} />
{children}
<span className="collection-nodes--total">
{nodes.length} node{nodes.length !== 1 ? "s" : ""}
</span>
</div>
);
};
</div>
);
};
@@ -11,8 +11,6 @@
width: var(--sequence-node-width);
min-height: var(--sequence-node-height);
min-width: var(--sequence-node-width);
/* outline: 1px dotted white; */
}
.sequence-node.disabled .sequence-node--inner {
@@ -16,7 +16,7 @@ import InputBoolean from "components/Inputs/Base/InputBoolean";
import { SpeedDial } from "components/SpeedDial";
import { SequenceNodeElementProps } from "./types";
import { useSequenceNodeColor } from "./util";
import { useLang } from "lang";
import { useLang } from "services/lang";
export const SequenceNodeElement: FC<
PropsWithChildren<SequenceNodeElementProps>
@@ -86,7 +86,6 @@ export const createDummyUpdater = (): DAGUpdaterInput<any> => ({
data: [],
onUpdate: console.warn,
});
// export const createScriptConditionFieldUpdater = (f: ScriptConditionField, )
export type DAGGraphUpdater = ReturnType<typeof createUpdater>;
export type DAGGraphChooseUpdater = ReturnType<
+2 -2
View File
@@ -6,9 +6,9 @@ import { InputDevice } from "components/Inputs/AutoComplete/InputDevice";
import { InputDeviceCapabilties } from "components/Inputs/AutoComplete/InputDeviceCapabilties";
import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
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 { useLang } from "lang";
import { useLang } from "services/lang";
export type DeviceEditorProps<DBT extends DeviceBaseType> = {
type: "action" | "condition" | "trigger";
+1 -1
View File
@@ -2,7 +2,7 @@ import "./ButtonIcons.css";
import Tooltip from "@mui/material/Tooltip";
import { FC, ReactNode } from "react";
import IconButton, { IconButtonTypeMap } from "@mui/material/IconButton";
import { useLang } from "lang";
import { useLang } from "services/lang";
export type ButtonIconProps = {
icon: ReactNode;
@@ -3,7 +3,8 @@ import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { useHAAreas } from "haService/AreaRegistry";
import { useHAAreas } from "services/ha/AreaRegistry";
import { useLang } from "services/lang";
export type InputAreaProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[];
@@ -11,12 +12,13 @@ export type InputAreaProps = InputAutoCompletePropsBase & {
};
export const InputArea: FC<InputAreaProps> = (props) => {
const lang = useLang();
// state
const areas = useHAAreas();
return (
<InputAutoComplete
{...props}
label={props.label ?? "Area"}
label={props.label ?? lang.get("AREA")}
getID={areas.getID}
getLabel={areas.getLabel}
options={areas.getOptions()}
@@ -7,6 +7,7 @@ import Popper from "@mui/material/Popper";
import { SearchItem } from "./extras";
import { ReactNode } from "react";
import { prettyName } from "utils/formatting";
import { useLang } from "services/lang";
export type BaseOption<T = {}> = {
id: string;
@@ -65,6 +66,7 @@ export function computeSimilarity(
export function InputAutoComplete<T extends Option>(
props: InputAutoCompleteProps<T>
) {
const lang = useLang();
// aliases
const getID = (opt: T): string => {
if (props.getID) {
@@ -186,16 +188,14 @@ export function InputAutoComplete<T extends Option>(
const id = getID(option);
return (
<>
<SearchItem
key={label + id}
listProps={listProps}
id={id}
label={label}
searchTerm={inputValue}
onlyShowLabel={props.onlyShowLabel}
/>
</>
<SearchItem
key={label + id}
listProps={listProps}
id={id}
label={label}
searchTerm={inputValue}
onlyShowLabel={props.onlyShowLabel}
/>
);
}}
renderInput={(params) => (
@@ -212,7 +212,7 @@ export function InputAutoComplete<T extends Option>(
}}
variant="filled"
required={props.required}
label={props.label ?? "Entity ID"}
label={props.label ?? lang.get("ENTITY_ID")}
helperText={helperText}
disabled={props.disabled}
error={error}
@@ -223,12 +223,13 @@ export function InputAutoComplete<T extends Option>(
)}
renderTags={(tagValue, getTagProps) => {
const inner = (
<div className="input-autocomplete--tags">
<div className="input-autocomplete--tags" key={"inner"}>
{tagValue.map((option, index) => {
const label = getLabel(option);
const id = getID(option);
const tagProps = getTagProps({ index });
tagProps.className += " input-autocomplete--chip";
tagProps.key = tagProps.key ?? index;
return (
<Chip
size="medium"
@@ -256,7 +257,11 @@ export function InputAutoComplete<T extends Option>(
}
if (props.multiple) {
return (
<Badge badgeContent={tagValue.length} color="info">
<Badge
badgeContent={tagValue.length}
color="info"
key="badge-wrapper"
>
{inner}
</Badge>
);
@@ -1,5 +1,6 @@
import { FC } from "react";
import { useHADeviceRegistry } from "haService";
import { useHADeviceRegistry } from "services/ha";
import { useLang } from "services/lang";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
@@ -9,11 +10,12 @@ export type InputDeviceProps = InputAutoCompletePropsBase;
export const InputDevice: FC<InputDeviceProps> = (props) => {
// state
const lang = useLang();
const dr = useHADeviceRegistry();
return (
<InputAutoComplete
{...props}
label={props.label ?? "Device"}
label={props.label ?? lang.get("DEVICE")}
getID={dr.getID}
getLabel={dr.getLabel}
options={dr.getOptions()}
@@ -1,5 +1,5 @@
import "./InputDeviceCapabilties.css";
import { HaFormSchema } from "haService/types";
import { HaFormSchema } from "services/ha/types";
import { useSnackbar } from "notistack";
import { useRef } from "react";
import { prettyName } from "utils/formatting";
@@ -1,5 +1,5 @@
import { FC } from "react";
import { useHAEntities } from "haService/HAEntities";
import { useHAEntities } from "services/ha/HAEntities";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
@@ -15,6 +15,7 @@ const { make, componentMeta } = makeStory({
<div
style={{
maxWidth: 200,
margin: "5em",
}}
>
<InputEntity
@@ -1,19 +1,27 @@
import { FC } from "react";
import { useHAServices } from 'haService';
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete';
import { prettyName } from 'utils/formatting';
import { useHAServices } from "services/ha";
import {
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 => {
const services = useHAServices();
return <InputAutoComplete
{...props}
label={props.label ?? "Service"}
options={services.getOptions()}
getID={services.getID}
getLabel={services.getLabel}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''}
export const InputService: FC<InputServiceProps> = (props) => {
const services = useHAServices();
const lang = useLang();
return (
<InputAutoComplete
{...props}
label={props.label ?? lang.get("SERVICE")}
options={services.getOptions()}
getID={services.getID}
getLabel={services.getLabel}
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
/>
}
);
};
@@ -12,6 +12,7 @@ import {
} from "utils/time";
import { InputEntity } from "./InputEntities";
import { InputTime } from "components/Inputs/Base/InputTime";
import { useLang } from "services/lang";
export type InputTimeEntityProps = {
value: string;
@@ -23,6 +24,7 @@ export const InputTimeEntity: FC<InputTimeEntityProps> = ({
onChange,
className = "",
}) => {
const lang = useLang();
const is24Hour = isAutomationTimeString24Hours(value);
let editor: ReactNode;
if (is24Hour) {
@@ -39,7 +41,7 @@ export const InputTimeEntity: FC<InputTimeEntityProps> = ({
} else {
editor = (
<InputEntity
label="Time Entity"
label={lang.get("TIME_ENTITY")}
restrictMode="or"
restrictedDeviceClass={["timestamp"]}
restrictToDomain={["input_datetime"]}
@@ -1,5 +1,4 @@
import React, { ReactNode, useState } from "react";
import { useToolTip } from "tooltip/context";
import { ReactNode, useState } from "react";
import TextField from "@mui/material/TextField";
export interface Props {
@@ -22,19 +21,16 @@ export default function InputText({
label,
title,
helperText,
textBoxFor,
value = "",
onChange,
endAdornment,
onEnter = () => {},
additionalTooltipFilters = {},
multiline = false,
maxRows = 4,
className,
placeholder,
required,
}: Props) {
const tooltip = useToolTip();
const [isFocused, setIsFocused] = useState(false);
return (
<TextField
@@ -68,17 +64,6 @@ export default function InputText({
}}
onFocus={(e) => {
setIsFocused(true);
if (textBoxFor) {
tooltip.setFocus(
e.target.getBoundingClientRect(),
{
searchObject: textBoxFor,
searchText: value,
filterObjects: additionalTooltipFilters,
},
onChange
);
}
}}
/>
);
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff. Show more