Compare commits

..
15 Commits
Author SHA1 Message Date
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
59 changed files with 713 additions and 289 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 --->
```
+17 -137
View File
@@ -1,5 +1,22 @@
# 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.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 +25,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 +40,6 @@
- Better global error capture - Better global error capture
![image](https://user-images.githubusercontent.com/7451445/185441268-9dbde36e-b28b-4a13-bd7f-45ae23834e78.png) ![image](https://user-images.githubusercontent.com/7451445/185441268-9dbde36e-b28b-4a13-bd7f-45ae23834e78.png)
## [0.5.3] - Bug Fixes
- Redirecting `/` to `/web` to resolve container install strangeness reported in https://github.com/asosnovsky/Shortumation/issues/125
- Fixed missing flag that caused the automation to explode in https://github.com/asosnovsky/Shortumation/issues/124
## [0.5.2] - Better Controls ## [0.5.2] - Better Controls
- Add automation trigger - Add automation trigger
@@ -54,11 +60,6 @@
- Websockets now live-refresh when updates occur - Websockets now live-refresh when updates occur
## [0.4.0] - Depedency update
- Core dependency updates
- Python port is now dynamically set
## [0.3.4] - Condition/Trigger Editor Upgrades! ## [0.3.4] - Condition/Trigger Editor Upgrades!
- Many condition editor fixes - Many condition editor fixes
@@ -75,19 +76,6 @@
![image](https://user-images.githubusercontent.com/7451445/180238004-4b04f13a-77a2-4c4c-9144-963dbc394bf4.png) ![image](https://user-images.githubusercontent.com/7451445/180238004-4b04f13a-77a2-4c4c-9144-963dbc394bf4.png)
## [0.3.2] - Fixed Addon Image for arm-based devices
- Using hypercon instead of uvicorn (this losses the rust dependency which makes it easier to install on arm)
- Pre-building web assets outside of docker (this takes the image size down and speeds up instaltion of addon)
- Updated build scripts to actually fail installation when build/prep steps fail
- Ensured that builds for all architecture run successfully
- Re-worked github actions (quicker test phases)
## [0.3.1] - Increased Pagination + Restricted Repeat Node
- Increased pagination to display up to 10,000 autos for now
- Repeat node now has types
## [0.3.0] - Complete Refactor of Graphs ## [0.3.0] - Complete Refactor of Graphs
- Added visual support for - Added visual support for
@@ -106,113 +94,5 @@
![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png) ![image](https://user-images.githubusercontent.com/7451445/179135916-8083aab5-bee1-4d27-b19d-9e000ca012f9.png)
## [0.1.22] - Many Visual improvements
- Deprecated several custom components in favor of mui.com
- Device Editor now has support for 99% of diplay types
- Condition Device is implemented
- Improved naming autogen for trigger & choose
## [0.1.21] - Service Editor
- first version of service editor
- reloading automations on save
## [0.1.20] - UI Bugfixes
- Using MUI elements for input time
- Added delay action / wait_on_triggers action
- Added enabled/disabled flag in node editor
- Optional flip vertical during desktop mode
- Fixed up modal clipping
## [0.1.19] - Vertical mobile mode
- in mobile mode we draw the graphs vertically now
## [0.1.17] - Websockets
- Connected to HA main websocket -- now we retrieve real-time information about
- Device names
- Entity names/ids
- Autocomplete for devices and entities
## [0.1.14] - Material UI + Autocomplete
- Brought some Material UI elements for input and text
- Autocomplete for tags
- Using 'id' as alias for trigger (as it seems to break HA otherwise)
- Not using 'alias' for conditions, always auto-generating it (again, this used to break HA)
- Added missing `data` object to service-actions
## [0.1.13] - YAML
- Better YAML
- Rewrote yaml parser/loader to use pyyaml and safe mode
- Cleaned up description vs alias
## [0.1.12] - Less Intense Error Messages
- Added more node-based errors (this way it's easier to see where validations failed)
- Made the validators less strict in order to capture more edge cases that HA supports
- Nicer auto-generated descriptions for some trigger nodes
## [0.1.10] - More Bug Fixes
- Allowing null or undefined values for metadata fields
- Trigger.platform==time will now have the .at property better supported
## [0.1.9] - Fixed up invalid types for various triggers
- Some triggers had invalid types and were causing a false-positive validation
## [0.1.8] - Support for Malformed Automations
- API will no longer error out on missing values or invalid lists
- Frontend has support for displaying bad automations
## [0.1.6] - Mobile Mode
- Improved mobile mode
- Fixed up arrow styles due to typos
- Added selection color
## [0.1.2] - Docker Hub Images
- Publishing images to docker hub is now stable
## [0.0.15] - Publish to dockerhub
- Publishing images to docker hub
## [0.0.14] - Using vanila ha yaml
- Supporing vanilla out of the box HA yaml as oppose to parsing them (no more $smType)
- Conditions have now a more a explicit node
## [0.0.13] - Better Styling with react-flow
- Fixed up styling (using react-flow)
- cleaned up some button styles
## [0.0.12] - Tags
- Added tag management system for automations
## [0.0.11] - Zoom
- Added lazy saving
## [0.0.10] - Zoom
- Introducing Zoom!
## [0.0.9] - First Working Version
- Instalable verion via github
- Initial POC done
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+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
+14 -6
View File
@@ -236,9 +236,11 @@ def load_automation_inline_ref(
) -> Iterator[ExtenededAutomation]: ) -> Iterator[ExtenededAutomation]:
for auto in inline_automation.automations: for auto in inline_automation.automations:
try: try:
cleaned_automation = clean_automation(auto)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(auto), **cleaned_automation,
tags=tag_manager.get(auto["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=inline_automation.configuration_key, configuration_key=inline_automation.configuration_key,
source_file=str(inline_automation.source_file.resolve().relative_to(root_path)), source_file=str(inline_automation.source_file.resolve().relative_to(root_path)),
source_file_type="inline", source_file_type="inline",
@@ -286,9 +288,11 @@ def load_automation_path(
if isinstance(automations, dict): if isinstance(automations, dict):
try: try:
cleaned_automation = clean_automation(automations)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(automations), **cleaned_automation,
tags=tag_manager.get(automations["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key, configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)), source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="obj", source_file_type="obj",
@@ -305,9 +309,11 @@ def load_automation_path(
return return
for automation in automations: for automation in automations:
try: try:
cleaned_automation = clean_automation(automation)
automation_id = cleaned_automation.get("id", None)
yield ExtenededAutomation( yield ExtenededAutomation(
**clean_automation(automation), **cleaned_automation,
tags=tag_manager.get(automation["id"], {}), tags={} if automation_id is None else tag_manager.get(automation_id, {}),
configuration_key=configuration_key, configuration_key=configuration_key,
source_file=str(automation_path.resolve().relative_to(root_path)), source_file=str(automation_path.resolve().relative_to(root_path)),
source_file_type="list", source_file_type="list",
@@ -324,6 +330,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] = []
@@ -1 +1,38 @@
automation: !include ../automations/ui.yaml automation: !include ../automations/ui.yaml
media_player:
- platform: template
media_players:
receiver:
friendly_name: Receiver
current_source_template: "{{ states('input_text.selected_source') }}"
value_template: >
{% if is_state("input_boolean.receiver_on", "on") -%}
on
{%- else -%}
off
{%- endif %}
turn_on:
service: switch.turn_on
data_template:
entity_id: switch.receiver_on
turn_off:
service: switch.turn_on
data_template:
entity_id: switch.receiver_off
volume_up:
service: switch.turn_on
data_template:
entity_id: switch.volume_up
volume_down:
service: switch.turn_on
data_template:
entity_id: switch.vol
input_templates:
source 1:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_1
source 2:
service: input_boolean.turn_on
data_template:
entity_id: input_boolean.source_2
@@ -0,0 +1,21 @@
- alias: UI 1
description: Example
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
- alias: UI 2
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition: []
action: []
mode: single
@@ -0,0 +1,30 @@
# Loads default set of integrations. Do not remove.
default_config:
# Text to speech
tts:
- platform: google_translate
# automation manual: !include_dir_list ./automations/include_dir_list
# automation ui: !include automations/ui.yaml
# automation: !include automations/base.yaml
# automation cools: !include_dir_merge_list automations/include_dir_merge_list
script: !include scripts.yaml
scene: !include scenes.yaml
automation:
- alias: inline-auto
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
homeassistant:
packages: !include packages.yaml
+16
View File
@@ -0,0 +1,16 @@
ha: !include packages/ha.yaml
sub: !include_dir_merge_named packages/sub
secret_ones:
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
@@ -0,0 +1 @@
automation: !include ../automations/ui.yaml
@@ -0,0 +1,13 @@
automation:
- alias: package ha
description: Example package auto
mode: single
trigger:
- platform: homeassistant
event: start
condition: []
action:
- service: counter.increment
data: {}
target:
entity_id: counter.up_times
+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,7 @@ from tests.utils import (
HA_CONFIG10_EXAMPLE, HA_CONFIG10_EXAMPLE,
HA_CONFIG11_EXAMPLE, HA_CONFIG11_EXAMPLE,
HA_CONFIG12_EXAMPLE, HA_CONFIG12_EXAMPLE,
HA_CONFIG13_EXAMPLE,
HA_CONFIG_EXAMPLE, HA_CONFIG_EXAMPLE,
) )
@@ -160,6 +161,7 @@ class loader_tests(TestCase):
(HA_CONFIG10_EXAMPLE, 3), (HA_CONFIG10_EXAMPLE, 3),
(HA_CONFIG11_EXAMPLE, 3), (HA_CONFIG11_EXAMPLE, 3),
(HA_CONFIG12_EXAMPLE, 4), (HA_CONFIG12_EXAMPLE, 4),
(HA_CONFIG13_EXAMPLE, 4),
]: ]:
with self.subTest(config_name=ha_path.name, expected=expected): with self.subTest(config_name=ha_path.name, expected=expected):
hass_config = HassConfig(ha_path) hass_config = HassConfig(ha_path)
@@ -65,6 +65,52 @@ class dumping_yamls_tests(TestCase):
}, },
) )
def test_load_template_in_yaml(self):
yaml_obj = load_yaml(
io.StringIO(
"""
- id: '1652069225859'
alias: 'Lower the volume'
description: ''
mode: single
trigger:
- platform: state
entity_id: input_number.preferred_temperature
condition: []
action:
- service: media_player.volume_set
data_template:
entity_id: media_player.denon_avr_x2500h
volume_level: '{{ ((states(''input_number.volume_video'')|int)+80)/100 }}'
"""
),
Path.cwd(),
)
self.assertIsInstance(yaml_obj, list)
self.assertEqual(len(yaml_obj), 1)
self.assertDictEqual(
dict(yaml_obj[0]),
{
"id": "1652069225859",
"alias": "Lower the volume",
"description": "",
"mode": "single",
"trigger": [
{"platform": "state", "entity_id": "input_number.preferred_temperature"}
],
"condition": [],
"action": [
{
"service": "media_player.volume_set",
"data_template": {
"entity_id": "media_player.denon_avr_x2500h",
"volume_level": "{{ ((states('input_number.volume_video')|int)+80)/100 }}",
},
}
],
},
)
def test_load_stub(self): def test_load_stub(self):
yaml_obj = load_yaml( yaml_obj = load_yaml(
io.StringIO( io.StringIO(
+1
View File
@@ -22,6 +22,7 @@ HA_CONFIG9_EXAMPLE = SAMPLES_FOLDER / "config-9"
HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10" HA_CONFIG10_EXAMPLE = SAMPLES_FOLDER / "config-10"
HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11" HA_CONFIG11_EXAMPLE = SAMPLES_FOLDER / "config-11"
HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12" HA_CONFIG12_EXAMPLE = SAMPLES_FOLDER / "config-12"
HA_CONFIG13_EXAMPLE = SAMPLES_FOLDER / "config-13"
def get_example_automation_loader( def get_example_automation_loader(
+2 -2
View File
@@ -1,7 +1,7 @@
name: Shortumation name: Shortumation
version: v0.6.3 version: v0.7.1
slug: shortumation slug: shortumation
image: asosnovsky/shortumation-{arch} image: "asosnovsky/shortumation-{arch}"
url: "https://github.com/asosnovsky/Shortumation" url: "https://github.com/asosnovsky/Shortumation"
description: "A homeassitant addon which provides better UI for automations & scripts." description: "A homeassitant addon which provides better UI for automations & scripts."
arch: arch:
+1 -7
View File
@@ -34,15 +34,9 @@ export const makeRemoteAPI = (baseURL: string): API => ({
return response; return response;
} catch (err) { } catch (err) {
console.error(err); console.error(err);
let error = String(err);
if (err instanceof Error) {
error += ` ${err.stack}`;
}
return { return {
ok: false, ok: false,
error, error: `Server error: ${method} ${path}`,
}; };
} }
}, },
+1 -1
View File
@@ -76,7 +76,7 @@ test("update tags from mock api", async () => {
); );
let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data let data = ((await mockApi.list({ limit: 10, offset: 0 })) as any).data
.data as AutomationData[]; .data as AutomationData[];
const autoId = data[0].id; const autoId = data[0].id as string;
expect(data[0].tags).toStrictEqual({}); expect(data[0].tags).toStrictEqual({});
mockApi.updateTags({ mockApi.updateTags({
automation_id: autoId, automation_id: autoId,
@@ -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)])
); );
@@ -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">
@@ -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}
@@ -32,6 +32,8 @@ 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 "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",
@@ -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;
}; };
@@ -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,
@@ -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) {
@@ -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,
}; };
}; };
@@ -38,10 +38,11 @@ const automations: AutomationManagerAuto[] = [
description: a.description ?? "", description: a.description ?? "",
state: "on", state: "on",
tags: a.tags, tags: a.tags,
id: a.id, id: a.id as string,
isSelected: false, isSelected: false,
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
readonly: false,
configuration_key: ["automation"], configuration_key: ["automation"],
})); }));
@@ -51,7 +52,8 @@ const bigList = bigMockAutoList.map<AutomationManagerAuto>((a) => ({
description: a.description ?? "", description: a.description ?? "",
state: "on", state: "on",
tags: a.tags, tags: a.tags,
id: a.id, id: a.id as string,
readonly: false,
isSelected: false, isSelected: false,
source_file: "automation.yaml", source_file: "automation.yaml",
source_file_type: "list", source_file_type: "list",
@@ -109,7 +109,7 @@ export const MissingAutoInConfig = make({
entity_id: `automation.${auto1.id}`, entity_id: `automation.${auto1.id}`,
attributes: { attributes: {
id: auto1.id, id: auto1.id,
friendly_name: auto1.alias, friendly_name: auto1.alias ?? auto1.id ?? "",
}, },
context: { id: "", parent_id: null, user_id: null }, context: { id: "", parent_id: null, user_id: null },
last_changed: "", last_changed: "",
@@ -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;
@@ -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")}
/> />
@@ -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({
@@ -4,6 +4,7 @@ import {
InputAutoCompletePropsBase, InputAutoCompletePropsBase,
} from "./InputAutoComplete"; } from "./InputAutoComplete";
import { useHAAreas } from "haService/AreaRegistry"; import { useHAAreas } from "haService/AreaRegistry";
import { useLang } from "lang";
export type InputAreaProps = InputAutoCompletePropsBase & { export type InputAreaProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[]; restrictToDomain?: string[];
@@ -11,12 +12,13 @@ export type InputAreaProps = InputAutoCompletePropsBase & {
}; };
export const InputArea: FC<InputAreaProps> = (props) => { export const InputArea: FC<InputAreaProps> = (props) => {
const lang = useLang();
// state // state
const areas = useHAAreas(); const areas = useHAAreas();
return ( return (
<InputAutoComplete <InputAutoComplete
{...props} {...props}
label={props.label ?? "Area"} label={props.label ?? lang.get("AREA")}
getID={areas.getID} getID={areas.getID}
getLabel={areas.getLabel} getLabel={areas.getLabel}
options={areas.getOptions()} options={areas.getOptions()}
@@ -7,6 +7,7 @@ import Popper from "@mui/material/Popper";
import { SearchItem } from "./extras"; import { SearchItem } from "./extras";
import { ReactNode } from "react"; import { ReactNode } from "react";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { useLang } from "lang";
export type BaseOption<T = {}> = { export type BaseOption<T = {}> = {
id: string; id: string;
@@ -65,6 +66,7 @@ export function computeSimilarity(
export function InputAutoComplete<T extends Option>( export function InputAutoComplete<T extends Option>(
props: InputAutoCompleteProps<T> props: InputAutoCompleteProps<T>
) { ) {
const lang = useLang();
// aliases // aliases
const getID = (opt: T): string => { const getID = (opt: T): string => {
if (props.getID) { if (props.getID) {
@@ -212,7 +214,7 @@ export function InputAutoComplete<T extends Option>(
}} }}
variant="filled" variant="filled"
required={props.required} required={props.required}
label={props.label ?? "Entity ID"} label={props.label ?? lang.get("ENTITY_ID")}
helperText={helperText} helperText={helperText}
disabled={props.disabled} disabled={props.disabled}
error={error} error={error}
@@ -1,5 +1,6 @@
import { FC } from "react"; import { FC } from "react";
import { useHADeviceRegistry } from "haService"; import { useHADeviceRegistry } from "haService";
import { useLang } from "lang";
import { import {
InputAutoComplete, InputAutoComplete,
InputAutoCompletePropsBase, InputAutoCompletePropsBase,
@@ -9,11 +10,12 @@ export type InputDeviceProps = InputAutoCompletePropsBase;
export const InputDevice: FC<InputDeviceProps> = (props) => { export const InputDevice: FC<InputDeviceProps> = (props) => {
// state // state
const lang = useLang();
const dr = useHADeviceRegistry(); const dr = useHADeviceRegistry();
return ( return (
<InputAutoComplete <InputAutoComplete
{...props} {...props}
label={props.label ?? "Device"} label={props.label ?? lang.get("DEVICE")}
getID={dr.getID} getID={dr.getID}
getLabel={dr.getLabel} getLabel={dr.getLabel}
options={dr.getOptions()} options={dr.getOptions()}
@@ -1,19 +1,27 @@
import { FC } from "react"; import { FC } from "react";
import { useHAServices } from 'haService'; import { useHAServices } from "haService";
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete'; import {
import { prettyName } from 'utils/formatting'; InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { prettyName } from "utils/formatting";
import { useLang } from "lang";
export type InputServiceProps = InputAutoCompletePropsBase & { multiple?: false }; export type InputServiceProps = InputAutoCompletePropsBase & {
multiple?: false;
};
export const InputService: FC<InputServiceProps> = props => { export const InputService: FC<InputServiceProps> = (props) => {
const services = useHAServices(); const services = useHAServices();
return <InputAutoComplete const lang = useLang();
{...props} return (
label={props.label ?? "Service"} <InputAutoComplete
options={services.getOptions()} {...props}
getID={services.getID} label={props.label ?? lang.get("SERVICE")}
getLabel={services.getLabel} options={services.getOptions()}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''} getID={services.getID}
getLabel={services.getLabel}
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
/> />
} );
};
@@ -12,6 +12,7 @@ import {
} from "utils/time"; } from "utils/time";
import { InputEntity } from "./InputEntities"; import { InputEntity } from "./InputEntities";
import { InputTime } from "components/Inputs/Base/InputTime"; import { InputTime } from "components/Inputs/Base/InputTime";
import { useLang } from "lang";
export type InputTimeEntityProps = { export type InputTimeEntityProps = {
value: string; value: string;
@@ -23,6 +24,7 @@ export const InputTimeEntity: FC<InputTimeEntityProps> = ({
onChange, onChange,
className = "", className = "",
}) => { }) => {
const lang = useLang();
const is24Hour = isAutomationTimeString24Hours(value); const is24Hour = isAutomationTimeString24Hours(value);
let editor: ReactNode; let editor: ReactNode;
if (is24Hour) { if (is24Hour) {
@@ -39,7 +41,7 @@ export const InputTimeEntity: FC<InputTimeEntityProps> = ({
} else { } else {
editor = ( editor = (
<InputEntity <InputEntity
label="Time Entity" label={lang.get("TIME_ENTITY")}
restrictMode="or" restrictMode="or"
restrictedDeviceClass={["timestamp"]} restrictedDeviceClass={["timestamp"]}
restrictToDomain={["input_datetime"]} restrictToDomain={["input_datetime"]}
+22 -15
View File
@@ -12,6 +12,7 @@ import {
} from "utils/time"; } from "utils/time";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import { useLang } from "lang";
// constants // constants
const fields: Array<keyof AutomationTimeObject> = [ const fields: Array<keyof AutomationTimeObject> = [
@@ -29,6 +30,7 @@ export type InputTimeProps = {
}; };
export const InputTime: FC<InputTimeProps> = (props) => { export const InputTime: FC<InputTimeProps> = (props) => {
// state // state
const lang = useLang();
const [disabled, setDisabled] = useState(!props.value); const [disabled, setDisabled] = useState(!props.value);
const [displayValue, setDisplayValue] = useState( const [displayValue, setDisplayValue] = useState(
convertAutomationTimeToTimeObject(props.value) convertAutomationTimeToTimeObject(props.value)
@@ -127,21 +129,26 @@ export const InputTime: FC<InputTimeProps> = (props) => {
<div className={["input-time", props.className ?? ""].join(" ")}> <div className={["input-time", props.className ?? ""].join(" ")}>
{/* <InputLabel >{props.label}</InputLabel> */} {/* <InputLabel >{props.label}</InputLabel> */}
<div className="input-time--inner"> <div className="input-time--inner">
{fields.map((name) => ( {fields.map((name) => {
<TextField const label = prettyName(
key={name} lang.get(`TIME_UNITS_${name}`.toUpperCase())
variant="filled" );
label={prettyName(name)} return (
defaultValue="00" <TextField
InputProps={{ key={name}
disabled, variant="filled"
type: "number", label={label}
title: prettyName(name), defaultValue="00"
}} InputProps={{
value={displayValue[name] ?? 0} disabled,
onChange={(e) => updateOne(name)(e.target.value)} type: "number",
/> title: label,
))} }}
value={displayValue[name] ?? 0}
onChange={(e) => updateOne(name)(e.target.value)}
/>
);
})}
{!props.restrictEmpty && ( {!props.restrictEmpty && (
<ButtonIcon <ButtonIcon
onClick={() => setDisabled(!disabled)} onClick={() => setDisabled(!disabled)}
@@ -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 "haService";
import { HAEntitiesState } from "haService/HAEntities"; import { HAEntitiesState } from "haService/HAEntities";
import { LangStore } from "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 "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({
@@ -158,6 +158,7 @@ export const useEditorNodeState = (
setState={setState} setState={setState}
ha={ha} ha={ha}
createMode={createMode} createMode={createMode}
langStore={langStore}
/> />
)} )}
</> </>
+1 -1
View File
@@ -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"
+1 -3
View File
@@ -60,9 +60,7 @@ export const InternalPage: FC<PageProps> = ({ children, api }) => {
}, [conn, snackbar]); }, [conn, snackbar]);
return ( return (
<main <main className={["page", "column", isMobile ? "mobile" : ""].join(" ")}>
className={["page", "center column", isMobile ? "mobile" : ""].join(" ")}
>
<div className="page-contents column">{children}</div> <div className="page-contents column">{children}</div>
<BottomBar api={api} /> <BottomBar api={api} />
<style> <style>
+4 -2
View File
@@ -29,10 +29,12 @@ export const makeStory = <
}; };
const Template: ComponentStory<T> = (args) => { const Template: ComponentStory<T> = (args) => {
let api: ApiService; let api: ApiService;
const connApi = useConnectedApiService();
const mockApi = useMockApiService([]);
if (useLiveApi) { if (useLiveApi) {
api = useConnectedApiService(); api = connApi;
} else { } else {
api = useMockApiService([]); api = mockApi;
} }
return ( return (
+1 -4
View File
@@ -1,6 +1,5 @@
import React, { FC, useEffect, useState } from "react"; import React, { FC, useEffect, useState } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { makeStory } from "devUtils";
import { Page } from "components/Page";
import { useHA } from "haService"; import { useHA } from "haService";
import InputYaml from "components/Inputs/Base/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
@@ -78,8 +77,6 @@ const Test: FC = () => {
); );
}; };
import { makeStory } from "devUtils";
const { make, componentMeta } = makeStory({ const { make, componentMeta } = makeStory({
Component: Test, Component: Test,
meta: { meta: {
+22 -1
View File
@@ -1,5 +1,6 @@
{ {
"ADD": "Add", "ADD": "Add",
"AREA": "Area",
"ALIAS": "Alias", "ALIAS": "Alias",
"ATTRIBUTE": "Attribute", "ATTRIBUTE": "Attribute",
"ABOVE": "Above", "ABOVE": "Above",
@@ -34,8 +35,10 @@
"OR": "Or", "OR": "Or",
"ZONE": "Zone", "ZONE": "Zone",
"ENTITY": "Entity", "ENTITY": "Entity",
"ENTITY_ID": "Entity ID",
"ENABLED": "Enabled", "ENABLED": "Enabled",
"ENTITY_WITH_LOCATION": "Entity with Location", "ENTITY_WITH_LOCATION": "Entity with Location",
"TIME_ENTITY": "Time Entity",
"AND_MORE": "and more", "AND_MORE": "and more",
"YES": "Yes", "YES": "Yes",
"NO": "No", "NO": "No",
@@ -43,16 +46,28 @@
"SERVICE": "Service", "SERVICE": "Service",
"REPEAT": "Repeat", "REPEAT": "Repeat",
"WAIT": "Wait", "WAIT": "Wait",
"WAIT_TYPE": "Wait Type",
"STOP": "Stop", "STOP": "Stop",
"STOP_REASON": "Stop Reason",
"CHOOSE": "Choose", "CHOOSE": "Choose",
"PARALLEL": "Parallel", "PARALLEL": "Parallel",
"SCENE": "Scene", "SCENE": "Scene",
"TIME_UNITS_HOURS": "hours",
"TIME_UNITS_MINUTES": "minutes",
"TIME_UNITS_SECONDS": "seconds",
"TIME_UNITS_MILISECONDS": "milliseconds",
"TIMEOUT": "Timeout",
"CONTINUTE_ON_TIMEOUT": "Continue on Timeout",
"FOR": "For",
"AND": "and", "AND": "and",
"NOT": "not", "NOT": "not",
"NUMERIC_STATE": "Numeric State", "NUMERIC_STATE": "Numeric State",
"TIME": "Time", "TIME": "Time",
"EVENT": "Event", "EVENT": "Event",
"EVENT_DATA": "Event Data",
"HOMEASSISTANT": "Home Assistant", "HOMEASSISTANT": "Home Assistant",
"CALENDAR": "Calendar", "CALENDAR": "Calendar",
"WEBHOOK": "Webhook", "WEBHOOK": "Webhook",
@@ -109,6 +124,7 @@
"ISSUES_INVALID_STATE": "Recived invalid state '{{state}}', this could be because you have a lingering automation that was not cleared by homeassistant, try to reboot HA or manually clear this automation from HA Database.", "ISSUES_INVALID_STATE": "Recived invalid state '{{state}}', this could be because you have a lingering automation that was not cleared by homeassistant, try to reboot HA or manually clear this automation from HA Database.",
"ISSUES_FIND_AUTOMATION_IN_CONFIG": "failed to find this automation in '/config' folder", "ISSUES_FIND_AUTOMATION_IN_CONFIG": "failed to find this automation in '/config' folder",
"ISSUES_NO_LOAD_AUTOMATION": "homeassistant did not load this automation, try to manually reload automations or restart homeassistant.", "ISSUES_NO_LOAD_AUTOMATION": "homeassistant did not load this automation, try to manually reload automations or restart homeassistant.",
"ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT": "In order to modify an automation you have specify a unique id. Please go to the file '{{sourceFile}}' and add an `id` field to the automation.",
"AUTOMATION_STATE_UNREGISTERED": "unregistered", "AUTOMATION_STATE_UNREGISTERED": "unregistered",
"AUTOMATION_STATE_ON": "On", "AUTOMATION_STATE_ON": "On",
@@ -154,5 +170,10 @@
"WARNING_SWITCHING_FROM_NONE_SAVE": "Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.", "WARNING_SWITCHING_FROM_NONE_SAVE": "Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.",
"WARNING_DEVICE_NO_TYPES": "This device has no {{type}}.", "WARNING_DEVICE_NO_TYPES": "This device has no {{type}}.",
"INFO_SUCCESS_CALL": "Successfully called {{entityId}}" "INFO_SUCCESS_CALL": "Successfully called {{entityId}}",
"HOW_MANY_TIMES": "How many times?",
"READONLY_MODE": "Read Only Mode",
"READONLY_CANNOT_UPDATE": "Cannot update in readonly mode"
} }
+45 -24
View File
@@ -1,9 +1,10 @@
{ {
"ADD": "Ajouter", "ADD": "Ajouter",
"ALIAS": "Pseudonyme", "AREA": "Zone",
"ALIAS": "Alias",
"ATTRIBUTE": "Attribuer", "ATTRIBUTE": "Attribuer",
"ABOVE": "Plus grand que", "ABOVE": "Plus grand que",
"BELOW": "Moins que", "BELOW": "Plus petit que",
"ID": "Id", "ID": "Id",
"NAME": "Nom", "NAME": "Nom",
"TAG": "Étiquette", "TAG": "Étiquette",
@@ -12,24 +13,24 @@
"ACTION": "Opération", "ACTION": "Opération",
"ACTIONS": "Opérations", "ACTIONS": "Opérations",
"TAG_NAME": "Nom de l'étiquette", "TAG_NAME": "Nom de l'étiquette",
"TAG_VALUE": "Valeur de balise", "TAG_VALUE": "Valeur de l'étiquette",
"TYPE": "Taper", "TYPE": "Taper",
"TITLE": "Titre", "TITLE": "Titre",
"TRIGGER_ID": "ID déclencheur", "TRIGGER_ID": "ID déclencheur",
"TEMPLATE": "Gabarit", "TEMPLATE": "Modèle",
"MODE": "Mode", "MODE": "Mode",
"CLOSE": "Proche", "CLOSE": "Fermer",
"DESCRIPTION": "Description", "DESCRIPTION": "Description",
"TRIGGER": "Déclencheur", "TRIGGER": "Déclencheur",
"TRIGGERS": "Déclencheurs", "TRIGGERS": "Déclencheurs",
"CONDITION": "Condition", "CONDITION": "Condition",
"CONDITIONS": "Les conditions", "CONDITIONS": "Les conditions",
"DELETE": "Supprimez", "DELETE": "Supprimer",
"METADATA": "Metadata", "METADATA": "Métadonnées",
"UNDO": "Undo", "UNDO": "Annuler",
"RAW": "Raw", "RAW": "Brut",
"SAVE": "Sauver", "SAVE": "Enregistrer",
"STATE": "State", "STATE": "Statut",
"SEARCH": "Chercher", "SEARCH": "Chercher",
"FLIPP": "Retourner", "FLIPP": "Retourner",
"CANCEL": "Annuler", "CANCEL": "Annuler",
@@ -37,8 +38,10 @@
"OR": "Ou", "OR": "Ou",
"ZONE": "Zone", "ZONE": "Zone",
"ENTITY": "Entité", "ENTITY": "Entité",
"ENTITY_ID": "ID d'entité",
"ENABLED": "Activé", "ENABLED": "Activé",
"ENTITY_WITH_LOCATION": "Entité avec emplacement", "ENTITY_WITH_LOCATION": "Entité avec emplacement",
"TIME_ENTITY": "Entité temporelle",
"AND_MORE": "et plus", "AND_MORE": "et plus",
"YES": "Oui", "YES": "Oui",
"NO": "Non", "NO": "Non",
@@ -46,21 +49,33 @@
"SERVICE": "Service", "SERVICE": "Service",
"REPEAT": "Répéter", "REPEAT": "Répéter",
"WAIT": "Attendre", "WAIT": "Attendre",
"WAIT_TYPE": "Type d'attente",
"STOP": "Arrêt", "STOP": "Arrêt",
"STOP_REASON": "Raison d'arrêt",
"CHOOSE": "Choisir", "CHOOSE": "Choisir",
"PARALLEL": "Parallèle", "PARALLEL": "Parallèle",
"SCENE": "Scène", "SCENE": "Scène",
"EVENT": "Événement", "EVENT": "Événement",
"EVENT_DATA": "Données d'événement",
"HOMEASSISTANT": "Home Assistant", "HOMEASSISTANT": "Home Assistant",
"CALENDAR": "Calendrier", "CALENDAR": "Calendrier",
"WEBHOOK": "Webhook", "WEBHOOK": "Webhook",
"SUN": "Sol", "SUN": "Soleil",
"MQTT": "MQTT", "MQTT": "MQTT",
"TIME_UNITS_HOURS": "heures",
"TIME_UNITS_MINUTES": "minutes",
"TIME_UNITS_SECONDS": "secondes",
"TIME_UNITS_MILISECONDS": "millisecondes",
"TIMEOUT": "Temps libre",
"CONTINUTE_ON_TIMEOUT": "Continuer sur Timeout",
"CONNECTED": "Connecté", "CONNECTED": "Connecté",
"FAILED": "Manquée", "FAILED": "Échoué",
"LOADING": "Chargement", "LOADING": "Chargement",
"FOR": "Pour",
"AND": "et", "AND": "et",
"NOT": "non", "NOT": "non",
"NUMERIC_STATE": "État numérique", "NUMERIC_STATE": "État numérique",
@@ -95,7 +110,7 @@
"MISSING_TEXT": "TEXTE MANQUANT --{{langId}}", "MISSING_TEXT": "TEXTE MANQUANT --{{langId}}",
"AUTOMATION_METADATA_TOOLTIP_TEXT": "Cette automatisation se trouve dans le fichier {{source_file}}. Il s'agit actuellement de '{{state}}', son identifiant d'entité est '{{entityId}}' et son identifiant d'automatisation est '{{id}}'", "AUTOMATION_METADATA_TOOLTIP_TEXT": "Cette automatisation se trouve dans le fichier {{source_file}}. Elle est actuellement '{{state}}', son identifiant d'entité est '{{entityId}}' et son identifiant d'automatisation est '{{id}}'",
"ERROR_FAILED_TO_SAVE": "Échec de l'enregistrement du contenu de l'automatisation \"{{aid}}\" - {{contents}} -- introuvable dans `/config`", "ERROR_FAILED_TO_SAVE": "Échec de l'enregistrement du contenu de l'automatisation \"{{aid}}\" - {{contents}} -- introuvable dans `/config`",
"ERROR_INVALID_AUTOMATION_STATE": "Etat non valide", "ERROR_INVALID_AUTOMATION_STATE": "Etat non valide",
@@ -108,9 +123,10 @@
"AUTOMATION_STATE_IS": "L'automatisation est {{state}}", "AUTOMATION_STATE_IS": "L'automatisation est {{state}}",
"ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK": "Impossible de trouver une automatisation sur le disque avec id = {{id}}", "ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK": "Impossible de trouver une automatisation sur le disque avec id = {{id}}",
"ISSUES_INVALID_STATE": "État invalide reçu '{{state}}', cela peut être dû au fait que vous avez une automatisation persistante qui n'a pas été effacée par homeassistant, essayez de redémarrer HA ou effacez manuellement cette automatisation de la base de données HA.", "ISSUES_INVALID_STATE": "État invalide reçu '{{state}}', cela peut être dû au fait que vous avez une automatisation persistante qui n'a pas été effacée par Home Assistant, essayez de redémarrer Home Assistant ou effacez manuellement cette automatisation de la base de données HA.",
"ISSUES_FIND_AUTOMATION_IN_CONFIG": "impossible de trouver cette automatisation dans le dossier '/config'", "ISSUES_FIND_AUTOMATION_IN_CONFIG": "impossible de trouver cette automatisation dans le dossier '/config'",
"ISSUES_NO_LOAD_AUTOMATION": "homeassistant n'a pas chargé cette automatisation, essayez de recharger manuellement les automatisations ou redémarrez homeassistant.", "ISSUES_NO_LOAD_AUTOMATION": "homeassistant n'a pas chargé cette automatisation, essayez de recharger manuellement les automatisations ou redémarrez Home Assistant.",
"ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT": "Pour modifier une automatisation, vous devez spécifier un identifiant unique. Veuillez aller dans le fichier '{{sourceFile}}' et ajouter un champ `id` à l'automatisation.",
"AUTOMATION_STATE_UNREGISTERED": "non enregistré", "AUTOMATION_STATE_UNREGISTERED": "non enregistré",
"AUTOMATION_STATE_ON": "Activé", "AUTOMATION_STATE_ON": "Activé",
@@ -118,7 +134,7 @@
"AUTOMATION_MANAGER_STATE_CHANGE": "modification de l'état de l'automatisation", "AUTOMATION_MANAGER_STATE_CHANGE": "modification de l'état de l'automatisation",
"AUTOMATION_MANAGER_STATE_CHANGE_FAIL": "Impossible de basculer l'automatisation en raison de \"{{err}}\"", "AUTOMATION_MANAGER_STATE_CHANGE_FAIL": "Impossible de basculer l'automatisation en raison de \"{{err}}\"",
"AUTOMATION_MANAGER_REFRESH": "automatisations rafraîchissantes", "AUTOMATION_MANAGER_REFRESH": "Actualisation des automatisations",
"AUTOMATION_MANAGER_REFRESH_FAIL": "Échec de l'actualisation des automatisations en raison de \"{{err}}\"", "AUTOMATION_MANAGER_REFRESH_FAIL": "Échec de l'actualisation des automatisations en raison de \"{{err}}\"",
"AUTOMATION_MANAGER_DELETE": "suppression des automatisation", "AUTOMATION_MANAGER_DELETE": "suppression des automatisation",
"AUTOMATION_MANAGER_DELETE_FAIL": "Échec de la suppression en raison de \"{{err}}\"", "AUTOMATION_MANAGER_DELETE_FAIL": "Échec de la suppression en raison de \"{{err}}\"",
@@ -138,8 +154,8 @@
"N/A": "n/a", "N/A": "n/a",
"VALIDATION_AUTOMATION_NAME": "Le nom doit comporter au moins 1 caractère", "VALIDATION_AUTOMATION_NAME": "Le nom doit comporter au moins 1 caractère",
"VALIDATION_MAX_TAG_SELECTION": "Ne peut sélectionner que {{count}} tags maximum", "VALIDATION_MAX_TAG_SELECTION": "Ne peut sélectionner que {{count}} étiquettes maximum",
"VALIDATION_TAG_EXISTS": "Le tag '{{name}}' existe déjà", "VALIDATION_TAG_EXISTS": "L'étiquette \"{{name}}\" existe déjà",
"VALIDATION_PLEASE_CORRECT_FILE": "Veuillez corriger le fichier d'automatisation manuellement, puis continuer !", "VALIDATION_PLEASE_CORRECT_FILE": "Veuillez corriger le fichier d'automatisation manuellement, puis continuer !",
"VALIDATION_MISSING_VALUES_FOR_NODE": "Il manque certaines valeurs à ce nœud", "VALIDATION_MISSING_VALUES_FOR_NODE": "Il manque certaines valeurs à ce nœud",
"VALIDATION_ERROR_VALUES_IN_NODE": "Ce nœud contient des erreurs", "VALIDATION_ERROR_VALUES_IN_NODE": "Ce nœud contient des erreurs",
@@ -148,13 +164,18 @@
"CONFIRM_EXIT": "Êtes-vous sûr de vouloir {{what}}?", "CONFIRM_EXIT": "Êtes-vous sûr de vouloir {{what}}?",
"MODE_SIGNLE_LABEL": "Ne démarrez pas une nouvelle course. Émettre un avertissement.", "MODE_SIGNLE_LABEL": "Ne pas démarrer une nouvelle exécution. Émettre un avertissement.",
"MODE_SIGNLE_PARALLEL": "Démarrez une nouvelle analyse indépendante en parallèle avec les analyses précédentes.", "MODE_SIGNLE_PARALLEL": "Démarrer une nouvelle exécution indépendante en parallèle avec les exécutions précédentes.",
"MODE_SIGNLE_QUEUED": "Démarrez une nouvelle exécution une fois toutes les exécutions précédentes terminées. Les exécutions sont garanties de s'exécuter dans l'ordre dans lequel elles ont été mises en file d'attente.", "MODE_SIGNLE_QUEUED": "Démarrer une nouvelle exécution une fois toutes les exécutions précédentes terminées. Les exécutions sont garanties de s'exécuter dans l'ordre dans lequel elles ont été mises en file d'attente.",
"MODE_SIGNLE_RESTART": "Démarrez une nouvelle analyse après avoir arrêté l'analyse précédente.", "MODE_SIGNLE_RESTART": "Démarrer une nouvelle exécution après avoir arrêté l'exécution précédente.",
"WARNING_SWITCHING_FROM_NONE_SAVE": "La sélection d'une autre automatisation vous fera perdre tout le travail effectué sur cette nouvelle automatisation. Veuillez d'abord enregistrer votre travail sur cette automatisation.", "WARNING_SWITCHING_FROM_NONE_SAVE": "La sélection d'une autre automatisation vous fera perdre tout le travail effectué sur cette nouvelle automatisation. Veuillez d'abord enregistrer votre travail sur cette automatisation.",
"WARNING_DEVICE_NO_TYPES": "Cet appareil n'a pas de {{type}}.", "WARNING_DEVICE_NO_TYPES": "Cet appareil n'a pas de {{type}}.",
"INFO_SUCCESS_CALL": "{{entityId}} a été appelé avec succès" "INFO_SUCCESS_CALL": "{{entityId}} a été appelé avec succès",
"HOW_MANY_TIMES": "Données d'événementaCombien de fois?",
"READONLY_MODE": "Mode lecture seule",
"READONLY_CANNOT_UPDATE": "Impossible de mettre à jour en mode lecture seule"
} }
+179
View File
@@ -0,0 +1,179 @@
{
"ADD": "Aggiungi",
"AREA": "La zona",
"ALIAS": "Alias",
"ATTRIBUTE": "Attributo",
"ABOVE": "Above",
"BELOW": "Below",
"ID": "Id",
"NAME": "Nome",
"TAG": "Tag",
"TAGS": "Tags",
"DEVICE": "Dispositivo",
"ACTION": "Azione",
"TAG_NAME": "Nome Tag",
"TAG_VALUE": "Valore Tag",
"TITLE": "Titolo",
"TYPE": "Tipo",
"TRIGGER_ID": "ID Attivazione",
"TEMPLATE": "Modello",
"MODE": "Modalità",
"CLOSE": "Chiudi",
"DESCRIPTION": "Descrizione",
"TRIGGER": "Attivazione",
"CONDITION": "Condizione",
"DELETE": "Elimina",
"METADATA": "Metadata",
"UNDO": "Annulla",
"RAW": "Raw",
"SAVE": "Salva",
"STATE": "Stato",
"SEARCH": "Cerca",
"FLIPP": "Flip",
"CANCEL": "Cancella",
"CREATE": "Crea",
"OR": "Oppure",
"ZONE": "Zona",
"ENTITY": "Entità",
"ENTITY_ID": "ID entità",
"ENABLED": "A",
"ENTITY_WITH_LOCATION": "Entità con posizione",
"TIME_ENTITY": "Entità Tempo",
"AND_MORE": "e altro",
"YES": "Sì",
"NO": "No",
"SERVICE": "Chiama Servizio",
"REPEAT": "Ripeti",
"WAIT": "Attesa",
"WAIT_TYPE": "Tipo di attesa",
"STOP": "Ferma",
"STOP_REASON": "Ferma la ragione",
"CHOOSE": "Scegli",
"PARALLEL": "Eseguire in parallelo",
"SCENE": "Scena",
"TIME_UNITS_HOURS": "ore",
"TIME_UNITS_MINUTES": "minuti",
"TIME_UNITS_SECONDS": "secondi",
"TIME_UNITS_MILISECONDS": "millisecondi",
"TIMEOUT": "Tempo scaduto",
"CONTINUTE_ON_TIMEOUT": "Continua su Timeout",
"FOR": "Per",
"AND": "e",
"NOT": "non",
"NUMERIC_STATE": "Valore Numerico",
"TIME": "Ora",
"EVENT": "Evento",
"EVENT_DATA": "Dati dell'evento",
"HOMEASSISTANT": "Home Assistant",
"CALENDAR": "Calendario",
"WEBHOOK": "Webhook",
"SUN": "Sole",
"MQTT": "MQTT",
"CONNECTED": "Connesso",
"FAILED": "Fallito",
"LOADING": "Caricamento",
"DAY_MON": "Lunedì",
"DAY_TUE": "Martedì",
"DAY_WED": "Mercoledì",
"DAY_THU": "Giovedì",
"DAY_FRI": "Venerdì",
"DAY_SAT": "Sabato",
"DAY_SUN": "Domenica",
"WEEKDAY": "Giorno della settimana",
"OPTION": "Opzione",
"THEME": "Tema",
"LANGUAGE": "Lingua",
"USER_PRERENCES": "Impostazioni",
"SELECT_AUTOMATION": "Seleziona automazione",
"TRIGGER_AUTOMATION": "Innesca Automazione",
"DELETE_AUTOMATION": "Elimina automazione",
"CONFIRMATION_DELETE_THIS_AUTOMATION": "Sei sicuro di voler eliminare questa automazione?",
"CONFIRMATION_DELETE_THIS_NODE": "Sei sicuro di voler eliminare questo nodo?",
"DELETED": "Eliminato.",
"NOT_DELETED_NODE": "Il nodo non è stato eliminato.",
"NOT_DELETED_THING": "{{item}} non è stato eliminato.",
"MISSING_TEXT": "TESTO MANCANTE -- {{langId}}",
"AUTOMATION_METADATA_TOOLTIP_TEXT": "Questa automazione si trova nel file {{source_file}}. It's currently '{{state}}', it's entity id is '{{entityId}}' and it's automation id is '{{id}}'",
"AUTOMATION_METADATA_TOOLTIP_SIMPLE": "ID={{id}}, ID Entità={{entityId}}",
"ERROR_FAILED_TO_SAVE": "Salvataggio dell'automazione fallito \"{{aid}}\" contents - {{contents}} -- non trovato in `/config`",
"ERROR_INVALID_AUTOMATION_STATE": "Stato Non Valido",
"ERROR_INVALID_AUTOMATION_DETECTED": "Rilevate Automazioni Non Valide!",
"ERROR_FAILED_CONNECTION_TO_HA": "Connessione al websocket fallita, perfavore controlla che il tuo token di accesso sia impostato correttamente.",
"ERROR_FAILED_CALLING": "Chiamata di {{entityId}} fallita perchè '{{msg}}'",
"ERROR_FAILED_CALLING_BC_CONNECTION": "Chiamata al servizio fallita perchè la connessione è '{{connStatus}}' -- {{connError}}",
"ERROR_INVALID_YAML": "! Yaml non valido !",
"AUTOMATION_STATE_IS": "L'automazione è {{state}}",
"ISSUE_FAILED_TO_FIND_AUTOMATION_ON_DISK": "Rcierca sul disco dell'automazione con id = {{id}} fallita ",
"ISSUES_INVALID_STATE": "Ricevuto uno stato non valido '{{state}}', questo potrebbe essere causato da una automazione persistente che non è stata cancellata da homeassistant, prova a riavviare HA o ad eliminare manualmente questa automazione dal database di HA.",
"ISSUES_FIND_AUTOMATION_IN_CONFIG": "ricerca dell'automazione fallita nella cartella '/config' ",
"ISSUES_NO_LOAD_AUTOMATION": "homeassistant non ha caricato questa automazione, prova a ricaricare manualmente le automazioni o riavvia homeassistant.",
"ISSUE_MUST_CONTAIN_A_UNQIUE_ID_TO_EDIT": "Per modificare un'automazione è necessario specificare un ID univoco. Vai al file '{{sourceFile}}' e aggiungi un campo `id` all'automazione.",
"AUTOMATION_STATE_UNREGISTERED": "Non registrata",
"AUTOMATION_STATE_ON": "On",
"AUTOMATION_STATE_OFF": "Off",
"AUTOMATION_MANAGER_STATE_CHANGE": "cambiando lo stato dell'automazione",
"AUTOMATION_MANAGER_STATE_CHANGE_FAIL": "Failed to toggle automation due to \"{{err}}\"",
"AUTOMATION_MANAGER_REFRESH": "aggiornamento automazioni",
"AUTOMATION_MANAGER_REFRESH_FAIL": "Aggiornamento delle automazioni fallito a causa di \"{{err}}\"",
"AUTOMATION_MANAGER_DELETE": "eliminando l'automazione",
"AUTOMATION_MANAGER_DELETE_FAIL": "Eliminazione fallita a causa di \"{{err}}\"",
"AUTOMATION_MANAGER_TRIGGER": "attivando l'automazione",
"AUTOMATION_MANAGER_TRIGGER_FAIL": "Attivazione fallita a causa di \"{{err}}\"",
"AUTOMATION_MANAGER_ADD": "aggiungendo l'automazione",
"AUTOMATION_MANAGER_ADD_FAIL": "Aggiunta delle automazioni fallito a causa di \"{{err}}\"",
"AUTOMATION_MANAGER_UPDATE": "aggironando l'automazione",
"AUTOMATION_MANAGER_UPDATE_FAIL": "Aggiornamento delle automazioni fallito a causa di \"{{err}}\"",
"AUTOMATION_MANAGER_UPDATE_TAGS": "Aggiornando i tag delle automazioni",
"AUTOMATION_MANAGER_UPDATE_TAGS_FAIL": "Aggiornamento dei tag delle automazioni fallito a causa di \"{{err}}\"",
"AUTOMATION_MANAGER_DELETE_LIGHT": "Eliminazione dell'automazione fallita, potresti risolvere aggiornando o riavviando Home Assistant",
"NEW_AUTOMATION": "Nuova Automazione",
"SWITCH_AUTOMATION": "Cambia Automazione",
"N/A": "n/d",
"VALIDATION_AUTOMATION_NAME": "Il nome deve essere lungo almeno un 1 carattere",
"VALIDATION_MAX_TAG_SELECTION": "Puoi selezionare massimo {{count}} tag",
"VALIDATION_TAG_EXISTS": "Il tag '{{name}}' esiste già",
"VALIDATION_PLEASE_CORRECT_FILE": "Perfavore correggi il file dell'automazione manualmente e poi continua !",
"VALIDATION_MISSING_VALUES_FOR_NODE": "Questo nodo contiene dei valori mancanti",
"VALIDATION_ERROR_VALUES_IN_NODE": "Questo nodo contiene errori",
"VALIDATION_UNSAVED_WORK_IN_NODE": "Questo nodo ha delle modifiche non salvate",
"VALIDATION_NOT_ALL_FIELD_FILLED_IN": "Alcuni campi non sono stati compilati correttamente",
"CONFIRM_EXIT": "Sei sicuro di voler {{what}}?",
"MODE_SIGNLE_LABEL": "Non avviare una nuova esecuzione. Fornisci un avvertimento.",
"MODE_SIGNLE_PARALLEL": "Avvia una nuova e indipendente esecuzione in parallelo con le esecuzioni precedenti.",
"MODE_SIGNLE_QUEUED": "Avvia una nuova esecuzione dopo che tutte le altre sono state completate. Le esecuzioni partiranno nell'ordine in cui sono state accodate.",
"MODE_SIGNLE_RESTART": "Avvia una nuova esecuzione dopo aver fermato quella precedente.",
"WARNING_SWITCHING_FROM_NONE_SAVE": "Selezionando un'altra automazione perderai tutte le modifiche effettuate a questa nuova automazione. Salva prima le modifiche.",
"WARNING_DEVICE_NO_TYPES": "Questo dispositivo non ha {{type}}.",
"INFO_SUCCESS_CALL": "{{entityId}} chiamata con successo",
"HOW_MANY_TIMES": "Dati eventoaQuante volte?",
"READONLY_MODE": "Modalità di sola lettura",
"READONLY_CANNOT_UPDATE": "Impossibile aggiornare in modalità di sola lettura"
}
+2 -2
View File
@@ -1,7 +1,7 @@
import * as st from "superstruct"; import * as st from "superstruct";
export const AutomationData = st.object({ export const AutomationData = st.object({
id: st.string(), id: st.nullable(st.string()),
alias: st.optional(st.string()), alias: st.optional(st.string()),
description: st.optional(st.string()), description: st.optional(st.string()),
trigger_variables: st.optional( trigger_variables: st.optional(
@@ -20,7 +20,7 @@ export const AutomationData = st.object({
}); });
export const BareAutomationData = st.object({ export const BareAutomationData = st.object({
id: st.string(), id: st.nullable(st.string()),
alias: st.optional(st.string()), alias: st.optional(st.string()),
description: st.optional(st.string()), description: st.optional(st.string()),
trigger_variables: st.optional( trigger_variables: st.optional(
+1 -1
View File
@@ -1,7 +1,7 @@
import * as st from "superstruct"; import * as st from "superstruct";
export const AutomationMetadata = st.object({ export const AutomationMetadata = st.object({
id: st.string(), id: st.nullable(st.string()),
alias: st.optional(st.string()), alias: st.optional(st.string()),
description: st.optional(st.string()), description: st.optional(st.string()),
trigger_variables: st.optional( trigger_variables: st.optional(
+3 -1
View File
@@ -62,7 +62,9 @@ export const getConditionDefaultValues = (
} as any; } as any;
}; };
export const defaultAutomation = (id: string): BareAutomationData => ({ export const defaultAutomation = (
id: string
): BareAutomationData & { id: string } => ({
id, id,
alias: "New Automation", alias: "New Automation",
description: "", description: "",