This commit is contained in:
britea 2020-05-01 20:28:39 +02:00
commit 3769ea32b0
11 changed files with 638 additions and 663 deletions

View file

@ -0,0 +1,558 @@
import React, { Component, useState } from "react";
import { connect } from "react-redux";
import { RemoteService } from "../../remote";
import update from "immutability-helper";
import "./Automations.css";
import {
Segment,
Grid,
Icon,
Header,
Input,
Button,
Modal,
List,
Divider,
Menu,
Form,
Dropdown,
Checkbox,
} from "semantic-ui-react";
export const operands = [
{ key: "EQUAL", text: "=", value: "EQUAL" },
{
key: "GREATER_EQUAL",
text: "\u2265",
value: "GREATER_EQUAL",
},
{
key: "GREATER",
text: ">",
value: "GREATER",
},
{
key: "LESS_EQUAL",
text: "\u2264",
value: "LESS_EQUAL",
},
{
key: "LESS",
text: "<",
value: "LESS",
},
];
const deviceStateOptions = [
{ key: "off", text: "off", value: false },
{ key: "on", text: "on", value: true },
];
const CreateTrigger = (props) => {
const [activeOperand, setActiveOperand] = useState(true);
const notAdmitedDevices = ["buttonDimmer"];
const hasOperand = new Set([
"knobDimmer",
"dimmableLight",
"curtains",
"sensor",
]);
const deviceList = Object.values(props.devices)
.map((device) => {
return {
key: device.id,
text: device.name,
value: device.id,
kind: device.kind,
};
})
.filter((e) => !notAdmitedDevices.includes(e.kind));
const onChange = (e, val) => {
props.inputChange(val);
setActiveOperand(hasOperand.has(props.devices[val.value].kind));
};
return (
<List.Item>
<List.Content>
<Form>
<Form.Group>
<Form.Field inline width={7}>
<Dropdown
onChange={onChange}
name="device"
search
selection
options={deviceList}
placeholder="Device"
/>
</Form.Field>
{activeOperand ? (
<React.Fragment>
<Form.Field inline width={2}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
name="operand"
compact
selection
options={operands}
/>
</Form.Field>
<Form.Field inline width={7}>
<Input
onChange={(e, val) => props.inputChange(val)}
name="value"
type="number"
placeholder="Value"
/>
</Form.Field>
</React.Fragment>
) : (
<Form.Field inline width={7}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
placeholder="State"
name="on"
compact
selection
options={deviceStateOptions}
/>
</Form.Field>
)}
</Form.Group>
</Form>
</List.Content>
</List.Item>
);
};
const SceneItem = (props) => {
let position = props.order.indexOf(props.scene.id);
return (
<List.Item>
<List.Header>
<Grid textAlign="center">
<Grid.Row>
<Grid.Column width={4}>
<Checkbox
toggle
onChange={(e, val) =>
props.orderScenes(props.scene.id, val.checked)
}
checked={position + 1 > 0}
/>
</Grid.Column>
<Grid.Column width={8}>
<h3>{props.scene.name}</h3>
</Grid.Column>
<Grid.Column width={4}>
<h3>{position !== -1 ? "# " + (position + 1) : ""}</h3>
</Grid.Column>
</Grid.Row>
</Grid>
</List.Header>
</List.Item>
);
};
const Trigger = ({ deviceName, trigger, onRemove, index }) => {
const { operand, value, on } = trigger;
let symbol;
if (operand) {
symbol = operands.filter((opt) => opt.key === operand)[0].text;
}
return (
<List.Item className="trigger-item">
<Menu compact>
<Menu.Item as="span">{deviceName}</Menu.Item>
{operand ? <Menu.Item as="span">{symbol}</Menu.Item> : ""}
<Menu.Item as="span">{operand ? value : on ? "on" : "off"}</Menu.Item>
</Menu>
<Icon
as={"i"}
onClick={() => onRemove(index)}
className="remove-icon"
name="remove"
/>
</List.Item>
);
};
class AutomationSaveModal extends Component {
constructor(props) {
super(props);
this.state = {
triggerList: [],
order: [],
automationName: "New Automation",
editName: false,
newTrigger: {},
scenesFilter: null,
openModal: false,
};
if (this.props.automation) {
this.state.automationName = this.props.automation.name;
for (const scenePriority of this.props.automation.scenes) {
this.state.order[scenePriority.priority] = scenePriority.sceneId;
}
for (const trigger of this.props.automation.triggers) {
this.state.triggerList.push(
Object.assign(
{
device: trigger.deviceId,
kind: trigger.kind,
},
trigger.kind === "booleanTrigger"
? { on: trigger.on }
: { operand: trigger.operator, value: trigger.value }
)
);
}
}
this.setTrigger = this._setter("triggerList");
this.setOrder = this._setter("order");
this.setautomationName = this._setter("automationName");
this.setEditName = this._setter("editName");
this.setNewTrigger = this._setter("newTrigger");
this.addTrigger = this.addTrigger.bind(this);
this.removeTrigger = this.removeTrigger.bind(this);
this.onInputChange = this.onInputChange.bind(this);
this.searchScenes = this.searchScenes.bind(this);
this.orderScenes = this.orderScenes.bind(this);
this.onChangeName = this.onChangeName.bind(this);
}
openModal = (e) => {
this.setState({ openModal: true });
};
closeModal = (e) => {
this.setState({ openModal: false });
};
get deviceList() {
return Object.values(this.props.devices);
}
_setter(property) {
return (value) =>
this.setState(update(this.state, { [property]: { $set: value } }));
}
triggerKind(trigger) {
if ("on" in trigger) {
return "booleanTrigger";
} else if ("operand" in trigger && "value" in trigger) {
return "rangeTrigger";
} else {
throw new Error("Trigger kind not handled");
}
}
_checkNewTrigger(trigger) {
const auxDevice = this.props.devices[trigger.device];
// Check for missing fields for creation
const error = {
result: false,
message: "There are missing fields!",
};
switch (this.triggerKind(trigger)) {
case "booleanTrigger":
if (!trigger.device || trigger.on === null || trigger.on === undefined)
return error;
break;
case "rangeTrigger":
if (!trigger.device || !trigger.operand || !trigger.value) return error;
break;
}
const isNotDuplicate = !this.state.triggerList.some(
(t) => t.device === trigger.device && t.operand === trigger.operand
);
return {
result: isNotDuplicate,
message: isNotDuplicate
? null
: "You have already created a trigger for this device with the same conditions",
};
}
addTrigger() {
const { result, message } = this._checkNewTrigger(this.state.newTrigger);
if (result) {
this.setState(
update(this.state, { triggerList: { $push: [this.state.newTrigger] } })
);
} else {
alert(message);
}
}
removeTrigger(index) {
this.setState(
update(this.state, { triggerList: { $splice: [[index, 1]] } })
);
}
// This gets triggered when the devices dropdown changes the value.
onInputChange(val) {
this.setNewTrigger({ ...this.state.newTrigger, [val.name]: val.value });
}
onChangeName(_, val) {
this.setautomationName(val.value);
}
orderScenes = (id, checked) => {
if (checked) {
this.setState(update(this.state, { order: { $push: [id] } }));
} else {
this.setState(
update(this.state, {
order: (prevList) => prevList.filter((e) => e !== id),
})
);
}
};
searchScenes(_, { value }) {
this.setState(update(this.state, { scenesFilter: { $set: value } }));
this.forceUpdate();
}
get sceneList() {
if (!this.scenesFilter) {
return this.props.scenes;
} else {
return this.props.scenes.filter((e) =>
e.name.includes(this.scenesFilter)
);
}
}
_generateKey = (trigger) => {
switch (this.triggerKind(trigger)) {
case "booleanTrigger":
return "" + trigger.device + trigger.on;
case "rangeTrigger":
return "" + trigger.device + trigger.operand + trigger.value;
}
};
checkBeforeSave = () => {
if (!this.state.automationName) {
alert("Give a name to the automation");
return false;
}
if (this.state.triggerList.length <= 0) {
alert("You have to create a trigger");
return false;
}
if (this.state.order.length <= 0) {
alert("You need at least one active scene");
return false;
}
return true;
};
saveAutomation = () => {
if (this.checkBeforeSave()) {
const automation = {
name: this.state.automationName,
};
if (this.props.id) {
automation.id = this.props.id;
automation.triggers = [];
automation.scenes = [];
for (let i = 0; i < this.state.order.length; i++) {
automation.scenes.push({
priority: i,
sceneId: this.state.order[i],
});
}
for (const trigger of this.state.triggerList) {
const kind = trigger.kind || this.triggerKind(trigger);
automation.triggers.push(
Object.assign(
{
deviceId: trigger.device,
kind,
},
kind
? { on: trigger.on }
: { operator: trigger.operand, value: trigger.value }
)
);
}
console.log(automation);
this.props
.fastUpdateAutomation(automation)
.then(this.closeModal)
.catch(console.error);
} else {
this.props
.saveAutomation({
automation,
triggerList: this.state.triggerList,
order: this.state.order,
})
.then(this.closeModal)
.catch(console.error);
}
}
};
get trigger() {
return this.props.id ? (
<Button
style={{ display: "inline" }}
circular
size="small"
icon="edit"
onClick={this.openModal}
/>
) : (
<Button icon labelPosition="left" color="green" onClick={this.openModal}>
<Icon name="add"></Icon>Create new automation
</Button>
);
}
render() {
return (
<Modal
closeIcon
trigger={this.trigger}
open={this.state.openModal}
onClose={this.closeModal}
>
<Segment basic>
<Header style={{ display: "inline", marginRight: "1rem" }}>
{this.state.editName ? (
<Input
focus
transparent
placeholder="New automation name..."
onChange={this.onChangeName}
/>
) : (
this.state.automationName
)}
</Header>
<Button
onClick={() => this.setEditName((prev) => !prev)}
style={{ display: "inline" }}
circular
size="small"
icon={this.state.editName ? "save" : "edit"}
/>
<Segment placeholder className="segment-automations">
<Grid columns={2} stackable textAlign="center">
<Divider vertical />
<Grid.Row verticalAlign="middle">
<Grid.Column>
<Header>Create Triggers</Header>
<List divided relaxed>
{this.state.triggerList.length > 0 &&
this.state.triggerList.map((trigger, i) => {
const deviceName = this.deviceList.filter(
(d) => d.id === trigger.device
)[0].name;
const key = this._generateKey(trigger);
return (
<Trigger
key={key}
index={i}
deviceName={deviceName}
trigger={trigger}
onRemove={this.removeTrigger}
/>
);
})}
<CreateTrigger
devices={this.props.devices}
inputChange={this.onInputChange}
/>
</List>
<Button
onClick={this.addTrigger}
circular
icon="add"
color="blue"
size="huge"
/>
</Grid.Column>
<Grid.Column>
{this.props.scenes.length > 0 ? (
<React.Fragment>
<Header>Activate Scenes</Header>
<Input
icon="search"
placeholder="Search..."
fluid
onChange={this.searchScenes}
/>
<Divider horizontal />
<List divided relaxed>
{this.sceneList.map((scene) => (
<SceneItem
key={scene.id}
scene={scene}
order={this.state.order}
orderScenes={this.orderScenes}
/>
))}
</List>
</React.Fragment>
) : (
<React.Fragment>
<Header icon>
<Icon name="world" />
</Header>
<Button primary>Create Scene</Button>
</React.Fragment>
)}
</Grid.Column>
</Grid.Row>
</Grid>
</Segment>
<Grid>
<Grid.Row>
<Grid.Column style={{ marginRight: "1rem" }}>
<Button onClick={() => this.saveAutomation()} color="green">
{this.props.id ? "Save" : "Create"}
</Button>
</Grid.Column>
</Grid.Row>
</Grid>
</Segment>
</Modal>
);
}
}
const mapStateToProps = (state, ownProps) => ({
scenes: Object.values(state.scenes),
devices: state.devices,
automation: ownProps.id ? state.automations[ownProps.id] : null,
});
const AutomationSaveModalContainer = connect(
mapStateToProps,
RemoteService
)(AutomationSaveModal);
export default AutomationSaveModalContainer;

View file

@ -6,402 +6,13 @@ import "./Automations.css";
import { import {
Segment, Segment,
Grid, Grid,
Icon,
Header, Header,
Input,
Button, Button,
List, List,
Dropdown,
Form,
Divider, Divider,
Checkbox,
Menu, Menu,
} from "semantic-ui-react"; } from "semantic-ui-react";
import CreateAutomation, { operands } from "./AutomationCreationModal";
const operands = [
{ key: "EQUAL", text: "=", value: "EQUAL" },
{
key: "GREATER_EQUAL",
text: "\u2265",
value: "GREATER_EQUAL",
},
{
key: "GREATER",
text: ">",
value: "GREATER",
},
{
key: "LESS_EQUAL",
text: "\u2264",
value: "LESS_EQUAL",
},
{
key: "LESS",
text: "<",
value: "LESS",
},
];
const deviceStateOptions = [
{ key: "off", text: "off", value: false },
{ key: "on", text: "on", value: true },
];
const CreateTrigger = (props) => {
const [activeOperand, setActiveOperand] = useState(true);
const admitedDevices = ["sensor", "regularLight", "dimmableLight"]; // TODO Complete this list
const deviceList = props.devices
.map((device) => {
return {
key: device.id,
text: device.name,
value: device.id,
kind: device.kind,
};
})
.filter((e) => admitedDevices.includes(e.kind));
const onChange = (e, val) => {
props.inputChange(val);
if (
props.devices.filter((d) => d.id === val.value)[0].hasOwnProperty("on")
) {
setActiveOperand(false);
} else {
setActiveOperand(true);
}
};
return (
<List.Item>
<List.Content>
<Form>
<Form.Group>
<Form.Field inline width={7}>
<Dropdown
onChange={onChange}
name="device"
search
selection
options={deviceList}
placeholder="Device"
/>
</Form.Field>
{activeOperand ? (
<React.Fragment>
<Form.Field inline width={2}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
name="operand"
compact
selection
options={operands}
/>
</Form.Field>
<Form.Field inline width={7}>
<Input
onChange={(e, val) => props.inputChange(val)}
name="value"
type="number"
placeholder="Value"
/>
</Form.Field>
</React.Fragment>
) : (
<Form.Field inline width={7}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
placeholder="State"
name="value"
compact
selection
options={deviceStateOptions}
/>
</Form.Field>
)}
</Form.Group>
</Form>
</List.Content>
</List.Item>
);
};
const SceneItem = (props) => {
let position = props.order.indexOf(props.scene.id);
return (
<List.Item>
<List.Header>
<Grid textAlign="center">
<Grid.Row>
<Grid.Column width={4}>
<Checkbox
toggle
onChange={(e, val) =>
props.orderScenes(props.scene.id, val.checked)
}
checked={position + 1 > 0}
/>
</Grid.Column>
<Grid.Column width={8}>
<h3>{props.scene.name}</h3>
</Grid.Column>
<Grid.Column width={4}>
<h3>{position !== -1 ? "# " + (position + 1) : ""}</h3>
</Grid.Column>
</Grid.Row>
</Grid>
</List.Header>
</List.Item>
);
};
const Trigger = ({ deviceName, trigger, onRemove, index }) => {
const { operand, value } = trigger;
let symbol;
if (operand) {
symbol = operands.filter((opt) => opt.key === operand)[0].text;
}
return (
<List.Item className="trigger-item">
<Menu compact>
<Menu.Item as="span">{deviceName}</Menu.Item>
{operand ? <Menu.Item as="span">{symbol}</Menu.Item> : ""}
<Menu.Item as="span">
{operand ? value : value ? "on" : "off"}
</Menu.Item>
</Menu>
<Icon
as={"i"}
onClick={() => onRemove(index)}
className="remove-icon"
name="remove"
/>
</List.Item>
);
};
export const CreateAutomation = (props) => {
const [triggerList, setTrigger] = useState([]);
const [order, setOrder] = useState([]);
const [stateScenes, setScenes] = useState(props.scenes);
const [automationName, setautomationName] = useState("New Automation");
const [editName, setEditName] = useState(false);
const [newTrigger, setNewTrigger] = useState({});
useEffect(() => {
setScenes(props.scenes);
}, [props]);
const _checkNewTrigger = (trigger) => {
const auxDevice = props.devices.filter((d) => d.id === trigger.device)[0];
if (auxDevice && auxDevice.hasOwnProperty("on")) {
if (!trigger.device || !trigger.value == null) {
return {
result: false,
message: "There are missing fields!",
};
}
} else {
if (!trigger.device || !trigger.operand || !trigger.value) {
return {
result: false,
message: "There are missing fields",
};
}
}
const result = !triggerList.some(
(t) => t.device === trigger.device && t.operand === trigger.operand
);
return {
result: result,
message: result
? ""
: "You have already created a trigger for this device with the same conditions",
};
};
const addTrigger = () => {
const { result, message } = _checkNewTrigger(newTrigger);
const auxTrigger = newTrigger;
if (result) {
if (
props.devices
.filter((d) => d.id === newTrigger.device)[0]
.hasOwnProperty("on")
) {
delete auxTrigger.operand;
}
setTrigger((prevList) => [...prevList, auxTrigger]);
} else {
alert(message);
}
};
const removeTrigger = (index) => {
setTrigger((prevList) => prevList.filter((t, i) => i !== index));
};
// This gets triggered when the devices dropdown changes the value.
const onInputChange = (val) => {
setNewTrigger({ ...newTrigger, [val.name]: val.value });
};
const onChangeName = (e, val) => setautomationName(val.value);
const orderScenes = (id, checked) => {
if (checked) {
setOrder((prevList) => [...prevList, id]);
} else {
setOrder((prevList) => prevList.filter((e) => e !== id));
}
};
const searchScenes = (e, { value }) => {
if (value.length > 0) {
setScenes((prevScenes) => {
return stateScenes.filter((e) => {
return e.name.includes(value);
});
});
} else {
setScenes(props.scenes);
}
};
const _generateKey = (trigger) => {
if (trigger.hasOwnProperty("operand")) {
return trigger.device + trigger.operand + trigger.value;
}
return trigger.device + trigger.value;
};
/*const checkBeforeSave = () => {
if (automationName.length <= 0) {
alert("Give a name to the automation");
return false;
}
if (triggerList.length <= 0) {
alert("You have to create a trigger");
return false;
}
if (order.length <= 0) {
alert("You need at least one active scene");
return false;
}
return true;
};*/
const saveAutomation = () => {
//if(checkBeforeSave()){
const automation = {
name: automationName,
};
props.save({ automation, triggerList, order });
//}
};
return (
<React.Fragment>
<Header style={{ display: "inline", marginRight: "1rem" }}>
{editName ? (
<Input
focus
transparent
placeholder="New automation name..."
onChange={onChangeName}
/>
) : (
automationName
)}
</Header>
<Button
onClick={() => setEditName((prev) => !prev)}
style={{ display: "inline" }}
circular
size="small"
icon={editName ? "save" : "edit"}
/>
<Segment placeholder className="segment-automations">
<Grid columns={2} stackable textAlign="center">
<Divider vertical />
<Grid.Row verticalAlign="middle">
<Grid.Column>
<Header>Create Triggers</Header>
<List divided relaxed>
{triggerList.length > 0 &&
triggerList.map((trigger, i) => {
const deviceName = props.devices.filter(
(d) => d.id === trigger.device
)[0].name;
const key = _generateKey(trigger);
return (
<Trigger
key={key}
index={i}
deviceName={deviceName}
trigger={trigger}
onRemove={removeTrigger}
/>
);
})}
<CreateTrigger
devices={props.devices}
inputChange={onInputChange}
/>
</List>
<Button
onClick={addTrigger}
circular
icon="add"
color="blue"
size="huge"
/>
</Grid.Column>
<Grid.Column>
{props.scenes.length > 0 ? (
<React.Fragment>
<Header>Activate Scenes</Header>
<Input
icon="search"
placeholder="Search..."
fluid
onChange={searchScenes}
/>
<Divider horizontal />
<List divided relaxed>
{stateScenes.map((scene) => (
<SceneItem
key={scene.id}
scene={scene}
order={order}
orderScenes={orderScenes}
/>
))}
</List>
</React.Fragment>
) : (
<React.Fragment>
<Header icon>
<Icon name="world" />
</Header>
<Button primary>Create Scene</Button>
</React.Fragment>
)}
</Grid.Column>
</Grid.Row>
</Grid>
</Segment>
<Grid>
<Grid.Row>
<Grid.Column style={{ marginRight: "1rem" }}>
<Button onClick={() => saveAutomation()} color="green">
SAVE
</Button>
</Grid.Column>
</Grid.Row>
</Grid>
</React.Fragment>
);
};
const Automation = ({ automation, devices, scenes, removeAutomation }) => { const Automation = ({ automation, devices, scenes, removeAutomation }) => {
const { triggers } = automation; const { triggers } = automation;
@ -414,12 +25,7 @@ const Automation = ({ automation, devices, scenes, removeAutomation }) => {
<Header style={{ display: "inline", marginRight: "1rem" }}> <Header style={{ display: "inline", marginRight: "1rem" }}>
{automation.name} {automation.name}
</Header> </Header>
<Button <CreateAutomation id={automation.id} />
style={{ display: "inline" }}
circular
size="small"
icon={"edit"}
/>
<Button <Button
style={{ display: "inline" }} style={{ display: "inline" }}
circular circular
@ -448,7 +54,7 @@ const Automation = ({ automation, devices, scenes, removeAutomation }) => {
? getOperator(trigger.operator) + ? getOperator(trigger.operator) +
" " + " " +
trigger.range trigger.range
: trigger.value : trigger.on
? " - on" ? " - on"
: " - off"} : " - off"}
</Menu.Item> </Menu.Item>
@ -518,11 +124,7 @@ class AutomationsPanel extends Component {
<Grid.Column textAlign="center" width={16}> <Grid.Column textAlign="center" width={16}>
{!this.state.openModal ? ( {!this.state.openModal ? (
<List> <List>
<CreateAutomation <CreateAutomation />
save={this.props.saveAutomation}
scenes={this.props.scenes}
devices={this.props.devices}
/>
</List> </List>
) : ( ) : (
<Button color="green">CREATE AUTOMATION</Button> <Button color="green">CREATE AUTOMATION</Button>
@ -531,7 +133,6 @@ class AutomationsPanel extends Component {
</Grid.Row> </Grid.Row>
<Grid.Row> <Grid.Row>
{this.props.automations.map((automation, i) => { {this.props.automations.map((automation, i) => {
console.log(23, automation, i, this.props.automations);
return ( return (
<Grid.Column key={i} width={8} style={{ margin: "2rem 0" }}> <Grid.Column key={i} width={8} style={{ margin: "2rem 0" }}>
<Automation <Automation

View file

@ -1,7 +1,7 @@
// vim: set ts=2 sw=2 et tw=80: // vim: set ts=2 sw=2 et tw=80:
import React, { Component } from "react"; import React, { Component } from "react";
import { Grid } from "semantic-ui-react"; import { Segment, Card } from "semantic-ui-react";
import Device from "./devices/Device"; import Device from "./devices/Device";
import NewDevice from "./devices/NewDevice"; import NewDevice from "./devices/NewDevice";
import { connect } from "react-redux"; import { connect } from "react-redux";
@ -24,25 +24,18 @@ class DevicePanel extends Component {
render() { render() {
return ( return (
<Grid <Card.Group centered style={{ paddingTop: "3rem" }}>
doubling
columns={3}
divided="vertically"
style={{ paddingTop: "3rem" }}
>
{this.props.devices.map((e, i) => { {this.props.devices.map((e, i) => {
return ( return <Device tab={this.props.tab} id={e.id} />;
<Grid.Column key={i}>
<Device tab={this.props.tab} id={e.id} />
</Grid.Column>
);
})} })}
{!this.props.isActiveRoomHome ? ( {!this.props.isActiveRoomHome ? (
<Grid.Column> <Card style={{ height: "23em" }}>
<NewDevice /> <Segment basic style={{ width: "100%", height: "100%" }}>
</Grid.Column> <NewDevice />
</Segment>
</Card>
) : null} ) : null}
</Grid> </Card.Group>
); );
} }
} }

View file

@ -159,7 +159,7 @@ class Device extends React.Component {
render() { render() {
{ {
return ( return (
<Card> <Card style={{ height: "23em" }}>
<Card.Content> <Card.Content>
<Card.Header textAlign="center"> <Card.Header textAlign="center">
<Header as="h3">{this.deviceName}</Header> <Header as="h3">{this.deviceName}</Header>

View file

@ -341,7 +341,14 @@ class NewDevice extends Component {
open={this.state.openModal} open={this.state.openModal}
onClose={this.resetState} onClose={this.resetState}
trigger={ trigger={
<StyledDiv onClick={this.handleOpen}> <StyledDiv
onClick={this.handleOpen}
style={{
position: "relative",
top: "calc(50% - 5rem)",
left: "calc(50% - 5rem)",
}}
>
<Image src="/img/add.svg" style={{ filter: "invert()" }} /> <Image src="/img/add.svg" style={{ filter: "invert()" }} />
</StyledDiv> </StyledDiv>
} }

View file

@ -315,36 +315,7 @@ export const RemoteService = {
fetchAutomations: () => { fetchAutomations: () => {
return (dispatch) => { return (dispatch) => {
return Endpoint.get("/automation/") return Endpoint.get("/automation/")
.then((res) => { .then((res) => void dispatch(actions.automationsUpdate(res.data)))
const length = res.data.length;
const automations = [];
res.data.forEach((a, index) => {
const { id, name } = a;
const automation = {
name,
id,
triggers: [],
scenes: [],
};
return Endpoint.get(`/booleanTrigger/${id}`).then((res) => {
automation.triggers.push(...res.data);
return Endpoint.get(`/rangeTrigger/${id}`).then((res) => {
automation.triggers.push(...res.data);
return Endpoint.get(`/scenePriority/${id}`).then((res) => {
automation.scenes.push(...res.data);
automations.push(automation);
if (index + 1 === length) {
return void dispatch(
actions.automationsUpdate(automations)
);
}
});
});
});
});
})
.catch((err) => { .catch((err) => {
console.error(`Fetch automations error`, err); console.error(`Fetch automations error`, err);
throw new RemoteError(["Network error"]); throw new RemoteError(["Network error"]);
@ -502,11 +473,22 @@ export const RemoteService = {
}; };
}, },
fastUpdateAutomation: (automation) => {
return (dispatch) => {
return Endpoint.put("/automation/fast", {}, automation)
.then((res) => dispatch(actions.automationSave(res.data)))
.catch((err) => {
console.warn("Update automation: ", automation, "error: ", err);
throw new RemoteError(["Network error"]);
});
};
},
/** /**
* Creates/Updates an automation with the given data. If * Creates/Updates an automation with the given data. If
* data.id is truthy, then a update call is performed, * data.id is truthy, then a update call is performed,
* otherwise a create call is performed. * otherwise a create call is performed.
* @param {Automation} data the device to update. * @param {Automation} data the automation to update.
* @returns {Promise<Device, RemoteError>} promise that resolves to the saved device and rejects * @returns {Promise<Device, RemoteError>} promise that resolves to the saved device and rejects
* with user-fiendly errors as a RemoteError * with user-fiendly errors as a RemoteError
*/ */

View file

@ -257,7 +257,6 @@ function reducer(previousState, action) {
break; break;
case "AUTOMATION_UPDATE": case "AUTOMATION_UPDATE":
newState = previousState;
const automations = {}; const automations = {};
for (const automation of action.automations) { for (const automation of action.automations) {
automations[automation.id] = automation; automations[automation.id] = automation;

View file

@ -1,165 +0,0 @@
import React, { Component } from "react";
import {
Menu,
Button,
Grid,
Icon,
Responsive,
Dropdown,
} from "semantic-ui-react";
import { editButtonStyle } from "../components/dashboard/devices/styleComponents";
import AutomationModal from "../components/AutomationModal";
import { RemoteService } from "../remote";
import { connect } from "react-redux";
import { appActions } from "../storeActions";
class AutomationsNavbar extends Component {
constructor(props) {
super(props);
this.state = {
editMode: false,
};
this.toggleEditMode = this.toggleEditMode.bind(this);
this.openCurrentModalMobile = this.openCurrentModalMobile.bind(this);
}
get activeItemAutomation() {
return this.props.activeAutomation;
}
set activeItemAutomation(item) {
this.props.setActiveAutomation(item);
}
get activeItemAutomationsName() {
if (this.props.activeAutomation === -1) return "Home";
return this.props.automations[this.props.activeAutomation].name;
}
openCurrentModalMobile() {
console.log(this.activeItemAutomation, this.props.automationsModalRefs);
const currentModal = this.props.automationsModalRefs[
this.activeItemAutomation
].current;
currentModal.openModal();
}
toggleEditMode(e) {
this.setState((prevState) => ({ editMode: !prevState.editMode }));
}
render() {
return (
<div style={{ background: "#1b1c1d!important", padding: "0 20px" }}>
<Responsive minWidth={768}>
<Grid>
<Grid.Row color="black">
<button style={editButtonStyle} onClick={this.toggleEditMode}>
Edit
</button>
</Grid.Row>
<Grid.Row>
<Menu inverted fluid vertical>
<Menu.Item
key={-1}
id={null}
name="automations"
active={this.activeItemAutomation === -1}
onClick={this.selectAutomations}
>
<Grid>
<Grid.Row>
<Grid.Column>
<Icon name="home" size="small" />
</Grid.Column>
<Grid.Column>AUTOMATIONS</Grid.Column>
</Grid.Row>
</Grid>
</Menu.Item>
{
//INSERT LIST OF AUTOMATIONS HERE
}
<Menu.Item name="newM">
<Grid>
<Grid.Row centered name="new">
<AutomationModal id={null} />
</Grid.Row>
</Grid>
</Menu.Item>
</Menu>
</Grid.Row>
</Grid>
</Responsive>
<Responsive maxWidth={768}>
<Menu>
<Dropdown item fluid text={this.activeItemAutomationName}>
<Dropdown.Menu>
<Dropdown.Item
key={-1}
id={null}
name="scene"
active={this.activeItemAutomation === -1}
onClick={this.selectAutomations}
>
<Grid>
<Grid.Row>
<Grid.Column>
<Icon name="home" size="small" />
</Grid.Column>
<Grid.Column>Automations</Grid.Column>
</Grid.Row>
</Grid>
</Dropdown.Item>
{
//INSERT LIST OF AUTOMATIONS HERE
}
</Dropdown.Menu>
</Dropdown>
</Menu>
<Grid inverted>
<Grid.Row>
<Grid.Column width={8}>
<AutomationModal id={null} />
</Grid.Column>
{this.activeItemAutomation !== -1 ? (
<Grid.Column width={8}>
<Button
icon
fluid
labelPosition="left"
onClick={this.openCurrentModalMobile}
>
<Icon name="pencil" size="small" />
EDIT AUTOMATION
</Button>
</Grid.Column>
) : null}
</Grid.Row>
</Grid>
</Responsive>
</div>
);
}
}
const setActiveAutomation = (activeAutomation) => {
return (dispatch) =>
dispatch(appActions.setActiveAutomation(activeAutomation));
};
const mapStateToProps = (state, _) => ({
automations: state.automations,
activeAutomation: state.active.activeAutomation,
automationModalRefs: Object.keys(state.automations).reduce(
(acc, key) => ({ ...acc, [key]: React.createRef() }),
{}
),
});
const AutomationsNavbarContainer = connect(mapStateToProps, {
...RemoteService,
setActiveAutomation,
})(AutomationsNavbar);
export default AutomationsNavbarContainer;

View file

@ -4,9 +4,8 @@ import ScenesPanel from "../components/dashboard/ScenesPanel";
import AutomationsPanel from "../components/dashboard/AutomationsPanel"; import AutomationsPanel from "../components/dashboard/AutomationsPanel";
import Navbar from "./Navbar"; import Navbar from "./Navbar";
import ScenesNavbar from "./ScenesNavbar"; import ScenesNavbar from "./ScenesNavbar";
import AutomationsNavbar from "./AutomationsNavbar";
import MyHeader from "../components/HeaderController"; import MyHeader from "../components/HeaderController";
import { Grid, Responsive, Button } from "semantic-ui-react"; import { Grid, Responsive, Button, Menu } from "semantic-ui-react";
import { import {
panelStyle, panelStyle,
mobilePanelStyle, mobilePanelStyle,
@ -67,13 +66,15 @@ class Dashboard extends Component {
return <Navbar />; return <Navbar />;
case "Scenes": case "Scenes":
return <ScenesNavbar />; return <ScenesNavbar />;
case "Automations":
return <AutomationsNavbar />;
default: default:
return <h1>ERROR</h1>; return <h1>ERROR</h1>;
} }
} }
get hasNavbar() {
return this.state.activeTab !== "Automations";
}
render() { render() {
return ( return (
<div style={{ background: "#1b1c1d" }}> <div style={{ background: "#1b1c1d" }}>
@ -85,40 +86,37 @@ class Dashboard extends Component {
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
<Grid.Row color="black"> <Grid.Row color="black">
<Grid.Column width={3}></Grid.Column> <Grid.Column textAlign="center" width={16}>
<Grid.Column textAlign="center" width={13}> <Menu fluid widths={3} inverted color="grey">
<Button <Menu.Item
basic basic
name="Devices" name="Devices"
content="Devices" content="Devices"
active={this.activeTab === "Devices"} active={this.activeTab === "Devices"}
color={this.activeTab === "Devices" ? "yellow" : "grey"} onClick={this.selectTab}
onClick={this.selectTab} />
/> <Menu.Item
<Button basic
basic name="Scenes"
name="Scenes" content="Scenes"
content="Scenes" active={this.activeTab === "Scenes"}
active={this.activeTab === "Scenes"} onClick={this.selectTab}
color={this.activeTab === "Scenes" ? "yellow" : "grey"} />
onClick={this.selectTab} <Menu.Item
/> name="Automations"
<Button content="Automations"
basic active={this.activeTab === "Automations"}
name="Automations" onClick={this.selectTab}
content="Automations" />
active={this.activeTab === "Automations"} </Menu>
color={this.activeTab === "Automations" ? "yellow" : "grey"}
onClick={this.selectTab}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row color="black">
<Grid.Column width={3}>
{this.renderNavbar(this.activeTab)}
</Grid.Column> </Grid.Column>
<Grid.Column width={13}> {this.hasNavbar && (
<Grid.Column width={3}>
{this.renderNavbar(this.activeTab)}
</Grid.Column>
)}
<Grid.Column width={this.hasNavbar ? 13 : 16}>
<div style={panelStyle}>{this.renderTab(this.activeTab)}</div> <div style={panelStyle}>{this.renderTab(this.activeTab)}</div>
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
@ -159,11 +157,13 @@ class Dashboard extends Component {
/> />
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
<Grid.Row color="black"> {this.hasNavbar && (
<Grid.Column color="black"> <Grid.Row color="black">
{this.renderNavbar(this.activeTab)} <Grid.Column color="black">
</Grid.Column> {this.renderNavbar(this.activeTab)}
</Grid.Row> </Grid.Column>
</Grid.Row>
)}
<Grid.Row> <Grid.Row>
<Grid.Column> <Grid.Column>
<div style={mobilePanelStyle}> <div style={mobilePanelStyle}>

View file

@ -60,9 +60,9 @@ class Navbar extends Component {
render() { render() {
return ( return (
<div style={{ background: "#1b1c1d!important", padding: "0 20px" }}> <div>
<Responsive minWidth={768}> <Responsive minWidth={768}>
<Grid> <Grid style={{ margin: "1em -1em 0 1em" }}>
<Grid.Row color="black"> <Grid.Row color="black">
<button style={editButtonStyle} onClick={this.toggleEditMode}> <button style={editButtonStyle} onClick={this.toggleEditMode}>
Edit Edit

View file

@ -69,9 +69,9 @@ class ScenesNavbar extends Component {
render() { render() {
return ( return (
<div style={{ background: "#1b1c1d!important", padding: "0 20px" }}> <div>
<Responsive minWidth={768}> <Responsive minWidth={768}>
<Grid> <Grid style={{ margin: "1em -1em 0 1em" }}>
<Grid.Row color="black"> <Grid.Row color="black">
<button style={editButtonStyle} onClick={this.toggleEditMode}> <button style={editButtonStyle} onClick={this.toggleEditMode}>
Edit Edit