cleaned up multinode stlying

This commit is contained in:
ari committed 2022-05-13 17:26:44 -04:00
1 parent 8d804add13
commit bfc95db6f6
14 files changed
+402 -69

No files matched your search

+49
View File
@@ -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
+1 -1
View File
@@ -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],
+4 -2
View File
@@ -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"))
@@ -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
+205
View File
@@ -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):
@@ -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(
+2 -1
View File
@@ -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(
{
@@ -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%'
+1 -4
View File
@@ -59,10 +59,7 @@ export const DAGAutomationFlow: FC<Props> = ({
modalBody = <MultiNodeEditor
sequence={modalState.node}
onClose={() => setModalState(null)}
onSave={(n) => {
modalState.update(n as any);
setModalState(null);
}}
onSave={(n) => modalState.update(n as any)}
allowedTypes={['condition']}
/>
}
@@ -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);
}
@@ -30,7 +30,9 @@ export default {
export const Simple: ComponentStory<typeof MultiNodeEditor> = args => {
return <div className="page">
<MultiNodeEditor {...args} />
<div className="center column" style={{ paddingTop: "1em" }}>
<MultiNodeEditor {...args} />
</div>
</div>
}
export const InAModal: ComponentStory<typeof MultiNodeEditor> = props => {
@@ -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<MultiNodeEditorProps> = ({
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 = <Button
onClick={onNextOrAdd}
@@ -117,24 +107,15 @@ export const MultiNodeEditor: FC<MultiNodeEditorProps> = ({
{nextOrAddBtn}
</div>
<div className='column center' style={{ marginTop: '1em' }}>
<Button onClick={() => areYouSureItsModified() && onClose()}>Close</Button>
<Button onClick={onClose}>Close</Button>
<Button onClick={() => onSave(state)}>Save</Button>
</div>
</div>
}
return <>
<div style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
minWidth: '20vw',
}}>
return <div className={["multinode-editor", isModified ? "modded" : ''].join(' ')}>
<div className="multinode-editor--navbar">
<Button onClick={onBack} disabled={slide === 0}>{"<<"}</Button>
<Button
onClick={onRemove}
>
Delete
</Button>
<Button onClick={onRemove}> Delete</Button>
{nextOrAddBtn}
</div>
<NodeEditor
@@ -142,19 +123,14 @@ export const MultiNodeEditor: FC<MultiNodeEditorProps> = ({
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 })
}
>
<Button onClick={onSaveAll} style={{
borderColor: isModified ? "var(--change)" : undefined,
color: isModified ? "var(--change)" : undefined,
}}>Save All</Button>
</NodeEditor>
/>
<div className='column center'>
<span>{slide + 1}/{state.length}</span>
</div>
</>
</div>
}
@@ -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;
+11 -6
View File
@@ -27,15 +27,18 @@ export const NodeEditor: FC<Props> = ({
// 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 <div className={["node-editor--root", isModified ? "modded" : ""].join(" ")}>
return <div className={["node-editor--root", isModified ? "modded" : "", !isReady ? 'not-ready' : ''].join(" ")}>
<div className="node-editor--body">
<div className="node-editor--body-title">
{allowedTypes.length > 1 ? <InputList
@@ -54,10 +57,12 @@ export const NodeEditor: FC<Props> = ({
{state.renderOptionList()}
</div>
<div className="node-editor--footer">
<Button onClick={onClose}>Close</Button>
<Button onClick={() => {
isReady && onSave(state.data)
}} disabled={!isReady}>{saveBtnCreateText ? "Create" : "Save"}</Button>
<Button className="node-editor--footer--close" onClick={onClose}>Close</Button>
<Button className="node-editor--footer--save" onClick={() => {
areYouSureNotReady() && onSave(state.data)
}} title={!isReady ? "Some fields have not been properly filled up" : ""}>
{saveBtnCreateText ? "Create" : "Save"}
</Button>
{children}
</div>
</div>