Compare commits

..
25 Commits
Author SHA1 Message Date
ari 6b21734041 added scene support 2022-08-06 22:43:56 -04:00
ari 754cc2ef98 added more support for trigger types 2022-08-06 22:37:26 -04:00
ari 1cb40288b1 remove state for zone 2022-08-06 20:41:02 -04:00
ari 129ba28ff5 v0.5.3 2022-08-06 20:28:09 -04:00
Ari Sosnovsky 44e246f79b Update README.md 2022-08-06 20:22:34 -04:00
ari 8bcbcaa801 added a redirect 2022-08-06 20:03:10 -04:00
ari b479476833 fixed up invalid node issue 2022-08-06 15:29:41 -04:00
Przemysław Adam Sowa baa31ab649 Don't use network host mode in the example docker-compose.yaml (#128) 2022-08-06 14:20:27 -04:00
Ari Sosnovsky dc7c6273e4 Update README.md 2022-08-06 13:16:34 -04:00
Ari Sosnovsky 2942b6173b Update README.md 2022-08-05 23:41:46 -04:00
ari bcfc648011 controls 2022-08-05 23:35:47 -04:00
ari 084d86ad7a fixed up build 2022-08-05 23:12:48 -04:00
ari ea6be4a8f3 infinte undo 2022-08-05 23:08:00 -04:00
ari 14649ac1fd added dial 2022-08-05 22:54:17 -04:00
ari f1b99cad1c trigger automation in metadata 2022-08-05 22:22:28 -04:00
ari ab7f50d4aa fixed trigger device validation 2022-08-05 22:04:31 -04:00
ari d22bba8c4d moving things around 2022-08-05 22:04:31 -04:00
ari 549f52655b refactor inputs 2022-08-05 22:04:31 -04:00
renovate[bot] 2c5d64ab86 Update dependency jss to v10.9.2 (#119)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-02 15:09:24 -04:00
renovate[bot] 7c50c345ec Update dependency react-jss to v10.9.2 (#120)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-02 15:09:13 -04:00
ari f4261f9701 better tag edit viz 2022-08-02 12:51:22 -04:00
ari 34826acb97 v0.5.1 2022-07-31 23:34:11 -04:00
ari cd1b4e8e2b ensuring scroll 2022-07-31 22:22:21 -04:00
ari 2b4c64c94b added ignore 2022-07-29 21:43:27 -04:00
ari 067f5fa642 added delay to save 2022-07-29 21:42:50 -04:00
117 changed files with 1433 additions and 991 deletions

No files matched your search

+25
View File
@@ -1,5 +1,30 @@
# 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.5.3] - Bug Fixes
- Redirecting `/` to `/web` to resolve container install strangeness reported in https://github.com/asosnovsky/Shortumation/issues/125
- Fixed missing flag that caused the automation to explode in https://github.com/asosnovsky/Shortumation/issues/124
## [0.5.2] - Better Controls
- Add automation trigger
- Speed dial on the bottom
<img src="https://user-images.githubusercontent.com/7451445/183231968-9891bbb4-5c7c-4e05-b804-36978c809a5c.png" width="200px"/>
- Infinite undos <img src="https://user-images.githubusercontent.com/7451445/183231977-ed000017-2886-4a57-b5fb-c7e527bf3894.png" width="200px"/>
## [0.5.1] - Sidebar!
- completely redesigned the sidebar!
- Disable/enable automatons
- See 'bad state' automatons
- Delete automatons from registry (in cases where references are stale)
- Refactored sidebar UX to match MUI standards
- Cleaned up editing tags in sidebar
<img src="https://user-images.githubusercontent.com/7451445/182066721-07a93651-2f83-44d5-8420-15093caa52df.png" width="400px"/>
- Websockets now live-refresh when updates occur
## [0.4.0] - Depedency update ## [0.4.0] - Depedency update
- Core dependency updates - Core dependency updates
+8 -4
View File
@@ -1,4 +1,4 @@
# Shortumation ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=platsic) # <img src="logo.png" height="40x"/> Shortumation ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=platsic)
[![Test](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml) [![Build](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml) [![Test](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/test.yml) [![Build](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml/badge.svg)](https://github.com/asosnovsky/Shortumation/actions/workflows/build.yml)
@@ -6,7 +6,9 @@
| ------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | ------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| Version | ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge) | ![Docker Image Version (latest semver)](https://img.shields.io/docker/v/asosnovsky/shortumation-amd64?&sort=date&label=&style=for-the-badge) | | Version | ![GitHub release (latest by date)](https://img.shields.io/github/v/release/asosnovsky/Shortumation?label=&style=for-the-badge) | ![Docker Image Version (latest semver)](https://img.shields.io/docker/v/asosnovsky/shortumation-amd64?&sort=date&label=&style=for-the-badge) |
A [home-assistant addon](https://www.home-assistant.io/addons/) for a better UI for managing and writing your automations. We provide a way to visualize your automation using a visual-programming language that draws inspirations from [Node-Red](https://nodered.org/). A [home-assistant addon](https://www.home-assistant.io/addons/) for a better UI for managing and writing your automations. We provide a way to visualize your automation using a visual-programming language that draws inspirations from [Node-Red](https://nodered.org/).
<img src="./assets/comparisons.png">
## Features ## Features
@@ -46,12 +48,14 @@ Add the repository URL under **Supervisor → Add-on store → ⋮ → Manage ad
It should now appear in your `Add-on Store` and you should be able to install it! It should now appear in your `Add-on Store` and you should be able to install it!
**Please note that you may need to enable advance mode in your settings first!**
### Containerized or HA Core ### Containerized or HA Core
Please note that this way of using Shortumation is **not future proof**.
If this warning does not scare you or you still want to try things out, then take a look at the example [docker-compose.yaml](example/containerized/docker-compose.yaml), or read the [extended guide here](https://github.com/asosnovsky/Shortumation/wiki/Installation#containerized--ha-core). If this warning does not scare you or you still want to try things out, then take a look at the example [docker-compose.yaml](example/containerized/docker-compose.yaml), or read the [extended guide here](https://github.com/asosnovsky/Shortumation/wiki/Installation#containerized--ha-core).
In general, if you want to help provide this to more home-assistant fans please join on the conversation here https://github.com/asosnovsky/Shortumation/issues/102 or help contribute :)
## FAQ ## FAQ
**How is this different from Node-Red?** **How is this different from Node-Red?**
+11 -1
View File
@@ -1,6 +1,7 @@
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
from src.automations.manager import AutomationManager from src.automations.manager import AutomationManager
from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER from src.env import API_PREFIX, ORIGIN, ROOT_FOLDER
@@ -10,7 +11,8 @@ from .routes import automations, details, ping, socket
def make_app(automation_mgr: AutomationManager) -> FastAPI: def make_app(automation_mgr: AutomationManager) -> FastAPI:
app = FastAPI() app = FastAPI()
if (ROOT_FOLDER / "web").exists(): has_web_folder = (ROOT_FOLDER / "web").exists()
if has_web_folder:
app.mount( app.mount(
f"{API_PREFIX}/web", f"{API_PREFIX}/web",
StaticFiles( StaticFiles(
@@ -19,6 +21,7 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
), ),
name="web", name="web",
) )
else: else:
print("WARN: could not find web folder") print("WARN: could not find web folder")
app.add_middleware( app.add_middleware(
@@ -36,4 +39,11 @@ def make_app(automation_mgr: AutomationManager) -> FastAPI:
details.make_details_router(automation_mgr.hass_config), prefix=f"{API_PREFIX}/details" details.make_details_router(automation_mgr.hass_config), prefix=f"{API_PREFIX}/details"
) )
app.include_router(socket.router, prefix=f"{API_PREFIX}/socket") app.include_router(socket.router, prefix=f"{API_PREFIX}/socket")
@app.get("/")
def get_index():
if has_web_folder:
return RedirectResponse("/web")
return RedirectResponse("/details")
return app return app
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

+1 -1
View File
@@ -1,5 +1,5 @@
name: Shortumation name: Shortumation
version: v0.4.0 version: v0.5.3
slug: shortumation slug: shortumation
image: asosnovsky/shortumation-{arch} image: asosnovsky/shortumation-{arch}
url: "https://github.com/asosnovsky/Shortumation" url: "https://github.com/asosnovsky/Shortumation"
+5 -2
View File
@@ -12,9 +12,12 @@ services:
shortumation: shortumation:
# make sure to replace the ARCH with whatever system you are running! # make sure to replace the ARCH with whatever system you are running!
image: "asosnovsky/shortumation-${ARCH:-amd64}:${SHORTUMATION_VERSION:-latest}" image: "asosnovsky/shortumation-${ARCH:-amd64}:${SHORTUMATION_VERSION:-latest}"
network_mode: host ports:
- 8000:8000
extra_hosts:
- "host.docker.internal:host-gateway"
volumes: volumes:
- ./config:/config - ./config:/config
environment: environment:
- SUPERVISOR_TOKEN=${SUPERVISOR_TOKEN} - SUPERVISOR_TOKEN=${SUPERVISOR_TOKEN}
- HASSIO_WS=ws://0.0.0.0:8123/api/websocket - HASSIO_WS=ws://host.docker.internal:8123/api/websocket
+6 -2
View File
@@ -2,13 +2,17 @@
"version": "2.0.0", "version": "2.0.0",
"tasks": [ "tasks": [
{ {
"icon": {
"id": "server-environment"
},
"type": "shell", "type": "shell",
"label": "Docker: Server", "label": "Docker: Start Server",
"group": "none", "group": "none",
"command": [".vscode/bin/start-docker-server.sh"], "command": [".vscode/bin/start-docker-server.sh"],
"runOptions": { "runOptions": {
"runOn": "folderOpen" "runOn": "folderOpen"
} },
"problemMatcher": []
}, },
{ {
"type": "npm", "type": "npm",
+2 -2
View File
@@ -17,7 +17,7 @@
"@uiw/react-codemirror": "4.10.4", "@uiw/react-codemirror": "4.10.4",
"autosuggest-highlight": "3.3.4", "autosuggest-highlight": "3.3.4",
"home-assistant-js-websocket": "7.1.0", "home-assistant-js-websocket": "7.1.0",
"jss": "10.9.1", "jss": "10.9.2",
"material-ui-confirm": "3.0.4", "material-ui-confirm": "3.0.4",
"notistack": "2.0.5", "notistack": "2.0.5",
"react": "18.2.0", "react": "18.2.0",
@@ -25,7 +25,7 @@
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-flow-renderer": "10.3.12", "react-flow-renderer": "10.3.12",
"react-imask": "6.4.2", "react-imask": "6.4.2",
"react-jss": "10.9.1", "react-jss": "10.9.2",
"react-router-dom": "6.3.0", "react-router-dom": "6.3.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"superstruct": "0.16.0", "superstruct": "0.16.0",
@@ -1,7 +1,7 @@
import "./AutoInfoBox.css"; import "./AutoInfoBox.css";
import { AutomationMetadata } from "types/automations"; import { AutomationMetadata } from "types/automations";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import { FC, ReactNode, useRef, useState } from "react"; import { FC, ReactNode, useRef, useState } from "react";
import { AddIcon, TrashIcon } from "components/Icons"; import { AddIcon, TrashIcon } from "components/Icons";
import InputAutoText from "components/Inputs/InputAutoText"; import InputAutoText from "components/Inputs/InputAutoText";
@@ -3,19 +3,23 @@ import "./index.mobile.css";
import { FC, useState } from "react"; import { FC, useState } from "react";
import { useCookies } from "react-cookie"; import { useCookies } from "react-cookie";
import { ControlButton } from "react-flow-renderer";
import Skeleton from "@mui/material/Skeleton"; import Skeleton from "@mui/material/Skeleton";
import LinearProgress from "@mui/material/LinearProgress"; import LinearProgress from "@mui/material/LinearProgress";
import SpeedDial from "@mui/material/SpeedDial";
import SpeedDialAction from "@mui/material/SpeedDialAction";
import Edit from "@mui/icons-material/Edit"; import SpeedDialIcon from "@mui/icons-material/SettingsRounded";
import UndoIcon from "@mui/icons-material/UndoSharp";
import Icon from "@mui/material/Icon"; import Icon from "@mui/material/Icon";
import ModeEditOutlineTwoToneIcon from "@mui/icons-material/ModeEditOutlineTwoTone"; import EditIcon from "@mui/icons-material/ModeEditOutlineTwoTone";
import DeleteIcon from "@mui/icons-material/DeleteForever";
import { CheckMarkIcon } from "components/Icons"; import { CheckMarkIcon } from "components/Icons";
import RunIcon from "@mui/icons-material/RunCircleOutlined";
import { Modal } from "components/Modal"; import { Modal } from "components/Modal";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Buttons/Button";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { TagDB } from "components/AutomationManager/TagDB"; import { TagDB } from "components/AutomationManager/TagDB";
import { DAGDims } from "components/DAGGraph/elements/types"; import { DAGDims } from "components/DAGGraph/elements/types";
import { DAGAutomationGraph } from "components/DAGGraph"; import { DAGAutomationGraph } from "components/DAGGraph";
@@ -32,6 +36,8 @@ interface Props {
automation?: AutomationData; automation?: AutomationData;
dims: DAGDims; dims: DAGDims;
onUpdate: (auto: AutomationData) => void; onUpdate: (auto: AutomationData) => void;
onTrigger: () => void;
onDelete: () => void;
tagDB: TagDB; tagDB: TagDB;
isNew?: boolean; isNew?: boolean;
} }
@@ -39,6 +45,8 @@ export const AutomationEditor: FC<Props> = ({
dims, dims,
automation: propsAutos, automation: propsAutos,
onUpdate: propsOnUpdate, onUpdate: propsOnUpdate,
onDelete,
onTrigger,
tagDB, tagDB,
isNew, isNew,
}) => { }) => {
@@ -52,6 +60,7 @@ export const AutomationEditor: FC<Props> = ({
validate, validate,
save, save,
saveAndUpdate, saveAndUpdate,
undo,
} = useAutomatioEditorState(propsAutos, propsOnUpdate); } = useAutomatioEditorState(propsAutos, propsOnUpdate);
const [infoBoxOpen, setInfoBox] = useState(false); const [infoBoxOpen, setInfoBox] = useState(false);
const [ const [
@@ -198,12 +207,11 @@ export const AutomationEditor: FC<Props> = ({
Flip Flip
</Button> </Button>
)} )}
<Button {state.status === "changed" && (
className={"automation-editor--flow-wrapper--toolbar--edit-btn"} <Button onClick={undo}>
onClick={() => setInfoBox(!infoBoxOpen)} <UndoIcon />
> </Button>
Metadata <Edit /> )}
</Button>
<Button <Button
className={"automation-editor--flow-wrapper--toolbar--save-btn"} className={"automation-editor--flow-wrapper--toolbar--save-btn"}
onClick={save} onClick={save}
@@ -220,12 +228,39 @@ export const AutomationEditor: FC<Props> = ({
onTriggerUpdate={updateTrigger} onTriggerUpdate={updateTrigger}
onConditionUpdate={updateCondition} onConditionUpdate={updateCondition}
isFlipped={flipped} isFlipped={flipped}
additionalControls={
<ControlButton onClick={() => setInfoBox(!infoBoxOpen)}>
<ModeEditOutlineTwoToneIcon />
</ControlButton>
}
/> />
<SpeedDial
ariaLabel="options label"
sx={{ position: "absolute", bottom: 16, right: 16 }}
icon={<SpeedDialIcon />}
>
<SpeedDialAction
tooltipOpen
icon={<RunIcon />}
tooltipTitle={"Trigger"}
onClick={onTrigger}
/>
<SpeedDialAction
tooltipOpen
icon={<DeleteIcon />}
tooltipTitle={"Delete"}
onClick={onDelete}
/>
<SpeedDialAction
tooltipOpen
icon={<EditIcon />}
tooltipTitle={"Metadata"}
onClick={() => setInfoBox(!infoBoxOpen)}
/>
{state.status === "changed" && (
<SpeedDialAction
tooltipOpen
icon={<UndoIcon />}
tooltipTitle={"Undo"}
onClick={undo}
/>
)}
</SpeedDial>
</div> </div>
</div> </div>
); );
+138 -99
View File
@@ -1,117 +1,156 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from "react";
import { AutomationData, AutomationMetadata } from "types/automations"; import { AutomationData, AutomationMetadata } from "types/automations";
import * as v from "types/validators/autmation"; import * as v from "types/validators/autmation";
import { getFailures } from "types/validators/helper"; import { getFailures } from "types/validators/helper";
import { MiniFailure } from '../../types/validators/helper'; import { MiniFailure } from "../../types/validators/helper";
export type EditorData = ReturnType<typeof genEditorData>; export type EditorData = ReturnType<typeof genEditorData>;
export type EditorState = { export type EditorState =
status: 'unchanged' | 'changed' | 'saving', | {
data: EditorData status: "unchanged";
} | { data: EditorData;
status: 'loading' }
} | { | {
status: 'invalid', status: "changed" | "saving";
failures: MiniFailure[], previous: EditorData[];
data: EditorData, data: EditorData;
} }
export type EditorStatus = EditorState['status']; | {
status: "loading";
}
| {
status: "invalid";
failures: MiniFailure[];
data: EditorData;
};
export type EditorStatus = EditorState["status"];
export const useAutomatioEditorState = ( export const useAutomatioEditorState = (
automation: AutomationData | undefined, automation: AutomationData | undefined,
onSave: (a: AutomationData) => void, onSave: (a: AutomationData) => void
) => { ) => {
const [state, update] = useState<EditorState>({ const [state, update] = useState<EditorState>({
status: "loading", status: "loading",
}); });
const makeUpdate = <K extends keyof EditorData, D extends EditorData[K]>(name: K) => ( const makeUpdate =
data: D <K extends keyof EditorData, D extends EditorData[K]>(name: K) =>
) => ((state.status === 'changed') || (state.status === 'unchanged')) && update({ (data: D) =>
status: 'changed', (state.status === "changed" || state.status === "unchanged") &&
update({
status: "changed",
previous:
state.status === "unchanged"
? [state.data]
: state.previous.concat([state.data]),
data: { data: {
...state.data, ...state.data,
[name]: data, [name]: data,
} },
}) });
const saveAndUpdate = (data: EditorData) => { const saveAndUpdate = (data: EditorData) => {
const cleanData = { if (state.status === "changed") {
...data, const cleanData = {
tags: data.tags.reduce((all, [tagName, tagValue]) => ({ ...data,
...all, tags: data.tags.reduce(
[tagName.trim()]: tagValue.trim(), (all, [tagName, tagValue]) => ({
}), {}) ...all,
}; [tagName.trim()]: tagValue.trim(),
}),
{}
),
};
update({
status: "saving",
previous: state.previous,
data,
});
onSave(cleanData);
}
};
useEffect(() => {
if (automation) {
const failures = getFailures(automation, v.AutomationData);
if (failures) {
update({ update({
status: "saving", status: "invalid",
data, failures,
}) data: genEditorData(automation),
onSave(cleanData); });
} else {
update({
status: "unchanged",
data: genEditorData(automation),
});
}
} }
}, [automation]);
useEffect(() => { return {
if (automation) { validate: (data: any) => getFailures(data, v.AutomationData),
const failures = getFailures(automation, v.AutomationData); updateTrigger: makeUpdate("trigger"),
if (failures) { updateSequence: makeUpdate("sequence"),
update({ updateCondition: makeUpdate("condition"),
status: 'invalid', saveAndUpdate,
failures, updateMetadata: (
data: genEditorData(automation), metadata: AutomationMetadata,
}) tags: Array<[string, string]>
} else { ) => {
update({ if (state.status === "changed" || state.status === "unchanged") {
status: 'unchanged', update({
data: genEditorData(automation), status: "changed",
}) previous:
} state.status === "changed"
? state.previous.concat([state.data])
: [state.data],
data: {
...state.data,
tags,
metadata,
},
});
}
},
save: () => {
if (state.status !== "loading") {
saveAndUpdate(state.data);
}
},
undo: () => {
if (state.status === "changed") {
if (state.previous.length === 1) {
update({
status: "unchanged",
data: state.previous[0],
});
} else {
update({
status: "changed",
data: state.previous[state.previous.length - 1],
previous: state.previous.slice(0, state.previous.length - 1),
});
} }
}, [automation]); }
},
return { get state() {
validate: (data: any) => getFailures(data, v.AutomationData), return state;
updateTrigger: makeUpdate('trigger'), },
updateSequence: makeUpdate('sequence'), };
updateCondition: makeUpdate('condition'), };
saveAndUpdate,
updateMetadata: (metadata: AutomationMetadata, tags: Array<[string, string]>) => {
if ((state.status === 'changed') || (state.status === 'unchanged')) {
update({
status: 'changed',
data: {
...state.data,
tags,
metadata,
}
})
}
},
save: () => {
if (state.status !== 'loading') {
saveAndUpdate(state.data)
}
},
get state() {
return state;
}
}
}
const genEditorData = (automation: AutomationData) => { const genEditorData = (automation: AutomationData) => {
const { const { metadata, trigger, sequence, condition } = automation;
metadata,
trigger,
sequence,
condition,
} = automation;
const tags: [string, string][] = Object.keys(automation.tags).map(tagName => [tagName, automation.tags[tagName]]); const tags: [string, string][] = Object.keys(automation.tags).map(
(tagName) => [tagName, automation.tags[tagName]]
);
return { return {
metadata, metadata,
trigger, trigger,
sequence, sequence,
condition, condition,
tags, tags,
} };
} };
@@ -13,6 +13,10 @@
user-select: none; user-select: none;
} }
.automation-manager--list-box-group.modified {
border: 1px var(--mui-success-main) solid;
}
.automation-manager--list-box-group { .automation-manager--list-box-group {
border-color: var(--mui-text-secondary); border-color: var(--mui-text-secondary);
border-width: 0.125px; border-width: 0.125px;
@@ -14,7 +14,10 @@ const { make, componentMeta } = makeStory({
args: { args: {
title: "Example", title: "Example",
type: "items", type: "items",
isSelected: false, flags: {
isSelected: false,
isModified: false,
},
data: [ data: [
{ {
id: "1", id: "1",
@@ -23,7 +26,10 @@ const { make, componentMeta } = makeStory({
description: "Amazing automation!", description: "Amazing automation!",
tags: {}, tags: {},
state: "on", state: "on",
isSelected: false, flags: {
isSelected: false,
isModified: false,
},
}, },
{ {
id: "2", id: "2",
@@ -31,7 +37,10 @@ const { make, componentMeta } = makeStory({
entityId: "automation.2", entityId: "automation.2",
description: "Cool!", description: "Cool!",
state: "on", state: "on",
isSelected: false, flags: {
isSelected: false,
isModified: false,
},
tags: { tags: {
room: "main bedroom", room: "main bedroom",
routine: "night time", routine: "night time",
@@ -48,16 +57,25 @@ export const Basic = make({});
export const Nested = make({ export const Nested = make({
title: "Top Group", title: "Top Group",
type: "group", type: "group",
isSelected: false, flags: {
isSelected: false,
isModified: false,
},
data: [ data: [
{ {
title: "Subgroup 1", title: "Subgroup 1",
type: "group", type: "group",
isSelected: true, flags: {
isSelected: true,
isModified: false,
},
data: [ data: [
{ {
type: "items", type: "items",
isSelected: true, flags: {
isSelected: true,
isModified: false,
},
title: "Subsub group", title: "Subsub group",
data: [ data: [
{ {
@@ -66,7 +84,10 @@ export const Nested = make({
description: "", description: "",
title: "Automation #1", title: "Automation #1",
state: "on", state: "on",
isSelected: true, flags: {
isSelected: true,
isModified: false,
},
tags: {}, tags: {},
}, },
{ {
@@ -75,7 +96,10 @@ export const Nested = make({
description: "another one", description: "another one",
title: "Automation #2", title: "Automation #2",
state: "off", state: "off",
isSelected: false, flags: {
isSelected: false,
isModified: false,
},
tags: {}, tags: {},
}, },
{ {
@@ -84,7 +108,10 @@ export const Nested = make({
description: "bad one", description: "bad one",
title: "Automation #3", title: "Automation #3",
state: "offing", state: "offing",
isSelected: false, flags: {
isSelected: false,
isModified: false,
},
tags: { tags: {
type: "bad", type: "bad",
}, },
@@ -96,20 +123,29 @@ export const Nested = make({
{ {
title: "Subgroup 2", title: "Subgroup 2",
type: "group", type: "group",
isSelected: false, flags: {
isSelected: false,
isModified: false,
},
data: [], data: [],
}, },
{ {
title: "Other", title: "Other",
type: "items", type: "items",
isSelected: false, flags: {
isSelected: false,
isModified: false,
},
data: [ data: [
{ {
id: "4", id: "4",
entityId: "automation.4", entityId: "automation.4",
description: "Cool thing", description: "Cool thing",
title: "Automation #4", title: "Automation #4",
isSelected: false, flags: {
isSelected: false,
isModified: false,
},
state: "on", state: "on",
tags: { tags: {
type: "good", type: "good",
@@ -16,6 +16,7 @@ export type ListBoxGroupProps = AutomationManagerItem & {
) => void; ) => void;
onAutomationDelete: (aid: string, eid: string) => void; onAutomationDelete: (aid: string, eid: string) => void;
onSelect: (aid: string) => void; onSelect: (aid: string) => void;
onRun: (eid: string) => void;
initialOpenState?: boolean; initialOpenState?: boolean;
tagsDB: TagDB; tagsDB: TagDB;
}; };
@@ -23,7 +24,7 @@ export const ListBoxGroup: FC<ListBoxGroupProps> = ({
title, title,
type, type,
data, data,
isSelected, flags,
initialOpenState, initialOpenState,
tagsDB, tagsDB,
...events ...events
@@ -41,7 +42,8 @@ export const ListBoxGroup: FC<ListBoxGroupProps> = ({
<div <div
className={[ className={[
"automation-manager--list-box-group", "automation-manager--list-box-group",
isSelected ? "selected" : "", flags.isSelected ? "selected" : "",
flags.isModified ? "modified" : "",
].join(" ")} ].join(" ")}
> >
<div <div
@@ -67,7 +69,9 @@ export const ListBoxGroup: FC<ListBoxGroupProps> = ({
onDelete={() => onDelete={() =>
events.onAutomationDelete(auto.id, auto.entityId) events.onAutomationDelete(auto.id, auto.entityId)
} }
isSelected={auto.flags.isSelected}
onSelect={() => events.onSelect(auto.id)} onSelect={() => events.onSelect(auto.id)}
onRun={() => events.onRun(auto.entityId)}
onDescriptionUpdate={(description) => onDescriptionUpdate={(description) =>
events.onAutomationUpdate( events.onAutomationUpdate(
{ {
@@ -28,17 +28,13 @@ export const useAutomationDB = (
return out; return out;
} }
}, },
getAutomationData(autoId: string) { getAutomationData(
autoId: string
): null | [AutomationManagerAuto, AutomationData | null] {
if (newAuto && newAuto[0].id === autoId) { if (newAuto && newAuto[0].id === autoId) {
return newAuto[1]; return newAuto;
} }
return (autoMap[autoId] ?? [null, null])[1]; return autoMap[autoId] ?? null;
},
getAutomationState(autoId: string): string | null {
if (newAuto && newAuto[0].id === autoId) {
return newAuto[0].state;
}
return (autoMap[autoId] ?? [{ state: null }, null])[0].state;
}, },
isAutoNew(autoId: string) { isAutoNew(autoId: string) {
return (newAuto && newAuto[0].id === autoId) ?? false; return (newAuto && newAuto[0].id === autoId) ?? false;
@@ -9,14 +9,27 @@ import {
UseAutomationManagerStateArgs, UseAutomationManagerStateArgs,
} from "./state"; } from "./state";
import Alert from "@mui/material/Alert"; import Alert from "@mui/material/Alert";
import { useConfirm } from "material-ui-confirm";
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & { export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {
onAutomationDelete: (aid: string, eid: string) => void; onAutomationDelete: (aid: string, eid: string) => void;
}; };
export const AutomationManagerLoaded: FC< export const AutomationManagerLoaded: FC<
PropsWithChildren<AutomationManagerLoadedProps> PropsWithChildren<AutomationManagerLoadedProps>
> = ({ children, onAutomationDelete, ...args }) => { > = ({ children, ...args }) => {
const state = useAutomationManagerState(args); const state = useAutomationManagerState(args);
const confirm = useConfirm();
const onAutomationDelete = async (aid: string, eid: string) =>
confirm({
title: "Are you sure you want to delete this automation?",
confirmationText: "Delete",
})
.then(() => {
args.onAutomationDelete(aid, eid);
state.setSelectedAutomationId(null);
})
.catch(() => {});
return ( return (
<div className="automation-manager"> <div className="automation-manager">
@@ -27,11 +40,9 @@ export const AutomationManagerLoaded: FC<
selectedAutomationId={state.currentAutomationId} selectedAutomationId={state.currentAutomationId}
onSelectedAutomationId={state.setSelectedAutomationId} onSelectedAutomationId={state.setSelectedAutomationId}
onAutomationAdd={() => state.addNew()} onAutomationAdd={() => state.addNew()}
onAutomationDelete={(aid, eid) => { onAutomationDelete={onAutomationDelete}
onAutomationDelete(aid, eid);
state.setSelectedAutomationId(null);
}}
onAutomationUpdate={state.sideBarUpdateAutomation} onAutomationUpdate={state.sideBarUpdateAutomation}
onRun={args.onAutomationRun}
/> />
<div className={["automation-manager--editor"].join(" ")}> <div className={["automation-manager--editor"].join(" ")}>
{state.currentAutomationId !== null ? ( {state.currentAutomationId !== null ? (
@@ -43,6 +54,22 @@ export const AutomationManagerLoaded: FC<
}} }}
automation={state.currentAutomation} automation={state.currentAutomation}
onUpdate={state.editorUpdateAutomation} onUpdate={state.editorUpdateAutomation}
onDelete={() => {
if (
state.currentAutomationId &&
state.currentAutomationEntityId
) {
onAutomationDelete(
state.currentAutomationId,
state.currentAutomationEntityId
);
}
}}
onTrigger={() => {
if (state.currentAutomationEntityId) {
args.onAutomationRun(state.currentAutomationEntityId);
}
}}
tagDB={state.tagsDB} tagDB={state.tagsDB}
isNew={state.currentAutomationIsNew} isNew={state.currentAutomationIsNew}
/> />
@@ -15,6 +15,7 @@ export type UseAutomationManagerStateArgs = {
onAutomationAdd: (auto: AutomationData) => void; onAutomationAdd: (auto: AutomationData) => void;
onAutomationUpdate: (aid: string, auto: AutomationData) => void; onAutomationUpdate: (aid: string, auto: AutomationData) => void;
onAutomationStateChange: (eid: string, on: boolean) => void; onAutomationStateChange: (eid: string, on: boolean) => void;
onAutomationRun: (eid: string) => void;
}; };
export const useAutomationManagerState = ({ export const useAutomationManagerState = ({
configAutomations, configAutomations,
@@ -65,12 +66,15 @@ export const useAutomationManagerState = ({
get tagsDB() { get tagsDB() {
return tagsDB; return tagsDB;
}, },
get currentAutomation() { get currentAutomation(): AutomationData | null {
return currentAutomation; return currentAutomation === null ? null : currentAutomation[1];
}, },
get currentAutomationIsNew() { get currentAutomationIsNew() {
return automationDB.isAutoNew(cookies.currentAutomationId ?? ""); return automationDB.isAutoNew(cookies.currentAutomationId ?? "");
}, },
get currentAutomationEntityId(): string | null {
return currentAutomation === null ? null : currentAutomation[0].entityId;
},
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())) {
@@ -101,8 +105,9 @@ export const useAutomationManagerState = ({
aid: string, aid: string,
eid: string eid: string
) { ) {
const previousAutoState = automationDB.getAutomationData(aid); const previousAuto = automationDB.getAutomationData(aid);
if (previousAutoState) { if (previousAuto && previousAuto[1]) {
const previousAutoState = previousAuto[1];
if ( if (
previousAutoState.metadata.alias !== a.title || previousAutoState.metadata.alias !== a.title ||
previousAutoState.metadata.description !== a.description previousAutoState.metadata.description !== a.description
@@ -124,7 +129,8 @@ export const useAutomationManagerState = ({
{ variant: "error" } { variant: "error" }
); );
} }
const previousState = automationDB.getAutomationState(aid); const previousState =
previousAuto === null ? null : previousAuto[0].state;
if (previousState !== a.state) { if (previousState !== a.state) {
onAutomationStateChange(eid, a.state === "on"); onAutomationStateChange(eid, a.state === "on");
} }
@@ -8,7 +8,7 @@ import SaveIcon from "@mui/icons-material/SaveOutlined";
import { cleanUpUndefined } from "utils/helpers"; import { cleanUpUndefined } from "utils/helpers";
import { Modal } from "components/Modal"; import { Modal } from "components/Modal";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Buttons/Button";
import InputAutoText from "components/Inputs/InputAutoText"; import InputAutoText from "components/Inputs/InputAutoText";
import { TagDB } from "../TagDB"; import { TagDB } from "../TagDB";
@@ -30,7 +30,7 @@ export type TagModalState =
export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => { export const Tags: FC<TagsProps> = ({ automationId, tagsDB }) => {
const [modalState, setModal] = useState<TagModalState>({ open: false }); const [modalState, setModal] = useState<TagModalState>({ open: false });
const tags = tagsDB.getTags(automationId); const tags = tagsDB.getTags(automationId, true);
const onUpdate = (t: Record<string, string>) => const onUpdate = (t: Record<string, string>) =>
tagsDB.update(automationId, t); tagsDB.update(automationId, t);
@@ -42,12 +42,25 @@
font-size: 0.9em; font-size: 0.9em;
} }
.automation-manager--metadatabox .buttons {
display: flex;
flex-direction: row;
gap: 0.25em;
}
.automation-manager--metadatabox .delete:hover { .automation-manager--metadatabox .delete:hover {
cursor: pointer; cursor: pointer;
color: var(--mui-error-light); color: var(--mui-error-light);
color: var(--mui-error-contrastText);
background-color: var(--mui-error-dark); background-color: var(--mui-error-dark);
} }
.automation-manager--metadatabox .run:hover {
cursor: pointer;
color: var(--mui-success-contrastText);
background-color: var(--mui-success-dark);
}
.automation-manager--metadatabox .select:hover, .automation-manager--metadatabox .select:hover,
.automation-manager--metadatabox.selected.automation-manager--metadatabox .select { .automation-manager--metadatabox.selected.automation-manager--metadatabox .select {
cursor: pointer; cursor: pointer;
@@ -7,6 +7,7 @@ import Alert from "@mui/material/Alert";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import SelectIcon from "@mui/icons-material/HighlightAltSharp"; import SelectIcon from "@mui/icons-material/HighlightAltSharp";
import RunIcon from "@mui/icons-material/RunCircleOutlined";
import { InputTextView } from "components/Inputs/InputTextView"; import { InputTextView } from "components/Inputs/InputTextView";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
@@ -17,6 +18,7 @@ import { TagDB } from "../TagDB";
export type MetadataBoxProps = AutomationManagerAuto & { export type MetadataBoxProps = AutomationManagerAuto & {
onDelete: () => void; onDelete: () => void;
onSelect: () => void; onSelect: () => void;
onRun: () => void;
onStateUpdate: (s: "on" | "off") => void; onStateUpdate: (s: "on" | "off") => void;
onTitleUpdate: (t: string) => void; onTitleUpdate: (t: string) => void;
onDescriptionUpdate: (t: string) => void; onDescriptionUpdate: (t: string) => void;
@@ -80,6 +82,7 @@ export const MetadataBox: FC<MetadataBoxProps> = (props) => {
icon={<SelectIcon />} icon={<SelectIcon />}
onClick={props.onSelect} onClick={props.onSelect}
/> />
<ButtonIcon className="run" icon={<RunIcon />} onClick={props.onRun} />
<ButtonIcon <ButtonIcon
className="delete" className="delete"
icon={<DeleteForeverIcon />} icon={<DeleteForeverIcon />}
@@ -33,6 +33,7 @@ const story = makeStory({
selectedAutomationId={selectedAutomationId} selectedAutomationId={selectedAutomationId}
tagsDB={useTagDB(automations, (a, t) => onTagUpdate(t, a))} tagsDB={useTagDB(automations, (a, t) => onTagUpdate(t, a))}
automations={automations} automations={automations}
onRun={args.onRun}
onSelectedAutomationId={(aid) => { onSelectedAutomationId={(aid) => {
args.onSelectedAutomationId(aid); args.onSelectedAutomationId(aid);
setSelAutoId(aid); setSelAutoId(aid);
@@ -5,7 +5,7 @@ import { FC, useState } from "react";
import ArrowIcon from "@mui/icons-material/ArrowBackIosNewOutlined"; import ArrowIcon from "@mui/icons-material/ArrowBackIosNewOutlined";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import InputMultiSelect from "components/Inputs/InputMultiSelect"; import InputMultiSelect from "components/Inputs/InputMultiSelect";
import { ListBoxGroup } from "../ListBoxGroup"; import { ListBoxGroup } from "../ListBoxGroup";
@@ -16,7 +16,7 @@ import {
AutomationManagerAuto, AutomationManagerAuto,
AutomationManagerAutoUpdatable, AutomationManagerAutoUpdatable,
} from "../types"; } from "../types";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
export type AutomationManagerSidebarProps = { export type AutomationManagerSidebarProps = {
@@ -31,6 +31,7 @@ export type AutomationManagerSidebarProps = {
onAutomationDelete: (aid: string, eid: string) => void; onAutomationDelete: (aid: string, eid: string) => void;
onAutomationAdd: () => void; onAutomationAdd: () => void;
onSelectedAutomationId: (aid: string) => void; onSelectedAutomationId: (aid: string) => void;
onRun: (eid: string) => void;
}; };
export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
automations, automations,
@@ -60,7 +61,11 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
); );
const items = grouping.top.map((i) => const items = grouping.top.map((i) =>
convertGroupingToItems(i, selectedAutomationId, automations, grouping) convertGroupingToItems(i, automations, grouping, (aid, t) => ({
...t,
isSelected: aid === selectedAutomationId,
isModified: tagsDB.isModified(aid),
}))
); );
return ( return (
@@ -85,7 +90,10 @@ export const AutomationManagerSidebar: FC<AutomationManagerSidebarProps> = ({
<ListBoxGroup <ListBoxGroup
{...item} {...item}
key={i} key={i}
onSelect={onSelectedAutomationId} onSelect={(id) => {
onSelectedAutomationId(id);
setHidden(true);
}}
{...events} {...events}
tagsDB={tagsDB} tagsDB={tagsDB}
initialOpenState={true} initialOpenState={true}
@@ -1,4 +1,9 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
type TagDBState = {
original: Record<string, Record<string, string>>;
changed: Record<string, Record<string, string>>;
};
export type TagDB = ReturnType<typeof useTagDB>; export type TagDB = ReturnType<typeof useTagDB>;
export const useTagDB = ( export const useTagDB = (
automations: Array<{ automations: Array<{
@@ -8,28 +13,30 @@ export const useTagDB = (
onUpdate: (aid: string, tags: Record<string, string>) => void onUpdate: (aid: string, tags: Record<string, string>) => void
) => { ) => {
const lastAuto = useRef(JSON.stringify(automations)); const lastAuto = useRef(JSON.stringify(automations));
const [{ automationTags, changed }, setState] = useState({ const [{ original, changed }, setState] = useState<TagDBState>({
automationTags: convertAutoListToMap(automations), original: convertAutoListToMap(automations),
changed: new Set<string>(), changed: {},
}); });
const allTags = computeAllTags(automationTags); const allTags = computeAllTags(original);
const allTagNames = Object.keys(allTags); const allTagNames = Object.keys(allTags);
const isModified = changed.size > 0; const isModified = Object.keys(changed).length > 0;
useEffect(() => { useEffect(() => {
const c = JSON.stringify(automations); const c = JSON.stringify(automations);
if (lastAuto.current !== c) { if (lastAuto.current !== c) {
lastAuto.current = c; lastAuto.current = c;
setState({ setState({
automationTags: convertAutoListToMap(automations), original: convertAutoListToMap(automations),
changed: new Set(), changed: {},
}); });
} }
}, [automations, setState]); }, [automations, setState]);
return { return {
getTags(automationId: string) { getTags(automationId: string, includeChanged: boolean = false) {
return automationTags[automationId] ?? {}; if (includeChanged) {
return changed[automationId] ?? original[automationId] ?? {};
}
return original[automationId] ?? {};
}, },
getTagNames(myTags: string[]): string[] { getTagNames(myTags: string[]): string[] {
return allTagNames.filter((n) => !myTags.includes(n)).sort(); return allTagNames.filter((n) => !myTags.includes(n)).sort();
@@ -39,27 +46,33 @@ export const useTagDB = (
? Array.from(allTags[tagName].values()).sort() ? Array.from(allTags[tagName].values()).sort()
: []; : [];
}, },
isModified(aid: string) { isModified(aid: string): boolean {
return changed.has(aid); return aid in changed;
}, },
update(aid: string, tags: Record<string, string>) { update(aid: string, tags: Record<string, string>) {
if (JSON.stringify(tags) !== JSON.stringify(automationTags[aid])) { const update = JSON.stringify(tags);
setState({ if (aid in changed) {
changed: changed.add(aid), if (update === JSON.stringify(changed[aid])) {
automationTags: { return;
...automationTags, }
[aid]: tags, } else if (update === JSON.stringify(original[aid])) {
}, return;
});
} }
setState({
changed: {
...changed,
[aid]: tags,
},
original,
});
}, },
save(aid: string | null) { save(aid: string | null) {
if (isModified) { if (isModified) {
if (aid) { if (aid) {
onUpdate(aid, automationTags[aid]); onUpdate(aid, changed[aid]);
} else { } else {
for (const aid of changed.values()) { for (const [aid, change] of Object.entries(changed)) {
onUpdate(aid, automationTags[aid]); onUpdate(aid, change);
} }
} }
} }
@@ -99,7 +99,7 @@ test("bigAutoList groupings has not duplicate ids", () => {
test("convert grouper to items when no tags are selected", () => { test("convert grouper to items when no tags are selected", () => {
const grouping = makeGrouping(automations, [], null); const grouping = makeGrouping(automations, [], null);
const items = grouping.top.map((i) => const items = grouping.top.map((i) =>
convertGroupingToItems(i, "", automations, grouping) convertGroupingToItems(i, automations, grouping)
); );
expect(items.filter((i) => i.type === "group")).toHaveLength(0); expect(items.filter((i) => i.type === "group")).toHaveLength(0);
expect(items).toHaveLength(1); expect(items).toHaveLength(1);
@@ -109,7 +109,7 @@ test("convert grouper to items when no tags are selected", () => {
test("convert grouper to items when 1 tag is selected", () => { test("convert grouper to items when 1 tag is selected", () => {
const grouping = makeGrouping(automations, ["Room"], null); const grouping = makeGrouping(automations, ["Room"], null);
const items = grouping.top.map((i) => const items = grouping.top.map((i) =>
convertGroupingToItems(i, "", automations, grouping) convertGroupingToItems(i, automations, grouping)
); );
expect(grouping.top).toHaveLength(3); expect(grouping.top).toHaveLength(3);
expect(items.filter((i) => i.type === "group")).toHaveLength(0); expect(items.filter((i) => i.type === "group")).toHaveLength(0);
@@ -125,7 +125,7 @@ test("convert grouper to items when 1 tag is selected", () => {
test("convert grouper to items when 2 tag is selected", () => { test("convert grouper to items when 2 tag is selected", () => {
const grouping = makeGrouping(automations, ["Room", "Type"], null); const grouping = makeGrouping(automations, ["Room", "Type"], null);
const items = grouping.top.map((i) => const items = grouping.top.map((i) =>
convertGroupingToItems(i, "", automations, grouping) convertGroupingToItems(i, automations, grouping)
); );
expect(grouping.top).toHaveLength(3); expect(grouping.top).toHaveLength(3);
expect(items.filter((i) => i.type === "group")).toHaveLength(2); expect(items.filter((i) => i.type === "group")).toHaveLength(2);
@@ -1,4 +1,9 @@
import { AutomationManagerAuto, AutomationManagerItem } from "./types"; import {
AutomationManagerAuto,
AutomationManagerAutoItem,
AutomationManagerItem,
AutomationManagerItemFlags,
} from "./types";
const makeGrouper = () => { const makeGrouper = () => {
const groupIdNames: string[] = []; const groupIdNames: string[] = [];
@@ -149,33 +154,59 @@ export const makeGrouping = (
export const convertGroupingToItems = ( export const convertGroupingToItems = (
currentGroupIdx: number, currentGroupIdx: number,
selectedAutomationId: string | null,
autos: AutomationManagerAuto[], autos: AutomationManagerAuto[],
grouping: AutomationGrouping grouping: AutomationGrouping,
computeFlags: (
aid: string,
f: AutomationManagerItemFlags
) => AutomationManagerItemFlags = (aid, t) => t
): AutomationManagerItem => { ): AutomationManagerItem => {
const groupData = grouping.getData(currentGroupIdx); const groupData = grouping.getData(currentGroupIdx);
const automationIds = grouping.getAutomations(currentGroupIdx); const automationIds = grouping.getAutomations(currentGroupIdx);
if (automationIds.length > 0) { if (automationIds.length > 0) {
const data = automationIds.map<AutomationManagerAutoItem>((i) => {
return {
...autos[i],
flags: computeFlags(autos[i].id, {
isSelected: false,
isModified: false,
}),
};
});
return { return {
type: "items", type: "items",
title: groupData.name, title: groupData.name,
data: automationIds.map((i) => { data,
return { flags: data.reduce<AutomationManagerItemFlags>(
...autos[i], (out, a) => ({
isSelected: autos[i].id === selectedAutomationId, isSelected: out.isSelected || a.flags.isSelected,
}; isModified: out.isModified || a.flags.isModified,
}), }),
isSelected: groupData.selected, {
isSelected: false,
isModified: false,
}
),
}; };
} }
const subgroups = grouping.getSubGroups(currentGroupIdx); const subgroups = grouping.getSubGroups(currentGroupIdx);
const data = subgroups.map((i) =>
convertGroupingToItems(i, autos, grouping, computeFlags)
);
return { return {
type: "group", type: "group",
title: groupData.name, title: groupData.name,
data: subgroups.map((i) => data,
convertGroupingToItems(i, selectedAutomationId, autos, grouping) flags: data.reduce<AutomationManagerItemFlags>(
(out, a) => ({
isSelected: out.isSelected || a.flags.isSelected,
isModified: out.isModified || a.flags.isModified,
}),
{
isSelected: false,
isModified: false,
}
), ),
isSelected: groupData.selected,
}; };
}; };
@@ -20,6 +20,7 @@ const { make, componentMeta } = makeStory({
api={useMockApiService(args.automations ?? [], !args.automations)} api={useMockApiService(args.automations ?? [], !args.automations)}
haEntities={useMockHAEntities(haEntities)} haEntities={useMockHAEntities(haEntities)}
refreshAutomations={() => {}} refreshAutomations={() => {}}
triggerAutomation={() => {}}
forceDeleteAutomation={() => {}} forceDeleteAutomation={() => {}}
onAutomationStateChange={(eid, on) => { onAutomationStateChange={(eid, on) => {
if (!haEntities.loading && !haEntities.error) { if (!haEntities.loading && !haEntities.error) {
@@ -119,3 +120,54 @@ export const MissingAutoInConfig = make({
entitySource: {}, entitySource: {},
}, },
}); });
export const BadAutomation = make({
haProps: {
loading: false,
entities: {
[`automation.${auto1.metadata.id}`]: {
entity_id: `automation.${auto1.metadata.id}`,
attributes: {
id: "test",
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
last_updated: "",
state: "on",
},
},
entitySource: {},
},
automations: [
{
tags: {},
metadata: {
id: "test",
mode: "single",
alias: "Light.Tank_Day",
description: "",
},
trigger: [
{
platform: "sun",
event: "sunrise",
offset: "30",
} as any,
{ whoAmI: "bad node is who" } as any,
],
condition: [{ whoAmI: "bad node is who" } as any],
sequence: [
{ scene: "scene.light_day" } as any,
{ whoAmI: "bad node is who" } as any,
{
service: "input_select.set_options",
target: {
entity_id: "input_select.tank_light_mode",
},
data: {
options: "day",
},
},
],
},
],
});
@@ -1,6 +1,6 @@
import "./index.css"; import "./index.css";
import { FC, useState } from "react"; import { FC, useEffect, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress"; import LinearProgress from "@mui/material/LinearProgress";
import Skeleton from "@mui/material/Skeleton"; import Skeleton from "@mui/material/Skeleton";
@@ -14,6 +14,7 @@ export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => void; onAutomationStateChange: (eid: string, on: boolean) => void;
refreshAutomations: () => void; refreshAutomations: () => void;
forceDeleteAutomation: (eid: string) => void; forceDeleteAutomation: (eid: string) => void;
triggerAutomation: (eid: string) => void;
haEntities: HAEntitiesState; haEntities: HAEntitiesState;
api: ApiService; api: ApiService;
}; };
@@ -24,10 +25,16 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
onAutomationStateChange, onAutomationStateChange,
refreshAutomations, refreshAutomations,
forceDeleteAutomation, forceDeleteAutomation,
triggerAutomation,
}) => { }) => {
const snackbr = useSnackbar(); const snackbr = useSnackbar();
const [isSaving, setIsSaving] = useState(false); const [isSaving, setIsSaving] = useState(false);
useEffect(() => {
refreshAutomations();
// eslint-disable-next-line
}, []);
// handle bad states // handle bad states
if (!haEntities.ready && haEntities.error) { if (!haEntities.ready && haEntities.error) {
return ( return (
@@ -74,6 +81,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
<AutomationManagerLoaded <AutomationManagerLoaded
configAutomations={configAutomations.data} configAutomations={configAutomations.data}
hassEntities={hassEntities} hassEntities={hassEntities}
onAutomationRun={triggerAutomation}
onAutomationStateChange={onAutomationStateChange} onAutomationStateChange={onAutomationStateChange}
onAutomationAdd={async (auto) => { onAutomationAdd={async (auto) => {
await api.updateAutomation({ await api.updateAutomation({
@@ -10,10 +10,16 @@ export type AutomationManagerAuto = AutomationManagerAutoUpdatable & {
issue?: string; issue?: string;
isNew?: boolean; isNew?: boolean;
}; };
export type AutomationManagerAutoItem = AutomationManagerAuto & {
flags: AutomationManagerItemFlags;
};
export type AutomationManagerItemFlags = {
isSelected: boolean;
isModified: boolean;
};
export type AutomationManagerItem = { export type AutomationManagerItem = {
title: string; title: string;
isSelected: boolean; flags: AutomationManagerItemFlags;
} & ( } & (
| { | {
type: "group"; type: "group";
@@ -21,6 +27,6 @@ export type AutomationManagerItem = {
} }
| { | {
type: "items"; type: "items";
data: Array<AutomationManagerAuto & { isSelected: boolean }>; data: Array<AutomationManagerAutoItem>;
} }
); );
@@ -7,7 +7,7 @@ import { AutomationCondition } from "types/automations/conditions";
import { getSubTypeList } from "utils/automations"; import { getSubTypeList } from "utils/automations";
import { getConditionDefaultValues } from "utils/defaults"; import { getConditionDefaultValues } from "utils/defaults";
import { useHA } from "haService"; import { useHA } from "haService";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { getViewer } from "./viewRender"; import { getViewer } from "./viewRender";
import { getEditor } from "./editorRender"; import { getEditor } from "./editorRender";
import useWindowSize from "utils/useWindowSize"; import useWindowSize from "utils/useWindowSize";
@@ -10,26 +10,26 @@ import {
TriggerCondition, TriggerCondition,
ZoneCondition, ZoneCondition,
} from "types/automations/conditions"; } from "types/automations/conditions";
import InputNumber from "components/Inputs/InputNumber"; import InputNumber from "components/Inputs/Base/InputNumber";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import { InputEntity } from "components/Inputs/InputEntities"; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { import {
ConditionNodeBase, ConditionNodeBase,
ConditionNodeBaseViewMode, ConditionNodeBaseViewMode,
} from "./ConditionNodeBase"; } from "./ConditionNodeBase";
import { genUpdateMethods } from "./nestedUpdater"; import { genUpdateMethods } from "./nestedUpdater";
import { InputTime } from "components/Inputs/InputTime"; import { InputTime } from "components/Inputs/Base/InputTime";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { HAService } from "haService"; import { HAService } from "haService";
import { DeviceEditor } from "components/DeviceEditor"; import { DeviceEditor } from "components/DeviceEditor";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
import AddIcon from "@mui/icons-material/Add"; import AddIcon from "@mui/icons-material/Add";
import { getEntityDomains } from "utils/automations"; import { getEntityDomains } from "utils/automations";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; import { InputAutoComplete } from "components/Inputs/AutoComplete/InputAutoComplete";
import { InputTimeEntity } from "components/Inputs/InputTimeEntity"; import { InputTimeEntity } from "components/Inputs/AutoComplete/InputTimeEntity";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { RemoveCircle } from "@mui/icons-material"; import { RemoveCircle } from "@mui/icons-material";
interface Editor<C extends AutomationCondition> interface Editor<C extends AutomationCondition>
@@ -6,7 +6,7 @@ export const NODE_HEIGHT = 80 as const;
export const DEFAULT_DIMS: DAGDims = { export const DEFAULT_DIMS: DAGDims = {
collection: { collection: {
height: NODE_HEIGHT * 3, height: NODE_HEIGHT * 3,
width: NODE_WIDTH * 1.5, width: NODE_WIDTH * 2.5,
}, },
node: { node: {
height: NODE_HEIGHT, height: NODE_HEIGHT,
@@ -8,67 +8,61 @@ import { AutomationActionData } from "types/automations";
import { createUpdaterFromAutomationData } from "../updater"; import { createUpdaterFromAutomationData } from "../updater";
import { ModalState } from "../board/types"; import { ModalState } from "../board/types";
import { DEFAULT_DIMS } from "./constants"; import { DEFAULT_DIMS } from "./constants";
import { makeStory } from "devUtils";
const Demo: FC<{ const { make, componentMeta } = makeStory({
automation: AutomationActionData; Component: (props: {
flipped: boolean; automation: AutomationActionData;
}> = (props) => { flipped: boolean;
const { namer } = useHA(); }) => {
const [state, setState] = useState<AutomationActionData>(props.automation); const { namer } = useHA();
const [modalState, setModalState] = const [state, setState] = useState<AutomationActionData>(props.automation);
useState<ModalState | undefined>(undefined); const [modalState, setModalState] =
const updater = createUpdaterFromAutomationData( useState<ModalState | undefined>(undefined);
setModalState, const updater = createUpdaterFromAutomationData(
state, setModalState,
setState state,
); setState
const elementData = useAutomationNodes(state, { );
dims: { const elementData = useAutomationNodes(state, {
...DEFAULT_DIMS, dims: {
flipped: props.flipped, ...DEFAULT_DIMS,
}, flipped: props.flipped,
namer, },
openModal: setModalState, namer,
stateUpdater: updater, openModal: setModalState,
}); stateUpdater: updater,
return ( });
<DAGGraphBoard return (
modalState={modalState} <DAGGraphBoard
closeModal={() => setModalState(undefined)} modalState={modalState}
state={{ closeModal={() => setModalState(undefined)}
ready: true, state={{
data: { ready: true,
elements: elementData, data: {
}, elements: elementData,
}} },
/> }}
); />
}; );
},
export default { meta: {
title: "DAGGraph/Elements", title: "DAGGraph/Elements",
component: Demo, args: {
parameters: { actions: { argTypesRegex: "^on.*" } }, flipped: true,
args: { automation: {
flipped: true, trigger: [],
automation: { condition: [],
trigger: [], sequence: [],
condition: [], },
sequence: [],
}, },
}, },
} as ComponentMeta<typeof Demo>; });
const Template: ComponentStory<typeof Demo> = (args) => ( export default componentMeta;
<Page>
<Demo {...args} />
</Page>
);
export const Empty = Template.bind({}); export const Empty = make({});
export const Trigger = Template.bind({}); export const Trigger = make({
Trigger.args = {
...Trigger.args,
automation: { automation: {
trigger: [ trigger: [
{ platform: "homeassistant", event: "up" }, { platform: "homeassistant", event: "up" },
@@ -82,10 +76,9 @@ Trigger.args = {
condition: [], condition: [],
sequence: [], sequence: [],
}, },
}; });
export const Conditions = Template.bind({});
Conditions.args = { export const Conditions = make({
...Conditions.args,
automation: { automation: {
trigger: [ trigger: [
{ {
@@ -119,11 +112,9 @@ Conditions.args = {
], ],
sequence: [], sequence: [],
}, },
}; });
export const FullAuto = Template.bind({}); export const FullAuto = make({
FullAuto.args = {
...FullAuto.args,
automation: { automation: {
condition: [ condition: [
{ {
@@ -272,11 +263,9 @@ FullAuto.args = {
}, },
], ],
}, },
}; });
export const ChooseAuto = Template.bind({}); export const ChooseAuto = make({
ChooseAuto.args = {
...ChooseAuto.args,
automation: { automation: {
condition: [], condition: [],
trigger: [], trigger: [],
@@ -370,12 +359,9 @@ ChooseAuto.args = {
}, },
], ],
}, },
}; });
export const EmptyChooseAuto = Template.bind({}); export const EmptyChooseAuto = make({
EmptyChooseAuto.args = {
...EmptyChooseAuto.args,
automation: { automation: {
condition: [], condition: [],
trigger: [], trigger: [],
@@ -386,11 +372,9 @@ EmptyChooseAuto.args = {
}, },
], ],
}, },
}; });
export const RepeatAuto = Template.bind({}); export const RepeatAuto = make({
RepeatAuto.args = {
...RepeatAuto.args,
automation: { automation: {
condition: [], condition: [],
trigger: [], trigger: [],
@@ -437,11 +421,9 @@ RepeatAuto.args = {
}, },
], ],
}, },
}; });
export const ParallelAuto = Template.bind({}); export const ParallelAuto = make({
ParallelAuto.args = {
...ParallelAuto.args,
automation: { automation: {
condition: [], condition: [],
trigger: [], trigger: [],
@@ -467,11 +449,9 @@ ParallelAuto.args = {
}, },
], ],
}, },
}; });
export const BadNodes = Template.bind({}); export const BadNodes = make({
BadNodes.args = {
...BadNodes.args,
automation: { automation: {
condition: [ condition: [
{ {
@@ -500,11 +480,9 @@ BadNodes.args = {
}, },
] as any, ] as any,
}, },
}; });
export const IfElseNode = Template.bind({}); export const IfElseNode = make({
IfElseNode.args = {
...IfElseNode.args,
automation: { automation: {
condition: [], condition: [],
trigger: [], trigger: [],
@@ -516,4 +494,24 @@ IfElseNode.args = {
}, },
], ],
}, },
}; });
export const TimeNodes = make({
automation: {
condition: [],
trigger: [
{
platform: "time",
at: "",
},
{
platform: "time_pattern",
},
],
sequence: [
{
condition: "time",
},
],
},
});
@@ -29,7 +29,7 @@ export const useDAGElementsState = () => {
}, },
getIsClosedActions(nodeId: string, node: AutomationNode) { getIsClosedActions(nodeId: string, node: AutomationNode) {
if (isSpecialNode(getNodeSubType(node))) { if (isSpecialNode(getNodeSubType(node, true))) {
return { return {
isClosed: this.get(nodeId).isClosed ?? false, isClosed: this.get(nodeId).isClosed ?? false,
setIsClosed: (v: boolean) => this.set(nodeId, "isClosed", v), setIsClosed: (v: boolean) => this.set(nodeId, "isClosed", v),
@@ -4,7 +4,7 @@ import { ButtonIcon } from "components/Icons/ButtonIcons";
import { FC } from "react"; import { FC } from "react";
import { ButtonNodeProps } from "./types"; import { ButtonNodeProps } from "./types";
import { Handle, Position } from "react-flow-renderer"; import { Handle, Position } from "react-flow-renderer";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Buttons/Button";
export const ButtonNode: FC<ButtonNodeProps> = ({ export const ButtonNode: FC<ButtonNodeProps> = ({
height, height,
@@ -12,7 +12,7 @@ import Edit from "@mui/icons-material/Edit";
import KeyboardArrowDownSharpIcon from "@mui/icons-material/KeyboardArrowDownSharp"; import KeyboardArrowDownSharpIcon from "@mui/icons-material/KeyboardArrowDownSharp";
import AddOutlined from "@mui/icons-material/AddOutlined"; import AddOutlined from "@mui/icons-material/AddOutlined";
import InputBoolean from "components/Inputs/InputBoolean"; import InputBoolean from "components/Inputs/Base/InputBoolean";
import { SpeedDial } from "components/SpeedDial"; import { SpeedDial } from "components/SpeedDial";
import { SequenceNodeElementProps } from "./types"; import { SequenceNodeElementProps } from "./types";
import { useSequenceNodeColor } from "./util"; import { useSequenceNodeColor } from "./util";
@@ -104,6 +104,9 @@ export const createUpdater = (
}), }),
trigger: createBasicUpdater("trigger", { trigger: createBasicUpdater("trigger", {
platform: "device", platform: "device",
domain: "",
type: "",
device_id: "",
})({ })({
trigger: args.trigger, trigger: args.trigger,
openModal: args.openModal, openModal: args.openModal,
+4 -4
View File
@@ -1,10 +1,10 @@
import { import {
BaseOption, BaseOption,
InputAutoComplete, InputAutoComplete,
} from "components/Inputs/InputAutoComplete"; } from "components/Inputs/AutoComplete/InputAutoComplete";
import { InputDevice } from "components/Inputs/InputDevice"; import { InputDevice } from "components/Inputs/AutoComplete/InputDevice";
import { InputDeviceCapabilties } from "components/Inputs/InputDeviceCapabilties"; import { InputDeviceCapabilties } from "components/Inputs/AutoComplete/InputDeviceCapabilties";
import { InputEntity } from "components/Inputs/InputEntities"; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { cleanUpUndefined } from "utils/helpers"; import { cleanUpUndefined } from "utils/helpers";
import { DeviceBaseType, DeviceTypeCapability } from "haService/types"; import { DeviceBaseType, DeviceTypeCapability } from "haService/types";
import { AutomationDeviceState } from "types/automations/common"; import { AutomationDeviceState } from "types/automations/common";
@@ -4,10 +4,10 @@ import { useSnackbar } from "notistack";
import { useRef } from "react"; import { useRef } from "react";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import { InputAutoComplete, Option } from "./InputAutoComplete"; import { InputAutoComplete, Option } from "./InputAutoComplete";
import InputBoolean from "./InputBoolean"; import InputBoolean from "components/Inputs/Base/InputBoolean";
import { InputTime } from "./InputDayTime"; import { InputTime } from "../Base/InputTime";
import InputNumber from "./InputNumber"; import InputNumber from "components/Inputs/Base/InputNumber";
import InputText from "./InputText"; import InputText from "components/Inputs/Base/InputText";
export type InputDeviceCapabiltiesProps<T extends Record<string, any>> = { export type InputDeviceCapabiltiesProps<T extends Record<string, any>> = {
defn: HaFormSchema[]; defn: HaFormSchema[];
@@ -11,7 +11,7 @@ import {
isAutomationTimeString24Hours, isAutomationTimeString24Hours,
} from "utils/time"; } from "utils/time";
import { InputEntity } from "./InputEntities"; import { InputEntity } from "./InputEntities";
import { InputTime } from "./InputTime"; import { InputTime } from "components/Inputs/Base/InputTime";
export type InputTimeEntityProps = { export type InputTimeEntityProps = {
value: string; value: string;
@@ -1,4 +1,5 @@
import "./InputTime.css"; import "./InputTime.css";
import { useState, useEffect, FC } from "react"; import { useState, useEffect, FC } from "react";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import EditIcon from "@mui/icons-material/Edit"; import EditIcon from "@mui/icons-material/Edit";
@@ -1,150 +0,0 @@
import "./InputTime.css";
import { useState, useEffect, FC } from "react";
import TextField from "@mui/material/TextField";
import EditIcon from "@mui/icons-material/Edit";
import CloseIcon from "@mui/icons-material/Close";
import { AutomationTime, AutomationTimeObject } from "types/automations/common";
import {
convertAutomationTimeToTimeObject,
convertObjectToAutomationTimeString,
} from "utils/time";
import { convertAutomationTimeToTimeString } from "utils/time";
import { prettyName } from "utils/formatting";
import InputLabel from "@mui/material/InputLabel";
import { ButtonIcon } from "components/Icons/ButtonIcons";
// constants
const fields: Array<keyof AutomationTimeObject> = [
"hours",
"minutes",
"seconds",
"milliseconds",
];
export interface Props {
label: string;
value?: AutomationTime;
onChange: (v?: AutomationTimeObject) => void;
}
export const InputTime: FC<Props> = (props) => {
// state
const [disabled, setDisabled] = useState(!props.value);
const [displayValue, setDisplayValue] = useState(
convertAutomationTimeToTimeObject(props.value)
);
// process display input
const updateOne = (k: keyof AutomationTimeObject) => (v: string) => {
if (Number(v) < 0) {
setDisplayValue({
...displayValue,
[k]: 0,
});
} else if (k === "hours") {
setDisplayValue({
...displayValue,
[k]: Number(v),
});
} else if (k === "minutes") {
let minutes = Number(v);
let { hours = 0 } = displayValue;
if (minutes > 59) {
const additonalHours = Math.floor(minutes / 60);
hours += additonalHours;
minutes = minutes - additonalHours * 60;
}
setDisplayValue({
...displayValue,
minutes,
hours,
});
} else if (k === "seconds") {
let seconds = Number(v);
let { hours = 0, minutes = 0 } = displayValue;
if (seconds > 59) {
const additonalHours = Math.floor(seconds / (60 * 60));
hours += additonalHours;
seconds = seconds - additonalHours * 60;
}
if (seconds > 59) {
const additionalMinutes = Math.floor(seconds / 60);
minutes += additionalMinutes;
seconds = seconds - additionalMinutes * 60;
}
setDisplayValue({
...displayValue,
minutes,
hours,
seconds,
});
} else if (k === "milliseconds") {
let milliseconds = Number(v);
let { hours = 0, minutes = 0, seconds = 0 } = displayValue;
if (milliseconds > 1000) {
const additonalHours = Math.floor(milliseconds / (60 * 60 * 1000));
hours += additonalHours;
milliseconds = milliseconds - additonalHours * 60 * 60 * 1000;
}
if (milliseconds > 1000) {
const additionalMinutes = Math.floor(milliseconds / (60 * 1000));
minutes += additionalMinutes;
milliseconds = milliseconds - additionalMinutes * 60 * 1000;
}
if (milliseconds > 1000) {
const additionalSeconds = Math.floor(milliseconds / 1000);
seconds += additionalSeconds;
milliseconds = milliseconds - additionalSeconds * 1000;
}
setDisplayValue({
...displayValue,
minutes,
hours,
seconds,
milliseconds,
});
}
};
// effect
useEffect(() => {
if (disabled && !props.value) {
return;
}
if (disabled) {
props.onChange(undefined);
} else {
const pVal = convertAutomationTimeToTimeString(props.value);
const cVal = convertObjectToAutomationTimeString(displayValue);
if (pVal !== cVal) {
props.onChange(displayValue);
}
}
// eslint-disable-next-line
}, [disabled, displayValue]);
return (
<div className="input-time">
<InputLabel>{props.label}</InputLabel>
<div className="input-time--inner">
{fields.map((name) => (
<TextField
key={name}
variant="filled"
label={prettyName(name)}
defaultValue="00"
InputProps={{
disabled,
type: "number",
title: prettyName(name),
}}
value={displayValue[name] ?? 0}
onChange={(e) => updateOne(name)(e.target.value)}
/>
))}
<ButtonIcon
onClick={() => setDisabled(!disabled)}
icon={disabled ? <EditIcon /> : <CloseIcon />}
/>
</div>
</div>
);
};
@@ -1,6 +1,6 @@
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { Page } from "components/Page";
import InputText from "./InputText"; import InputText from "./Base/InputText";
import { InputTextView } from "./InputTextView"; import { InputTextView } from "./InputTextView";
+28 -25
View File
@@ -1,33 +1,36 @@
import React from "react"; import React from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react'; import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Modal } from "."; import { Modal } from ".";
import { useState } from 'react'; import { useState } from "react";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Buttons/Button";
export default { export default {
title: 'Modal', title: "Modal",
component: Modal, component: Modal,
parameters: { actions: { argTypesRegex: '^on.*' } }, parameters: { actions: { argTypesRegex: "^on.*" } },
args: { args: {
open: true open: true,
} },
} as ComponentMeta<typeof Modal> } as ComponentMeta<typeof Modal>;
export const Simple: ComponentStory<typeof Modal> = args => { export const Simple: ComponentStory<typeof Modal> = (args) => {
return <> return (
<Modal {...args}> <>
<div>Hello World!</div> <Modal {...args}>
</Modal> <div>Hello World!</div>
</> </Modal>
} </>
export const WithButtons: ComponentStory<typeof Modal> = args => { );
};
export const WithButtons: ComponentStory<typeof Modal> = (args) => {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
return <> return (
<Button onClick={() => setOpen(!open)}>Open Me!</Button> <>
<Modal open={open}> <Button onClick={() => setOpen(!open)}>Open Me!</Button>
<div>Hello World!</div> <Modal open={open}>
<Button onClick={() => setOpen(!open)}>Close Me!</Button> <div>Hello World!</div>
</Modal> <Button onClick={() => setOpen(!open)}>Close Me!</Button>
</> </Modal>
} </>
);
};
@@ -1,33 +1,31 @@
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import { FireEventAction } from "types/automations/actions"; import { FireEventAction } from "types/automations/actions";
import { OptionManager, updateActionData } from "./OptionManager"; import { OptionManager, updateActionData } from "./OptionManager";
export const ActionEventState: OptionManager<FireEventAction> = { export const ActionEventState: OptionManager<FireEventAction> = {
defaultState: () => ({ defaultState: () => ({
alias: "Fire Event", alias: "Fire Event",
event: "", event: "",
event_data: {}, event_data: {},
}), }),
isReady: ({ alias, event }) => ( isReady: ({ alias, event }) => alias !== "" && event !== "",
alias !== '' &&
event !== ""
),
renderOptionList: (state, setState) => { renderOptionList: (state, setState) => {
const update = updateActionData(state, setState); const update = updateActionData(state, setState);
return <> return (
<InputText <>
textBoxFor="event" <InputText
label="Event" textBoxFor="event"
value={state.event} label="Event"
onChange={event => update({ event })} value={state.event}
/> onChange={(event) => update({ event })}
<InputYaml />
label="Event Data" <InputYaml
value={state.event_data} label="Event Data"
onChange={event_data => update({ event_data })} value={state.event_data}
/> onChange={(event_data) => update({ event_data })}
</> />
} </>
} );
},
};
@@ -1,7 +1,7 @@
import InputNumber from "components/Inputs/InputNumber"; import InputNumber from "components/Inputs/Base/InputNumber";
import { RepeatAction } from "types/automations/actions"; import { RepeatAction } from "types/automations/actions";
import { OptionManager } from "./OptionManager"; import { OptionManager } from "./OptionManager";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; import { InputAutoComplete } from "components/Inputs/AutoComplete/InputAutoComplete";
const determineType = (repeatNode: RepeatAction["repeat"]) => const determineType = (repeatNode: RepeatAction["repeat"]) =>
"count" in repeatNode ? "count" : "until" in repeatNode ? "until" : "while"; "count" in repeatNode ? "count" : "until" in repeatNode ? "until" : "while";
@@ -0,0 +1,21 @@
import InputText from "components/Inputs/Base/InputText";
import { SceneAction } from "types/automations/actions";
import { OptionManager } from "./OptionManager";
export const ActionSceneState: OptionManager<SceneAction> = {
defaultState: () => ({
scene: "",
}),
isReady: () => true,
Component: ({ state, setState }) => {
return (
<>
<InputText
label="Scene"
value={state.scene ?? ""}
onChange={(d) => setState({ ...state, scene: d })}
/>
</>
);
},
};
@@ -1,4 +1,4 @@
import { InputService } from "components/Inputs/InputService"; import { InputService } from "components/Inputs/AutoComplete/InputService";
import { ServiceEditor } from "components/ServiceEditor"; import { ServiceEditor } from "components/ServiceEditor";
import { ServiceAction } from "types/automations/actions"; import { ServiceAction } from "types/automations/actions";
import { OptionManager, updateActionData } from "./OptionManager"; import { OptionManager, updateActionData } from "./OptionManager";
@@ -1,4 +1,4 @@
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import { StopAction } from "types/automations/actions"; import { StopAction } from "types/automations/actions";
import { OptionManager } from "./OptionManager"; import { OptionManager } from "./OptionManager";
@@ -1,23 +1,23 @@
import "./ActionWait.css"; import "./ActionWait.css";
import InputBoolean from "components/Inputs/InputBoolean"; import InputBoolean from "components/Inputs/Base/InputBoolean";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import InputNumber from "components/Inputs/InputNumber"; import InputNumber from "components/Inputs/Base/InputNumber";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import { InputTime } from "components/Inputs/InputTime"; import { InputTime } from "components/Inputs/Base/InputTime";
import { useState } from "react"; import { useState } from "react";
import { DelayAction, WaitAction } from "types/automations/actions"; import { DelayAction, WaitAction } from "types/automations/actions";
import { OptionManager, updateActionData } from './OptionManager'; import { OptionManager, updateActionData } from "./OptionManager";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
type ThisAction = WaitAction | DelayAction; type ThisAction = WaitAction | DelayAction;
type Option = 'delay' | 'template' | 'trigger' type Option = "delay" | "template" | "trigger";
const getCurrentOption = (node: ThisAction): Option => { const getCurrentOption = (node: ThisAction): Option => {
if ('delay' in node) { if ("delay" in node) {
return 'delay' return "delay";
} else { } else {
return 'template' return "template";
} }
} };
export const ActionWaitState: OptionManager<ThisAction> = { export const ActionWaitState: OptionManager<ThisAction> = {
defaultState: () => ({ defaultState: () => ({
@@ -32,78 +32,108 @@ export const ActionWaitState: OptionManager<ThisAction> = {
const base: any = { const base: any = {
alias: state.alias, alias: state.alias,
variables: state.variables, variables: state.variables,
} };
if (opt === 'delay') { if (opt === "delay") {
setState({ setState({
...base, ...base,
delay: (state as any).delay ?? "", delay: (state as any).delay ?? "",
}) });
} else { } else {
base.timeout = (state as any).timeout base.timeout = (state as any).timeout;
base.continue_on_timeout = (state as any).continue_on_timeout base.continue_on_timeout = (state as any).continue_on_timeout;
if (opt === 'template') { if (opt === "template") {
setState({ setState({
...base, ...base,
wait_template: (state as any).wait_template ?? "", wait_template: (state as any).wait_template ?? "",
}) });
} else { } else {
setState({ setState({
...base, ...base,
wait_for_trigger: (state as any).wait_for_trigger ?? "", wait_for_trigger: (state as any).wait_for_trigger ?? "",
}) });
} }
} }
_setCurrent(opt) _setCurrent(opt);
} };
// determine options // determine options
let option: JSX.Element = <></>; let option: JSX.Element = <></>;
if (current === "delay") { if (current === "delay") {
option = <> option = (
<InputTime className="for" label="for" value={(state as any).delay} onChange={delay => update({ delay })} /> <>
</> <InputTime
} else if (current === 'template') { className="for"
label="for"
value={(state as any).delay}
onChange={(delay) => update({ delay })}
/>
</>
);
} else if (current === "template") {
state = state as WaitAction; state = state as WaitAction;
option = <> option = (
<InputText <>
label="Template" <InputText
className="template" label="Template"
value={state.wait_template ?? ""} className="template"
onChange={wait_template => update({ wait_template })} value={state.wait_template ?? ""}
/> onChange={(wait_template) => update({ wait_template })}
</> />
} else if (current === 'trigger') { </>
);
} else if (current === "trigger") {
state = state as WaitAction; state = state as WaitAction;
option = <> option = (
<InputYaml <>
className="triggers" <InputYaml
label="Triggers" className="triggers"
value={state.wait_for_trigger ?? []} label="Triggers"
onChange={wait_for_trigger => update({ wait_for_trigger })} value={state.wait_for_trigger ?? []}
/> onChange={(wait_for_trigger) => update({ wait_for_trigger })}
</> />
</>
);
} }
// render // render
return <div className="node-editor--action-wait"> return (
<InputList <div className="node-editor--action-wait">
className="wait-type" <InputList
label="Wait Type" prettyOptionLabels className="wait-type"
options={["template", 'trigger', "delay"]} label="Wait Type"
current={current} onChange={setCurrent} /> prettyOptionLabels
{option} options={["template", "trigger", "delay"]}
{current !== 'delay' ? <div className="wait-options"> current={current}
<InputNumber onChange={setCurrent}
label="Timeout"
value={(state as any).timeout ? Number((state as any).timeout) : undefined}
onChange={timeout => update({ timeout: timeout === undefined ? undefined : String(timeout) })}
/> />
<InputBoolean {option}
label="Continue on Timeout" {current !== "delay" ? (
value={(state as any).continue_on_timeout ?? false} <div className="wait-options">
onChange={continue_on_timeout => update({ continue_on_timeout })} <InputNumber
/> label="Timeout"
</div> : <></>} value={
</div> (state as any).timeout
} ? Number((state as any).timeout)
} : undefined
}
onChange={(timeout) =>
update({
timeout: timeout === undefined ? undefined : String(timeout),
})
}
/>
<InputBoolean
label="Continue on Timeout"
value={(state as any).continue_on_timeout ?? false}
onChange={(continue_on_timeout) =>
update({ continue_on_timeout })
}
/>
</div>
) : (
<></>
)}
</div>
);
},
};
@@ -0,0 +1,39 @@
import { OptionManager } from "./OptionManager";
import { AutomationTriggerCalendar } from "types/automations/triggers";
import { InputList } from "components/Inputs/InputList";
import InputText from "components/Inputs/Base/InputText";
export const TriggerCalendarState: OptionManager<AutomationTriggerCalendar> = {
defaultState: (): AutomationTriggerCalendar => ({
platform: "calendar",
event: "sunset",
}),
isReady: () => true,
Component: ({ state, setState }) => {
return (
<>
<InputList
label="Event Type"
current={state.event}
options={["start", "end"]}
onChange={(event) =>
setState({
...state,
event,
})
}
/>
<InputText
label="Offset"
value={state.offset ?? ""}
onChange={(s) =>
setState({
...state,
offset: !s ? undefined : s,
})
}
/>
</>
);
},
};
@@ -5,6 +5,9 @@ import { DeviceEditor } from "components/DeviceEditor";
export const TriggerDevice: OptionManager<AutomationTriggerDevice> = { export const TriggerDevice: OptionManager<AutomationTriggerDevice> = {
defaultState: () => ({ defaultState: () => ({
platform: "device", platform: "device",
device_id: "",
domain: "",
type: "",
}), }),
isReady: () => true, isReady: () => true,
Component: ({ state, setState, ha }) => { Component: ({ state, setState, ha }) => {
@@ -27,6 +30,9 @@ export const TriggerDevice: OptionManager<AutomationTriggerDevice> = {
setState={(s) => setState={(s) =>
setState({ setState({
platform: "device", platform: "device",
device_id: "",
domain: "",
type: "",
...s, ...s,
}) })
} }
@@ -1,7 +1,7 @@
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import { OptionManager } from "./OptionManager"; import { OptionManager } from "./OptionManager";
import { AutomationTriggerEvent } from "../../../types/automations/triggers"; import { AutomationTriggerEvent } from "../../../types/automations/triggers";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
export const TriggerEventState: OptionManager<AutomationTriggerEvent> = { export const TriggerEventState: OptionManager<AutomationTriggerEvent> = {
defaultState: () => ({ defaultState: () => ({
@@ -1,33 +1,34 @@
import { OptionManager } from './OptionManager'; import { OptionManager } from "./OptionManager";
import { AutomationTriggerMQTT } from 'types/automations/triggers'; import { AutomationTriggerMQTT } from "types/automations/triggers";
import InputText from 'components/Inputs/InputText'; import InputText from "components/Inputs/Base/InputText";
export const TriggerMQTTState: OptionManager<AutomationTriggerMQTT> = { export const TriggerMQTTState: OptionManager<AutomationTriggerMQTT> = {
defaultState: () => ({ defaultState: () => ({
"platform": "mqtt", platform: "mqtt",
"payload": "", payload: "",
"topic": "", topic: "",
"value_template": "" value_template: "",
}), }),
isReady: () => true, isReady: () => true,
renderOptionList: (state, setState) => { renderOptionList: (state, setState) => {
return <> return (
<InputText <>
label='Payload' <InputText
value={state.payload} label="Payload"
onChange={payload => setState({ ...state, payload })} value={state.payload}
/> onChange={(payload) => setState({ ...state, payload })}
<InputText />
label='Topic' <InputText
value={state.topic} label="Topic"
onChange={topic => setState({ ...state, topic })} value={state.topic}
/> onChange={(topic) => setState({ ...state, topic })}
<InputText />
label='Template' <InputText
value={state.value_template} label="Template"
onChange={value_template => setState({ ...state, value_template })} value={state.value_template}
/> onChange={(value_template) => setState({ ...state, value_template })}
</> />
} </>
} );
},
};
@@ -1,63 +1,82 @@
import { OptionManager } from './OptionManager'; import { OptionManager } from "./OptionManager";
import { AutomationTriggerNumericState } from 'types/automations/triggers'; import { AutomationTriggerNumericState } from "types/automations/triggers";
import InputText from 'components/Inputs/InputText'; import InputText from "components/Inputs/Base/InputText";
import { InputEntity } from 'components/Inputs/InputEntities'; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import InputNumber from 'components/Inputs/InputNumber'; import InputNumber from "components/Inputs/Base/InputNumber";
import { InputTime } from 'components/Inputs/InputTime'; import InputYaml from 'components/Inputs/InputYaml'; import { InputTime } from "components/Inputs/Base/InputTime";
import InputYaml from "components/Inputs/Base/InputYaml";
export const TriggerNumericState: OptionManager<AutomationTriggerNumericState> =
export const TriggerNumericState: OptionManager<AutomationTriggerNumericState> = { {
defaultState: () => ({ defaultState: () => ({
"platform": 'numeric_state', platform: "numeric_state",
"entity_id": "", entity_id: "",
}), }),
isReady: () => true, isReady: () => true,
renderOptionList: (state, setState) => { renderOptionList: (state, setState) => {
return <> return (
<InputEntity <>
value={state.entity_id} <InputEntity
multiple value={state.entity_id}
onChange={entity_id => setState({ multiple
...state, onChange={(entity_id) =>
entity_id setState({
})} ...state,
/> entity_id,
<InputText label="Attribute" value={state.attribute ?? ""} onChange={attribute => setState({ })
...state, }
attribute />
})} /> <InputText
<InputNumber label="Attribute"
label="Above" value={state.attribute ?? ""}
value={state.above ? Number(state.above) : undefined} onChange={(attribute) =>
onChange={above => setState({ setState({
...state, ...state,
above: above ? String(above) : undefined, attribute,
})} })
/> }
<InputNumber />
label="Below" <InputNumber
value={state.below ? Number(state.below) : undefined} label="Above"
onChange={below => setState({ value={state.above ? Number(state.above) : undefined}
...state, onChange={(above) =>
below: below ? String(below) : undefined, setState({
})} ...state,
/> above: above ? String(above) : undefined,
<InputYaml })
label="Template" }
value={state.value_template ?? ""} />
onChange={value_template => setState({ <InputNumber
...state, label="Below"
value_template value={state.below ? Number(state.below) : undefined}
})} onChange={(below) =>
/> setState({
<InputTime ...state,
label="For" below: below ? String(below) : undefined,
value={state.for} })
onChange={_for => setState({ }
...state, />
for: _for, <InputYaml
})} label="Template"
/> value={state.value_template ?? ""}
</> onChange={(value_template) =>
} setState({
} ...state,
value_template,
})
}
/>
<InputTime
label="For"
value={state.for}
onChange={(_for) =>
setState({
...state,
for: _for,
})
}
/>
</>
);
},
};
@@ -1,9 +1,9 @@
import { OptionManager } from "./OptionManager"; import { OptionManager } from "./OptionManager";
import { AutomationTriggerState } from "types/automations/triggers"; import { AutomationTriggerState } from "types/automations/triggers";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import { InputEntity } from "components/Inputs/InputEntities"; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { InputTime } from "components/Inputs/InputTime"; import { InputTime } from "components/Inputs/Base/InputTime";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; import { InputAutoComplete } from "components/Inputs/AutoComplete/InputAutoComplete";
import { FC } from "react"; import { FC } from "react";
import { getEntityDomains } from "utils/automations"; import { getEntityDomains } from "utils/automations";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
@@ -0,0 +1,39 @@
import { OptionManager } from "./OptionManager";
import { AutomationTriggerSun } from "types/automations/triggers";
import { InputList } from "components/Inputs/InputList";
import InputText from "components/Inputs/Base/InputText";
export const TriggerSunState: OptionManager<AutomationTriggerSun> = {
defaultState: (): AutomationTriggerSun => ({
platform: "sun",
event: "sunset",
}),
isReady: () => true,
Component: ({ state, setState }) => {
return (
<>
<InputList
label="Event Type"
current={state.event}
options={["sunset", "sunrise"]}
onChange={(event) =>
setState({
...state,
event,
})
}
/>
<InputText
label="Offset"
value={state.offset ?? ""}
onChange={(s) =>
setState({
...state,
offset: !s ? undefined : s,
})
}
/>
</>
);
},
};
@@ -1,30 +1,33 @@
import { OptionManager } from './OptionManager'; import { OptionManager } from "./OptionManager";
import { AutomationTriggerTemplate } from 'types/automations/triggers'; import { AutomationTriggerTemplate } from "types/automations/triggers";
import InputText from 'components/Inputs/InputText'; import InputText from "components/Inputs/Base/InputText";
import { InputTime } from 'components/Inputs/InputTime'; import { InputTime } from "components/Inputs/Base/InputTime";
export const TriggerTemplate: OptionManager<AutomationTriggerTemplate> = { export const TriggerTemplate: OptionManager<AutomationTriggerTemplate> = {
defaultState: () => ({ defaultState: () => ({
"platform": 'template', platform: "template",
"value_template": "", value_template: "",
}), }),
isReady: () => true, isReady: () => true,
renderOptionList: (state, setState) => { renderOptionList: (state, setState) => {
return <> return (
<InputText <>
label='Template' <InputText
value={state.value_template} label="Template"
onChange={value_template => setState({ ...state, value_template })} value={state.value_template}
/> onChange={(value_template) => setState({ ...state, value_template })}
<InputTime />
label="For" <InputTime
value={state.for} label="For"
onChange={_for => setState({ value={state.for}
...state, onChange={(_for) =>
for: _for, setState({
})} ...state,
/> for: _for,
</> })
} }
} />
</>
);
},
};
@@ -8,13 +8,13 @@ import {
AutomationTriggerExactTime, AutomationTriggerExactTime,
AutomationTriggerTimePattern, AutomationTriggerTimePattern,
} from "types/automations/triggers"; } from "types/automations/triggers";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import { FC } from "react"; import { FC } from "react";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button"; 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/InputTimeEntity"; import { InputTimeEntity } from "components/Inputs/AutoComplete/InputTimeEntity";
export const TriggerTime: OptionManager<AutomationTriggerTime> = { export const TriggerTime: OptionManager<AutomationTriggerTime> = {
defaultState: () => ({ defaultState: () => ({
@@ -59,7 +59,8 @@ export const TriggerTime: OptionManager<AutomationTriggerTime> = {
divisible by that number. You can specify "*" to match any value.{" "} divisible by that number. You can specify "*" to match any value.{" "}
<a <a
href="https://www.home-assistant.io/docs/automation/trigger/#time-pattern-trigger" href="https://www.home-assistant.io/docs/automation/trigger/#time-pattern-trigger"
target="_blank" rel="noreferrer" target="_blank"
rel="noreferrer"
> >
More Info. More Info.
</a> </a>
@@ -1,20 +1,31 @@
import { OptionManager } from './OptionManager'; import { OptionManager } from "./OptionManager";
import { AutomationTriggerWebhook } from 'types/automations/triggers'; import { AutomationTriggerWebhook } from "types/automations/triggers";
import InputText from 'components/Inputs/InputText'; import InputText from "components/Inputs/Base/InputText";
export const TriggerWebhook: OptionManager<AutomationTriggerWebhook> = { export const TriggerWebhook: OptionManager<AutomationTriggerWebhook> = {
defaultState: () => ({ defaultState: () => ({
"platform": 'webhook', platform: "webhook",
"webhook_id": "", webhook_id: "",
}), }),
isReady: () => true, isReady: () => true,
renderOptionList: (state, setState) => { Component: ({ state, setState }) => {
return <> return (
<InputText label="Webhook ID" value={state.webhook_id ?? ""} onChange={webhook_id => setState({ <>
...state, <InputText
webhook_id label="Webhook ID"
})} /> value={state.webhook_id ?? ""}
</> onChange={(webhook_id) =>
} setState({
} ...state,
webhook_id,
})
}
/>
<span>
You can run this automation by sending an HTTP POST request to
http://your-home-assistant-ip/api/webhook/{state.webhook_id}.
</span>
</>
);
},
};
@@ -1,40 +1,53 @@
import { OptionManager } from './OptionManager'; import { OptionManager } from "./OptionManager";
import { AutomationTriggerZone } from 'types/automations/triggers'; import { AutomationTriggerZone } from "types/automations/triggers";
import { InputList } from 'components/Inputs/InputList'; import { InputList } from "components/Inputs/InputList";
import { InputEntity } from 'components/Inputs/InputEntities'; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
export const TriggerZone: OptionManager<AutomationTriggerZone> = { export const TriggerZone: OptionManager<AutomationTriggerZone> = {
defaultState: () => ({ defaultState: () => ({
"platform": 'zone', platform: "zone",
"zone": "", zone: "",
"event": "enter", event: "enter",
"entity_id": "", entity_id: "",
}), }),
isReady: () => true, isReady: () => true,
renderOptionList: (state, setState) => { renderOptionList: (state, setState) => {
return <> return (
<InputEntity label="Zone" restrictToDomain={['zone']} value={state.zone} onChange={zone => setState({ <>
...state, <InputEntity
zone: zone ?? "" label="Zone"
})} /> restrictToDomain={["zone"]}
<InputList value={state.zone}
label="Event" onChange={(zone) =>
current={state.event} setState({
options={['enter', 'leave']} ...state,
onChange={event => setState({ zone: zone ?? "",
...state, event, })
})} }
/> />
<InputEntity <InputList
multiple label="Event"
restrictToDomain={["device_tracker", "person"]} current={state.event}
value={state.entity_id} options={["enter", "leave"]}
onChange={entity_id => setState({ onChange={(event) =>
...state, setState({
entity_id ...state,
})} event,
/> })
</> }
} />
} <InputEntity
multiple
restrictToDomain={["device_tracker", "person"]}
value={state.entity_id}
onChange={(entity_id) =>
setState({
...state,
entity_id,
})
}
/>
</>
);
},
};
@@ -20,6 +20,9 @@ import { TriggerZone } from "./TriggerZone";
import { TriggerDevice } from "./TriggerDevice"; import { TriggerDevice } from "./TriggerDevice";
import { ActionStopState } from "./ActionStop"; import { ActionStopState } from "./ActionStop";
import { ActionParallelState } from "./ActionParallel"; import { ActionParallelState } from "./ActionParallel";
import { TriggerSunState } from "./TriggerSun";
import { TriggerCalendarState } from "./TriggerCalendar";
import { ActionSceneState } from "./ActionScene";
export const getOptionManager = <T extends AutomationNodeTypes>( export const getOptionManager = <T extends AutomationNodeTypes>(
nodeType: T, nodeType: T,
@@ -39,6 +42,8 @@ export const getOptionManager = <T extends AutomationNodeTypes>(
return ActionCallServiceState; return ActionCallServiceState;
case "wait": case "wait":
return ActionWaitState; return ActionWaitState;
case "scene":
return ActionSceneState;
case "stop": case "stop":
return ActionStopState; return ActionStopState;
case "delay": case "delay":
@@ -58,6 +63,10 @@ export const getOptionManager = <T extends AutomationNodeTypes>(
return TriggerHAState; return TriggerHAState;
case "mqtt": case "mqtt":
return TriggerMQTTState; return TriggerMQTTState;
case "sun":
return TriggerSunState;
case "calendar":
return TriggerCalendarState;
case "numeric_state": case "numeric_state":
return TriggerNumericState; return TriggerNumericState;
case "state": case "state":
@@ -7,8 +7,8 @@ import {
getSubTypeList, getSubTypeList,
validateNode, validateNode,
} from "utils/automations"; } from "utils/automations";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import { getDescriptionFromAutomationNode } from "utils/formatting"; import { getDescriptionFromAutomationNode } from "utils/formatting";
import { useHA } from "haService"; import { useHA } from "haService";
import { Generic } from "./Generic"; import { Generic } from "./Generic";
@@ -1,57 +1,55 @@
import React from "react"; import React from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react"; import { ComponentStory } from "@storybook/react";
import { NodeEditor } from "."; import { NodeEditor, NodeEditorProps } from ".";
import { AutomationCondition } from "types/automations/conditions"; import { AutomationCondition } from "types/automations/conditions";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Buttons/Button";
import { useState } from "react"; import { useState } from "react";
import { Modal } from "components/Modal"; import { Modal } from "components/Modal";
import { Page } from "components/Page"; import { Page } from "components/Page";
import { makeStory } from "devUtils";
export default { const { componentMeta, make } = makeStory({
title: "NodeEditor", meta: {
component: NodeEditor, title: "NodeEditor",
parameters: { actions: { argTypesRegex: "^on.*" } }, args: {
args: { node: {
node: { data: {},
data: {}, service: "",
service: "", target: "",
target: "", },
}, },
}, },
} as ComponentMeta<typeof NodeEditor>; Component: (props: NodeEditorProps) => {
const [state, setState] = useState(props.node);
return (
<Page>
<NodeEditor
{...props}
node={state}
onSave={(s) => {
setState(s);
props.onSave && props.onSave(s);
}}
/>
</Page>
);
},
});
const Base: ComponentStory<typeof NodeEditor> = (props) => { export default componentMeta;
const [state, setState] = useState(props.node);
return ( export const Action = make({});
<Page> export const SingleOption = make({
<NodeEditor
{...props}
node={state}
onSave={(s) => {
setState(s);
props.onSave && props.onSave(s);
}}
/>
</Page>
);
};
export const Action = Base.bind({});
export const SingleOption = Action.bind({});
SingleOption.args = {
...SingleOption.args,
allowedTypes: ["action"], allowedTypes: ["action"],
}; });
export const Condition = Action.bind({}); export const Condition = make({
Condition.args = {
...Condition.args,
node: { node: {
condition: "and", condition: "and",
conditions: [ conditions: [
{ {
condition: "numeric_state", condition: "numeric_state",
entity_id: ["sensor.kitchen_humidity"], entity_id: ["sensor.kitchen_humidity"],
conditions: [],
above: "40", above: "40",
}, },
{ {
@@ -59,26 +57,22 @@ Condition.args = {
value_template: "states('switch.kitchen') == 'on'", value_template: "states('switch.kitchen') == 'on'",
}, },
], ],
} as AutomationCondition, },
}; });
export const UnSupported = Action.bind({}); export const UnSupported = make({
UnSupported.args = {
...UnSupported.args,
node: { node: {
condition: "bargs", condition: "bargs",
platform: "rouge", platform: "rouge",
} as any, } as any,
}; });
export const DeviceTriggerExample = Action.bind({}); export const DeviceTriggerExample = make({
DeviceTriggerExample.args = {
...DeviceTriggerExample.args,
node: { node: {
platform: "device", platform: "device",
device_id: "bd83b10cb1c7aa028c12dade5b4e87d5", device_id: "bd83b10cb1c7aa028c12dade5b4e87d5",
}, },
}; });
export const InAModal: ComponentStory<typeof NodeEditor> = (props) => { export const InAModal: ComponentStory<typeof NodeEditor> = (props) => {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@@ -92,19 +86,15 @@ export const InAModal: ComponentStory<typeof NodeEditor> = (props) => {
); );
}; };
export const ServiceExample = Action.bind({}); export const ServiceExample = make({
ServiceExample.args = {
...ServiceExample.args,
node: { node: {
target: {}, target: {},
data: {}, data: {},
service: "", service: "",
}, },
}; });
export const ServiceWithDataExample = Action.bind({}); export const ServiceWithDataExample = make({
ServiceWithDataExample.args = {
...ServiceWithDataExample.args,
node: { node: {
target: { target: {
entity: "light.switch_baby", entity: "light.switch_baby",
@@ -114,37 +104,29 @@ ServiceWithDataExample.args = {
}, },
service: "light.turn_on", service: "light.turn_on",
}, },
}; });
export const DelayExample = Action.bind({}); export const DelayExample = make({
DelayExample.args = {
...DelayExample.args,
node: { node: {
wait_template: "", wait_template: "",
}, },
}; });
export const StateTriggerExample = Action.bind({}); export const StateTriggerExample = make({
StateTriggerExample.args = {
...StateTriggerExample.args,
node: { node: {
platform: "state", platform: "state",
entity_id: "binary_sensor.door_main", entity_id: "binary_sensor.door_main",
}, },
}; });
export const DeviceActionFilledExample = Action.bind({}); export const DeviceActionFilledExample = make({
DeviceActionFilledExample.args = {
...DeviceActionFilledExample.args,
node: { node: {
type: "toggle", type: "toggle",
device_id: "c9711be86b0301955f72380509285485", device_id: "c9711be86b0301955f72380509285485",
}, } as any,
}; });
export const NotifyPhoneViaDeviceAction = Action.bind({}); export const NotifyPhoneViaDeviceAction = make({
NotifyPhoneViaDeviceAction.args = {
...NotifyPhoneViaDeviceAction.args,
node: { node: {
device_id: "2a98db84af7526c7ec3cc7aebd1a9e1c", device_id: "2a98db84af7526c7ec3cc7aebd1a9e1c",
domain: "mobile_app", domain: "mobile_app",
@@ -152,4 +134,11 @@ NotifyPhoneViaDeviceAction.args = {
title: "Hassio Status", title: "Hassio Status",
message: "Hassio Is turning off...", message: "Hassio Is turning off...",
} as any, } as any,
}; });
export const Sun = make({
node: {
platform: "sun",
event: "sunset",
},
});
+2 -2
View File
@@ -4,8 +4,8 @@ import { FC, ReactNode } from "react";
import { AutomationNode, AutomationNodeMapping } from "types/automations/index"; import { AutomationNode, AutomationNodeMapping } from "types/automations/index";
import { useEditorNodeState } from "./OptionManager"; import { useEditorNodeState } from "./OptionManager";
import { InputList } from "components/Inputs/InputList"; import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button"; import { Button } from "components/Inputs/Buttons/Button";
import InputBoolean from "components/Inputs/InputBoolean"; import InputBoolean from "components/Inputs/Base/InputBoolean";
import { useConfirm } from "material-ui-confirm"; import { useConfirm } from "material-ui-confirm";
import { getNodeSubTypeDescription } from "./utils"; import { getNodeSubTypeDescription } from "./utils";
+15
View File
@@ -4,10 +4,25 @@ const subtypeDescMap: Partial<Record<AutomationNodeSubtype, string>> = {
choose: "create conditional if/else statements", choose: "create conditional if/else statements",
parallel: "run multiple nodes at the same time", parallel: "run multiple nodes at the same time",
stop: "stop the automation with a status code", stop: "stop the automation with a status code",
scene: "activate a scene.",
wait: "wait based on a condition", wait: "wait based on a condition",
repeat: "repeat a sequence until or while some conditions are met", repeat: "repeat a sequence until or while some conditions are met",
device: "device related actions", device: "device related actions",
service: "call a service", service: "call a service",
event: "fires when an event is being received.",
homeassistant: "fires when Home Assistant starts up or shuts down.",
mqtt: "fires when a specific message is received on given MQTT topic.",
sun: "fires when the sun is setting or rising.",
numeric_state:
"fires when the numeric value of an entity's state or attribute changes.",
state: "fires when an entity's state or attribute changes",
template: "evaluate a custom template",
time: "specify a certain time to run",
webhook:
"webhook trigger fires when a web request is made to the webhook endpoint",
zone: "specify when an entity enters or leaves a zone",
tag: "fires when a tag is scanned.",
calendar: "fires when a Calendar event starts or ends.",
}; };
export const getNodeSubTypeDescription = ( export const getNodeSubTypeDescription = (
@@ -1,16 +1,19 @@
import "./ServiceEditorField.css"; import "./ServiceEditorField.css";
import { FC, useRef } from "react"; import { FC, useRef } from "react";
import { ServiceEditorOption } from "./options"; import { ServiceEditorOption } from "./options";
import InputText from "components/Inputs/InputText"; import InputText from "components/Inputs/Base/InputText";
import InputNumber from "components/Inputs/InputNumber"; import InputNumber from "components/Inputs/Base/InputNumber";
import { RemoveCircle } from "@mui/icons-material"; import { RemoveCircle } from "@mui/icons-material";
import { InputAutoComplete, Option } from "components/Inputs/InputAutoComplete"; import {
InputAutoComplete,
Option,
} from "components/Inputs/AutoComplete/InputAutoComplete";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
import InputBoolean from "components/Inputs/InputBoolean"; import InputBoolean from "components/Inputs/Base/InputBoolean";
import { SelectorNumber, SelectorText } from "haService/fieldTypes"; import { SelectorNumber, SelectorText } from "haService/fieldTypes";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
import { useSnackbar } from "notistack"; import { useSnackbar } from "notistack";
import { InputEntity } from "components/Inputs/InputEntities"; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { ButtonIcon } from "components/Icons/ButtonIcons"; import { ButtonIcon } from "components/Icons/ButtonIcons";
export type ServiceEditorFieldProps = { export type ServiceEditorFieldProps = {
@@ -1,9 +1,9 @@
import "./ServiceEditorTarget.css"; import "./ServiceEditorTarget.css";
import { InputDevice } from "components/Inputs/InputDevice"; import { InputDevice } from "components/Inputs/AutoComplete/InputDevice";
import { InputEntity } from "components/Inputs/InputEntities"; import { InputEntity } from "components/Inputs/AutoComplete/InputEntities";
import { Targets } from "haService/fieldTypes"; import { Targets } from "haService/fieldTypes";
import { FC } from "react"; import { FC } from "react";
import { InputArea } from "components/Inputs/InputArea"; import { InputArea } from "components/Inputs/AutoComplete/InputArea";
type RawTargetData = { type RawTargetData = {
entity_id?: string[] | string; entity_id?: string[] | string;
@@ -3,7 +3,7 @@ import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page"; import { Page } from "components/Page";
import { ServiceEditor } from "."; import { ServiceEditor } from ".";
import { TypedHassService } from "haService/fieldTypes"; import { TypedHassService } from "haService/fieldTypes";
import InputYaml from "components/Inputs/InputYaml"; import InputYaml from "components/Inputs/Base/InputYaml";
export default { export default {
title: "Services/ServiceEditor", title: "Services/ServiceEditor",
@@ -10,7 +10,7 @@ import {
ServiceEditorData, ServiceEditorData,
} from "./options"; } from "./options";
import { ServiceEditorField } from "./ServiceEditorField"; import { ServiceEditorField } from "./ServiceEditorField";
import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; import { InputAutoComplete } from "components/Inputs/AutoComplete/InputAutoComplete";
import { ServiceEditorTarget } from "./ServiceEditorTarget"; import { ServiceEditorTarget } from "./ServiceEditorTarget";
export type ServiceEditorProps = { export type ServiceEditorProps = {
+12 -7
View File
@@ -1,4 +1,4 @@
import { BaseOption } from "components/Inputs/InputAutoComplete"; import { BaseOption } from "components/Inputs/AutoComplete/InputAutoComplete";
import { FieldData, TypedHassService } from "haService/fieldTypes"; import { FieldData, TypedHassService } from "haService/fieldTypes";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
@@ -7,17 +7,22 @@ export type ServiceEditorData = {
target: Record<string, any>; target: Record<string, any>;
}; };
export type ServiceEditorOption = BaseOption<{ export type ServiceEditorOption = BaseOption<{
data: FieldData data: FieldData;
}>; }>;
export const convertFieldToOption = (id: string, data: FieldData): ServiceEditorOption => ({ export const convertFieldToOption = (
id: string,
data: FieldData
): ServiceEditorOption => ({
id, id,
label: data.name ?? prettyName(id), label: data.name ?? prettyName(id),
data, data,
}) });
export const splitUpOptions = (
export const splitUpOptions = (service: TypedHassService, data: ServiceEditorData) => { service: TypedHassService,
data: ServiceEditorData
) => {
const required: ServiceEditorOption[] = []; const required: ServiceEditorOption[] = [];
const additional: ServiceEditorOption[] = []; const additional: ServiceEditorOption[] = [];
const incmFields: string[] = []; const incmFields: string[] = [];
@@ -28,7 +33,7 @@ export const splitUpOptions = (service: TypedHassService, data: ServiceEditorDat
required.push(opt); required.push(opt);
} else { } else {
if (data.field[opt.id]) { if (data.field[opt.id]) {
incmFields.push(opt.id) incmFields.push(opt.id);
} else { } else {
additional.push(opt); additional.push(opt);
} }
+4 -1
View File
@@ -1,6 +1,9 @@
import { Connection, getCollection } from "home-assistant-js-websocket"; import { Connection, getCollection } from "home-assistant-js-websocket";
import { useHassCollection } from "./useHassCollection"; import { useHassCollection } from "./useHassCollection";
import { Option, BaseOption } from "components/Inputs/InputAutoComplete"; import {
Option,
BaseOption,
} from "components/Inputs/AutoComplete/InputAutoComplete";
import { EntityRegisteryItem, HassEntitiesRegistry } from "./types"; import { EntityRegisteryItem, HassEntitiesRegistry } from "./types";
import { prettyName } from "utils/formatting"; import { prettyName } from "utils/formatting";
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more