new automation support

This commit is contained in:
ari committed 2022-07-28 17:54:15 -04:00
1 parent 96617e7b0c
commit 3f0430ab37
9 files changed
+285 -136

No files matched your search

@@ -0,0 +1,129 @@
import { HassEntities } from "home-assistant-js-websocket";
import { useEffect, useState } from "react";
import { AutomationData } from "types/automations";
import { defaultAutomation } from "utils/defaults";
import { TagDB } from "../TagDB";
import { AutomationManagerAuto } from "../types";
export const useAutomationDB = (
haEntities: HassEntities,
configAutomations: AutomationData[],
tagsDB: TagDB
) => {
const autoMap = genMapping(haEntities, configAutomations, tagsDB);
const [newAuto, setNewAuto] =
useState<null | [AutomationManagerAuto, AutomationData]>(null);
useEffect(() => {
if (newAuto && autoMap[newAuto[0].id]) {
setNewAuto(null);
}
}, [autoMap, newAuto]);
return {
get managerAutoList() {
const out = Object.values(autoMap).map(([m, _]) => m);
if (newAuto) {
return out.concat([newAuto[0]]);
} else {
return out;
}
},
getAutomationData(autoId: string) {
if (newAuto && newAuto[0].id === autoId) {
return newAuto[1];
}
return (autoMap[autoId] ?? [null, null])[1];
},
isAutoNew(autoId: string) {
return (newAuto && newAuto[0].id === autoId) ?? false;
},
removeNew() {
setNewAuto(null);
},
addNew() {
const auto = defaultAutomation(String(Date.now()));
setNewAuto([
{
id: auto.metadata.id,
entityId: "",
title: auto.metadata.alias ?? "",
description: auto.metadata.description ?? "",
state: "unregistered",
tags: {},
issue: "New Automation",
},
auto,
]);
return auto;
},
};
};
const genMapping = (
haEntities: HassEntities,
configAutomations: AutomationData[],
tagsDB: TagDB
) => {
const configData: Record<string, AutomationData> = configAutomations.reduce(
(all, n) => ({
...all,
[n.metadata.id]: n,
}),
{}
);
const automatioinMap: Record<
string,
[AutomationManagerAuto, AutomationData | null]
> = {};
Object.entries(haEntities)
.filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation."))
.forEach(([entityId, entityData]) => {
const autoId = entityData.attributes.id;
let title = entityData.attributes.friendly_name ?? "";
let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state)
? undefined
: `recived invalid state "${entityData.state}, this could be because you have a lingering automation that was not cleared by homeassistant, try to reboot HA or manually clear this automation from HA Database."`;
let found: AutomationData | null = null;
if (configData[autoId]) {
found = configData[entityData.attributes.id];
title = found.metadata.alias ?? title;
description = found.metadata.description ?? description;
delete configData[autoId];
} else {
issue = "failed to find this automation in '/config' folder";
}
automatioinMap[autoId] = [
{
id: autoId,
entityId,
title,
description,
state: entityData.state,
tags: tagsDB.getTags(autoId),
issue,
},
found,
];
});
Object.values(configData).forEach((auto) => {
automatioinMap[auto.metadata.id] = [
{
id: auto.metadata.id,
entityId: "",
title: auto.metadata.alias ?? "",
description: auto.metadata.description ?? "",
state: "unregistered",
tags: tagsDB.getTags(auto.metadata.id),
issue:
"homeassistant did not load this automation, try to manually reload automations or restart homeassistant.",
},
auto,
];
});
return automatioinMap;
};
@@ -2,69 +2,49 @@ import "./index.css";
import { AutomationEditor } from "components/AutomationEditor";
import { DEFAULT_DIMS } from "components/DAGGraph/elements/constants";
import { HassEntities } from "home-assistant-js-websocket";
import { FC, PropsWithChildren } from "react";
import { AutomationData } from "types/automations";
import { consolidateAutomations } from "../helpers";
import { AutomationManagerSidebar } from "../Sidebar";
import { useTagDB } from "../TagDB";
import { useAutomationManagerState } from "./state";
import {
useAutomationManagerState,
UseAutomationManagerStateArgs,
} from "./state";
import Alert from "@mui/material/Alert";
export type AutomationManagerLoadedProps = {
configAutomations: AutomationData[];
hassEntities: HassEntities;
onUpdateTags: (aid: string, tags: Record<string, string>) => void;
};
export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {};
export const AutomationManagerLoaded: FC<
PropsWithChildren<AutomationManagerLoadedProps>
> = ({ configAutomations, onUpdateTags, hassEntities, children }) => {
const state = useAutomationManagerState();
const tagsDB = useTagDB(
configAutomations.map(({ metadata: { id }, tags }) => ({
id,
tags,
})),
onUpdateTags
);
const automations = consolidateAutomations(
hassEntities,
configAutomations.map(({ metadata }) => metadata),
tagsDB
);
const currentAutomation = configAutomations.filter(
({ metadata: { id } }) => state.current === id
);
> = ({ children, ...args }) => {
const state = useAutomationManagerState(args);
return (
<div className="automation-manager">
{children}
<AutomationManagerSidebar
automations={automations}
tagsDB={tagsDB}
selectedAutomationId={state.current}
onSelectedAutomationId={state.setCurrent}
onAutomationAdd={() => {}}
automations={state.automations}
tagsDB={state.tagsDB}
selectedAutomationId={state.currentAutomationId}
onSelectedAutomationId={state.setSelectedAutomationId}
onAutomationAdd={() => state.addNew()}
onAutomationDelete={() => {}}
onAutomationUpdate={() => {}}
/>
<div className="automation-manager--editor">
{state.current !== null ? (
currentAutomation.length > 0 ? (
<div className={["automation-manager--editor"].join(" ")}>
{state.currentAutomationId !== null ? (
state.currentAutomation ? (
<AutomationEditor
dims={{
...DEFAULT_DIMS,
flipped: true,
}}
automation={currentAutomation[0]}
onUpdate={() => {}}
tagDB={tagsDB}
automation={state.currentAutomation}
onUpdate={state.updateAutomation}
tagDB={state.tagsDB}
/>
) : (
<div>
<Alert color="warning">
Failed to find an automation on disk with id {state.current}.
Failed to find an automation on disk with id{" "}
{state.currentAutomationId}.
</Alert>
</div>
)
@@ -1,7 +1,99 @@
import { HassEntities } from "home-assistant-js-websocket";
import { useState } from "react";
import { useCookies } from "react-cookie";
import { AutomationData } from "types/automations";
import { useTagDB } from "../TagDB";
import { useAutomationDB } from "./automationDB";
import { useConfirm } from "material-ui-confirm";
export const useAutomationManagerState = () => {
export type UseAutomationManagerStateArgs = {
configAutomations: AutomationData[];
hassEntities: HassEntities;
onUpdateTags: (aid: string, tags: Record<string, string>) => void;
// onAutomationDelete: (aid: string) => void;
onAutomationAdd: (auto: AutomationData) => void;
};
export const useAutomationManagerState = ({
configAutomations,
hassEntities,
onUpdateTags,
onAutomationAdd,
}: UseAutomationManagerStateArgs) => {
// state
const confirm = useConfirm();
const cookies = useAMSCookies();
const tagsDB = useTagDB(
configAutomations.map(({ metadata: { id }, tags }) => ({
id,
tags,
})),
onUpdateTags
);
const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB);
// alias
const stillHaveNewAreYouSure = async () => {
try {
await confirm({
content:
"Selecting another automation will cause you to lose all work done on this new automation. Please save your work on this automation first.",
confirmationText: "Switch Automation",
cancellationText: "Cancel",
});
return true;
} catch (_) {
return false;
}
};
const currentAutomation = automationDB.getAutomationData(
cookies.currentAutomationId ?? ""
);
const methods = {
get currentAutomationId() {
return cookies.currentAutomationId;
},
get automations() {
return automationDB.managerAutoList;
},
get tagsDB() {
return tagsDB;
},
get currentAutomation() {
return currentAutomation;
},
get currentAutomationIsNew() {
return automationDB.isAutoNew(cookies.currentAutomationId ?? "");
},
async setSelectedAutomationId(i: string | null, force: boolean = false) {
if (methods.currentAutomationIsNew && !force) {
if (!(await stillHaveNewAreYouSure())) {
return;
}
automationDB.removeNew();
}
cookies.setSelectedAutomation(i);
},
async addNew() {
if (methods.currentAutomationIsNew) {
if (!(await stillHaveNewAreYouSure())) {
return;
}
}
const auto = automationDB.addNew();
methods.setSelectedAutomationId(auto.metadata.id, true);
},
updateAutomation(auto: AutomationData) {
if (methods.currentAutomationIsNew) {
onAutomationAdd(auto);
} else {
}
},
};
return methods;
};
const useAMSCookies = () => {
const [
cookies,
setCookies,
@@ -13,12 +105,13 @@ export const useAutomationManagerState = () => {
initialCurrent = cookies.selectedAutomation ?? null;
} catch (_) {}
const [current, setCurrent] = useState<string | null>(initialCurrent);
const [selectedAutomation, setSelectedAutomation] =
useState<string | null>(initialCurrent);
return {
current,
setCurrent(i: string | null) {
setCurrent(i);
currentAutomationId: selectedAutomation,
setSelectedAutomation(i: string | null) {
setSelectedAutomation(i);
setCookies("selectedAutomation", i === null ? undefined : i);
},
};
@@ -0,0 +1,19 @@
import { AutomationManagerAuto } from "../types";
export const filterAutomations = (
autos: AutomationManagerAuto[],
searchText: string
): AutomationManagerAuto[] =>
autos.filter((a) => {
if (searchText.length > 0) {
if (
!(
(a.description ?? "").toLocaleLowerCase().includes(searchText) ||
(a.title ?? "").toLocaleLowerCase().includes(searchText)
)
) {
return false;
}
}
return true;
});
@@ -5,6 +5,7 @@
--bottom-height: 3em;
position: relative;
height: 100%;
min-width: 25vw;
}
.automation-manager--sidebar-box--nav {
@@ -35,6 +36,7 @@
.automation-manager--sidebar.hidden {
width: 2.5em;
min-width: 0;
}
.automation-manager--sidebar.hidden .automation-manager--sidebar-box--nav,
@@ -8,7 +8,7 @@ import InputText from "components/Inputs/InputText";
import InputMultiSelect from "components/Inputs/InputMultiSelect";
import { ListBoxGroup } from "../ListBoxGroup";
import { filterAutomations } from "../helpers";
import { filterAutomations } from "./helpers";
import { TagDB } from "../TagDB";
import { convertGroupingToItems, makeGrouping } from "../automationGrouper";
import {
@@ -1,82 +0,0 @@
import { HassEntities } from "home-assistant-js-websocket";
import { AutomationMetadata } from "types/automations";
import { TagDB } from "./TagDB";
import { AutomationManagerAuto } from "./types";
export const consolidateAutomations = (
haEntities: HassEntities,
configAutomationMetadatas: AutomationMetadata[],
tagsDB: TagDB
): AutomationManagerAuto[] => {
const configData: Record<string, AutomationMetadata> =
configAutomationMetadatas.reduce(
(all, n) => ({
...all,
[n.id]: n,
}),
{}
);
const out = Object.entries(haEntities)
.filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation."))
.map<AutomationManagerAuto>(([entityId, entityData]) => {
const autoId = entityData.attributes.id;
let title = entityData.attributes.friendly_name ?? "";
let description = "";
let issue: string | undefined = ["on", "off"].includes(entityData.state)
? undefined
: `recived invalid state "${entityData.state}, this could be because you have a lingering automation that was not cleared by homeassistant, try to reboot HA or manually clear this automation from HA Database."`;
if (configData[autoId]) {
title = configData[entityData.attributes.id].alias ?? title;
description =
configData[entityData.attributes.id].description ?? description;
delete configData[autoId];
} else {
issue = "failed to find this automation in '/config' folder";
}
return {
id: autoId,
entityId,
title,
description,
state: entityData.state,
tags: tagsDB.getTags(autoId),
issue,
};
});
Object.values(configData).forEach((autoMetadata) => {
out.push({
id: autoMetadata.id,
entityId: "",
title: autoMetadata.alias ?? "",
description: autoMetadata.description ?? "",
state: "unregistered",
tags: tagsDB.getTags(autoMetadata.id),
issue:
"homeassistant did not load this automation, try to manually reload automations or restart homeassistant.",
});
});
return out;
};
export const filterAutomations = (
autos: AutomationManagerAuto[],
searchText: string
): AutomationManagerAuto[] =>
autos.filter((a) => {
if (searchText.length > 0) {
if (
!(
(a.description ?? "").toLocaleLowerCase().includes(searchText) ||
(a.title ?? "").toLocaleLowerCase().includes(searchText)
)
) {
return false;
}
}
return true;
});
@@ -12,12 +12,14 @@ const { make, componentMeta } = makeStory({
Component: (args: {
automations?: AutomationData[];
haProps: MockHAEntitiesProps;
}) => (
<AutomationManager
api={useMockApiService(args.automations ?? [], !args.automations)}
haEntites={useMockHAEntities(args.haProps)}
/>
),
}) => {
return (
<AutomationManager
api={useMockApiService(args.automations ?? [], !args.automations)}
haEntites={useMockHAEntities(args.haProps)}
/>
);
},
meta: {
title: "App/AutomationManager",
args: {
@@ -47,12 +47,18 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}
// alias
const configAutomations = api.state.automations.data.data;
const configAutomations = api.state.automations.data;
const hassEntities = haEntites.collection.state;
return (
<AutomationManagerLoaded
configAutomations={configAutomations}
configAutomations={configAutomations.data}
hassEntities={hassEntities}
onAutomationAdd={(auto) =>
api.updateAutomation({
index: configAutomations.totalItems + 1,
auto,
})
}
onUpdateTags={async (aid, t) => {
setIsSaving(true);
await api.updateTags({