From bfc95db6f65d37eeedb1a0a994748a6dedd3fc21 Mon Sep 17 00:00:00 2001 From: Ari Date: Thu, 12 May 2022 17:45:10 -0400 Subject: [PATCH] cleaned up multinode stlying --- api/src/automations/deparser.py | 49 +++++ api/src/automations/types.py | 2 +- api/src/hass_config/__init__.py | 6 +- .../samples/config/.shortumations/tags.yaml | 77 +++++++ api/tests/unittests/api/test_automations.py | 205 ++++++++++++++++++ .../unittests/automations/test_parsers.py | 1 + api/tests/unittests/test_yaml_serializer.py | 3 +- .../src/components/ConditionEditor/style.ts | 9 +- webapp/src/components/DAGFlow/index.tsx | 5 +- .../src/components/MultiNodeEditors/index.css | 15 ++ .../MultiNodeEditors/index.stories.tsx | 4 +- .../src/components/MultiNodeEditors/index.tsx | 74 +++---- webapp/src/components/NodeEditor/index.css | 4 + webapp/src/components/NodeEditor/index.tsx | 17 +- 14 files changed, 402 insertions(+), 69 deletions(-) create mode 100644 api/src/automations/deparser.py create mode 100644 api/tests/samples/config/.shortumations/tags.yaml create mode 100644 webapp/src/components/MultiNodeEditors/index.css diff --git a/api/src/automations/deparser.py b/api/src/automations/deparser.py new file mode 100644 index 0000000..c715d97 --- /dev/null +++ b/api/src/automations/deparser.py @@ -0,0 +1,49 @@ + + + +from typing import Iterable, Union + +from src.automations.types import AutomationActionNode, AutomationConditionNode + + +def _deparse(nodes: Iterable[Union[AutomationActionNode, AutomationConditionNode]]) -> Iterable[dict]: + for node in nodes: + if isinstance(node, AutomationActionNode): + yield from _deparse_action(node) + elif isinstance(node, AutomationConditionNode): + yield from _deparse_condition(node) + else: + raise NotImplementedError(type(node)) + +def _deparse_action(action: AutomationActionNode) -> Iterable[dict]: + if action.action == 'repeat': + raw_data = action.action_data + repeat_data = raw_data.pop("repeat") + yield { + **raw_data, + "repeat": { + **repeat_data, + "sequence": list(_deparse(repeat_data['sequence'])) + } + } + elif action.action == 'choose': + raw_data = action.action_data + choose_data = raw_data.pop("choose") + default_data = raw_data.pop("default", []) + yield { + **raw_data, + "choose": [ + { + "conditions": list(map(_deparse_condition, option.get("conditions", []))), + "sequence": list(_deparse(option.get("sequence", []))), + } + for option in choose_data + ], + "default": list(_deparse(default_data)), + } + else: + yield action.action_data + + +def _deparse_condition(condition: AutomationConditionNode) -> Iterable[dict]: + raise NotImplementedError \ No newline at end of file diff --git a/api/src/automations/types.py b/api/src/automations/types.py index f85fa9d..bb6b2e8 100644 --- a/api/src/automations/types.py +++ b/api/src/automations/types.py @@ -39,7 +39,7 @@ class AutomationData(BaseModel): def to_primitive(self): return { - **self.metadata.dict(), + **self.metadata.dict(exclude_unset=True, exclude_none=True), "trigger": self.trigger, "condition": [], "action": [action.to_primitive() for action in self.sequence], diff --git a/api/src/hass_config/__init__.py b/api/src/hass_config/__init__.py index 2e909c7..b1eab3c 100644 --- a/api/src/hass_config/__init__.py +++ b/api/src/hass_config/__init__.py @@ -10,8 +10,10 @@ def find_hass_config() -> HassConfig: if config("USE_EXAMPLE_REPO", False, cast=bool): print("using USE_EXAMPLE_REPO") from tests.utils import create_copy_of_example_config - - return HassConfig(create_copy_of_example_config()) + + path = create_copy_of_example_config() + print("|-> ", path) + return HassConfig(path) if "HASSIO_TOKEN" in os.environ: return HassConfig(Path("/config")) diff --git a/api/tests/samples/config/.shortumations/tags.yaml b/api/tests/samples/config/.shortumations/tags.yaml new file mode 100644 index 0000000..e3b090c --- /dev/null +++ b/api/tests/samples/config/.shortumations/tags.yaml @@ -0,0 +1,77 @@ +0: + Type: HA +1: + Type: HA +2: + Type: Button + Room: Living +3: + Type: Button + Room: Kitchen +4: + Type: Button + Room: Kitchen +5: + Type: Button + Room: Kitchen +6: + Type: Button + Room: Kitchen +7: + Type: Button + Room: Living +8: + Type: Button + Room: Baby +9: + Type: Button + Room: Baby +10: + Type: Button + Room: Baby +11: + Type: Routine + Room: Baby +12: + Type: Routine + Room: Baby +13: + Type: Window + Room: Office +14: + Type: Door + Room: Balcony +15: + Type: Routine +16: + Type: Button + Room: Baby +17: + Type: Routine +18: + Type: Routine +19: + Type: Door + Room: Bedroom +20: + Type: Ensure Power +21: + Type: Ensure Power +22: + Type: Motion + Room: Office +23: + Type: Routine + Room: Baby +24: + Type: Climate + Climate: Heat +25: + Type: Climate + Climate: Time +26: + Type: Routine +27: + Type: Button + Room: Bedroom + BadOne: yes diff --git a/api/tests/unittests/api/test_automations.py b/api/tests/unittests/api/test_automations.py index 76b6fce..b924dbf 100644 --- a/api/tests/unittests/api/test_automations.py +++ b/api/tests/unittests/api/test_automations.py @@ -1,3 +1,4 @@ +from ruamel.yaml import YAML from unittest import TestCase from fastapi.testclient import TestClient from src.api.app import make_app @@ -110,6 +111,210 @@ class automation_update_tests(BaseTestCase): self.assertNotEqual(original_auto, new_auto) self.assertEqual(ExtenededAutomationData(metadata=AutomationMetdata(id="testme")).dict(), new_auto) + def test_consistent_standard_1(self): + resp = self.client.post("/automations/list", json={"limit": 1, "offset": 15}) + original_auto = resp.json()["data"][0] + original_auto['metadata']['alias'] = "I CHANGED!" + resp = self.client.post( + "/automations", + json={ + "index": 15, + "data": original_auto, + }, + ) + self.assertEqual(resp.status_code, 200) + with (self.config_folder / "automations.yaml").open('r') as fp: + disk_data = dict(YAML().load(fp)[15]) + trigger = list(map(dict, disk_data.pop('trigger'))) + condition = disk_data.pop('condition') + action = list(map(dict, disk_data.pop('action'))) + self.assertDictEqual(disk_data, { + "id": "1629422438707", + "alias": "I CHANGED!", + "description": "", + "mode": "single" + }) + self.assertListEqual(trigger, [ + {"platform": "time", "at": "input_datetime.vita_night_pump_time"} + ]) + self.assertListEqual(condition, []) + self.assertListEqual(action, [ + { + "conditions": [ + {"condition": "time", "after": "input_datetime.vita_night_pump_time", "before": "00:00:00"}, + {"condition": "time", "after": "00:00:00", "before": "06:00:00"} + ], + "condition": "and" + }, + { + "service": "light.turn_on", + "target": { + "entity_id": "light.bulb_staircase", + "area_id": "living_room" + }, + "data": { + "brightness_pct": 40, + "transition": 15 + } + } + ]) + + def test_consistent_standard_2(self): + resp = self.client.post("/automations/list", json={"limit": 1, "offset": 27}) + original_auto = resp.json()["data"][0] + original_auto['metadata']['alias'] = "I CHANGED!" + resp = self.client.post( + "/automations", + json={ + "index": 27, + "data": original_auto, + }, + ) + self.assertEqual(resp.status_code, 200) + with (self.config_folder / "automations.yaml").open('r') as fp: + disk_data = dict(YAML().load(fp)[27]) + trigger = list(map(dict, disk_data.pop('trigger'))) + condition = disk_data.pop('condition') + action = list(map(dict, disk_data.pop('action'))) + self.assertDictEqual(disk_data, { + "id": "1649947692702", + "alias": "I CHANGED!", + "description": "", + "mode": "single" + }) + self.assertListEqual(trigger, [ + { + "device_id": "das2qdasdasdasadaasd", + "domain": "zha", + "platform": "device", + "type": "remote_button_short_press", + "subtype": "turn_on", + "id": "turn_on" + }, + { + "device_id": "das2qdasdasdasadaasd", + "domain": "zha", + "platform": "device", + "type": "remote_button_short_press", + "subtype": "turn_off", + "id": "turn_off" + }, + { + "device_id": "das2qdasdasdasadaasd", + "domain": "zha", + "platform": "device", + "type": "remote_button_short_press", + "subtype": "dim_up", + "id": "dim_up" + }, + { + "device_id": "das2qdasdasdasadaasd", + "domain": "zha", + "platform": "device", + "type": "remote_button_short_press", + "subtype": "dim_down", + "id": "dim_down" + }, + { + "device_id": "das2qdasdasdasadaasd", + "domain": "zha", + "platform": "device", + "type": "remote_button_double_press", + "subtype": "turn_on", + "id": "up_dbclk" + } + ]) + self.assertListEqual(condition, []) + self.assertListEqual(action, [ + { + "choose": [ + { + "conditions": [ + { + "condition": "trigger", + "id": "turn_off", + } + ], + "sequence": [ + { + "action": "device", + "type": "turn_off", + "device_id": "das2qdasdasdasadaasd", + "entity_id": "light.bulb_ari_lamp", + "domain": "light" + } + ] + }, + { + "conditions": [ + { + "condition": "trigger", + "id": "turn_on", + } + ], + "sequence": [ + { + "action": "service", + "service": "light.turn_on", + "data": {"color_temp": 153, "brightness_pct": 100}, + "target": {"device_id": "das2qdasdasdasadaasd"} + } + ] + }, + { + "conditions": [ + { + "condition": "trigger", + "id": "dim_up", + } + ], + "sequence": [ + { + "action": "device", + "device_id": "das2qdasdasdasadaasd", + "domain": "light", + "entity_id": "light.bulb_ari_lamp", + "type": "brightness_increase" + } + ] + }, + { + "conditions": [ + { + "condition": "trigger", + "id": "dim_down", + } + ], + "sequence": [ + { + "action": "device", + "device_id": "das2qdasdasdasadaasd", + "domain": "light", + "entity_id": "light.bulb_ari_lamp", + "type": "brightness_decrease" + } + ] + }, + { + "conditions": [ + { + "condition": "trigger", + "id": "up_dbclk", + } + ], + "sequence": [ + { + "action": "service", + "service": "light.turn_on", + "data": {"color_temp": 500, "brightness_pct": 100}, + "target": {"device_id": "das2qdasdasdasadaasd"} + } + ] + } + ], + "default": [] + } + ]) class automation_delete_tests(BaseTestCase): def test_delete_some(self): diff --git a/api/tests/unittests/automations/test_parsers.py b/api/tests/unittests/automations/test_parsers.py index a725176..04a9471 100644 --- a/api/tests/unittests/automations/test_parsers.py +++ b/api/tests/unittests/automations/test_parsers.py @@ -21,6 +21,7 @@ class parser_tests(TestCase): {"condition": "time", "after": "10:00:00", "weekday": ["mon", "tue"]}, {"condition": "what is this?", "wuba": "dub"}, SecretValue("supersecretcondition", "rm -rf ./*"), + {"condition": "and", ""} ] expected_process = [ AutomationConditionNode( diff --git a/api/tests/unittests/test_yaml_serializer.py b/api/tests/unittests/test_yaml_serializer.py index a7466de..7ed48ec 100644 --- a/api/tests/unittests/test_yaml_serializer.py +++ b/api/tests/unittests/test_yaml_serializer.py @@ -9,9 +9,10 @@ from src.yaml_serializer.types import ( SecretValue, IncludedYamlDir, ) - +from tests.utils import SAMPLES_FOLDER class dumping_yamls_tests(TestCase): + def test_dumping_includes(self): yaml = dump_yaml( { diff --git a/webapp/src/components/ConditionEditor/style.ts b/webapp/src/components/ConditionEditor/style.ts index 70d99a0..5d028db 100644 --- a/webapp/src/components/ConditionEditor/style.ts +++ b/webapp/src/components/ConditionEditor/style.ts @@ -43,7 +43,6 @@ export const useStyles = createAppUseStyles<{ borderBottomRightRadius: 0, borderBottomLeftRadius: hasChildren ? 0 : 10, padding: 10, - maxWidth: 120, minWidth: 30, textOverflow: 'ellipsis', textAlign: 'center', @@ -58,7 +57,8 @@ export const useStyles = createAppUseStyles<{ }, modifyBtn: ({ hasChildren }) => ({ // styling - backgroundColor: theme.primary, + backgroundColor: theme.green, + color: theme.primary, fill: theme.primaryAccent, borderColor: theme.primaryAccent, borderWidth: 1, @@ -72,13 +72,12 @@ export const useStyles = createAppUseStyles<{ justifyContent: 'center', alignItems: 'center', padding: '0px 10px', - // position: hasChildren ? 'absolute' : 'block', right: 1, top: 10, // on hover "&:hover": { - backgroundColor: theme.primaryLight, + backgroundColor: theme.greenLight, fill: theme.primaryAccentLight, }, "&:hover $icon": { @@ -94,7 +93,7 @@ export const useStyles = createAppUseStyles<{ display: 'flex', flexDirection: 'column', justifyContent: 'center', - border: `1px solid ${theme.primaryAccent}`, + border: `1px solid ${theme.secondaryAccent}`, borderBottomRightRadius: hasChildren ? 10 : 0, borderBottomLeftRadius: hasChildren ? 10 : 0, minHeight: hasChildren ? undefined : '100%' diff --git a/webapp/src/components/DAGFlow/index.tsx b/webapp/src/components/DAGFlow/index.tsx index 67a4795..30ab210 100644 --- a/webapp/src/components/DAGFlow/index.tsx +++ b/webapp/src/components/DAGFlow/index.tsx @@ -59,10 +59,7 @@ export const DAGAutomationFlow: FC = ({ modalBody = setModalState(null)} - onSave={(n) => { - modalState.update(n as any); - setModalState(null); - }} + onSave={(n) => modalState.update(n as any)} allowedTypes={['condition']} /> } diff --git a/webapp/src/components/MultiNodeEditors/index.css b/webapp/src/components/MultiNodeEditors/index.css new file mode 100644 index 0000000..bbca1bc --- /dev/null +++ b/webapp/src/components/MultiNodeEditors/index.css @@ -0,0 +1,15 @@ +.multinode-editor { + max-width: 80vw; +} + +.multinode-editor--navbar { + display: flex; + flex-direction: row; + justify-content: space-evenly; + align-items: center; + min-width: 20vw; +} + +.multinode-editor.modded>.multinode-editor--navbar * { + border-color: var(--green-light); +} \ No newline at end of file diff --git a/webapp/src/components/MultiNodeEditors/index.stories.tsx b/webapp/src/components/MultiNodeEditors/index.stories.tsx index b9b9681..ad2357d 100644 --- a/webapp/src/components/MultiNodeEditors/index.stories.tsx +++ b/webapp/src/components/MultiNodeEditors/index.stories.tsx @@ -30,7 +30,9 @@ export default { export const Simple: ComponentStory = args => { return
- +
+ +
} export const InAModal: ComponentStory = props => { diff --git a/webapp/src/components/MultiNodeEditors/index.tsx b/webapp/src/components/MultiNodeEditors/index.tsx index 5058e97..07626cf 100644 --- a/webapp/src/components/MultiNodeEditors/index.tsx +++ b/webapp/src/components/MultiNodeEditors/index.tsx @@ -1,3 +1,4 @@ +import "./index.css"; import { FC, useState } from 'react'; import { AutomationNode, AutomationNodeMapping } from 'types/automations'; import { NodeEditor } from 'components/NodeEditor'; @@ -39,64 +40,53 @@ export interface MultiNodeEditorProps { export const MultiNodeEditor: FC = ({ sequence: initialState, allowedTypes = ['action', 'condition'], - onClose = () => { }, + onClose: _onClose = () => { }, onSave = () => { }, }) => { // state - const [{ slide, state, isNodeModified, isModified, isReady }, setState] = useState({ + const [{ slide, state, isModified, isReady }, setState] = useState({ slide: 0, state: initialState, isModified: false, - isNodeModified: false, isReady: true, }) // alias - const areYouSureItsModified = () => isNodeModified ? - window.confirm("You've made changes, by pressing this you will lose them!") : - true const areYouSureItsNotReady = () => !isReady ? window.confirm("The node is not ready, are you sure you want to move?") : true + const areYouSureItsModified = () => !isModified ? + window.confirm("If you close this without saving, you will lose all progress!") : + true + const onClose = () => areYouSureItsModified() ? + _onClose() : + null const onAdd = () => setState({ slide: state.length, state: [...state, makeDefault(allowedTypes[0])], - isNodeModified: false, isReady, isModified: true, }); const onRemove = () => setState({ slide: slide > 0 ? slide - 1 : 0, state: [...state.slice(0, slide), ...state.slice(slide + 1)], - isNodeModified: false, isReady, isModified: true, }); - const onNodeSave = (n: AutomationNode) => setState({ - slide, - state: [...state.slice(0, slide), n, ...state.slice(slide + 1)], - isNodeModified: false, - isReady, - isModified: true, - }); - const onSaveAll = () => isNodeModified ? - window.alert("Please save the node data first!") : - onSave(state) + const onAllSave = (n: AutomationNode) => onSave([ + ...state.slice(0, slide), n, ...state.slice(slide + 1) + ]); const onNextOrAdd = () => { - if (!areYouSureItsModified()) { - return - } if (!areYouSureItsNotReady()) { return } if (slide >= state.length - 1) { onAdd() } else { - setState({ slide: slide + 1, state, isNodeModified, isReady, isModified, }) + setState({ slide: slide + 1, state, isReady, isModified, }) } } - const onBack = () => areYouSureItsModified() && - areYouSureItsNotReady() && - setState({ slide: slide - 1, state, isNodeModified, isReady, isModified, }) + const onBack = () => areYouSureItsNotReady() && + setState({ slide: slide - 1, state, isReady, isModified }) // components const nextOrAddBtn = + + } - return <> -
+ return
+
- + {nextOrAddBtn}
= ({ node={state[slide]} allowedTypes={allowedTypes} onClose={onClose} - onSave={onNodeSave} + onSave={onAllSave} onFlags={ - (ir, inm) => ((inm !== isNodeModified) || (ir !== isReady)) && - setState({ slide, state, isNodeModified: inm, isReady: ir, isModified }) + (ir) => (ir !== isReady) && + setState({ slide, state, isReady: ir, isModified }) } - > - - + />
{slide + 1}/{state.length}
- +
} diff --git a/webapp/src/components/NodeEditor/index.css b/webapp/src/components/NodeEditor/index.css index 1772c6c..2fac625 100644 --- a/webapp/src/components/NodeEditor/index.css +++ b/webapp/src/components/NodeEditor/index.css @@ -17,6 +17,10 @@ border-color: var(--change); } +.node-editor--root.not-ready .node-editor--footer--save { + color: var(--error) +} + .node-editor--body-title { display: flex; flex-direction: row; diff --git a/webapp/src/components/NodeEditor/index.tsx b/webapp/src/components/NodeEditor/index.tsx index f043a5a..2d80e72 100644 --- a/webapp/src/components/NodeEditor/index.tsx +++ b/webapp/src/components/NodeEditor/index.tsx @@ -27,15 +27,18 @@ export const NodeEditor: FC = ({ // state const state = useEditorNodeState(node); - // state + // alias const isModified = state.isModified; const isReady = state.isReady(); + const areYouSureNotReady = () => !isReady ? + window.confirm("This node is missing some values, are you sure you want to save?") : + true; // events onFlags(isReady, isModified); // render - return
+ return
{allowedTypes.length > 1 ? = ({ {state.renderOptionList()}
- - + + {children}