- refactor for multi-config suport done

- added better errror captures
This commit is contained in:
ari committed 2022-08-16 11:40:30 -04:00
1 parent 55ea1e23a4
commit c67d1bd32f
32 files changed
+991 -835

No files matched your search

@@ -46,10 +46,10 @@ export const useAutomationDB = (
const auto = defaultAutomation(String(Date.now()));
setNewAuto([
{
id: auto.metadata.id,
id: auto.id,
entityId: "",
title: auto.metadata.alias ?? "",
description: auto.metadata.description ?? "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: "unregistered",
tags: {},
issue: "New Automation",
@@ -70,7 +70,7 @@ const genMapping = (
const configData: Record<string, AutomationData> = configAutomations.reduce(
(all, n) => ({
...all,
[n.metadata.id]: n,
[n.id]: n,
}),
{}
);
@@ -91,8 +91,8 @@ const genMapping = (
if (configData[autoId]) {
found = configData[entityData.attributes.id];
title = found.metadata.alias ?? title;
description = found.metadata.description ?? description;
title = found.alias ?? title;
description = found.description ?? description;
delete configData[autoId];
} else {
issue = "failed to find this automation in '/config' folder";
@@ -113,14 +113,14 @@ const genMapping = (
});
Object.values(configData).forEach((auto) => {
automatioinMap[auto.metadata.id] = [
automatioinMap[auto.id] = [
{
id: auto.metadata.id,
id: auto.id,
entityId: "",
title: auto.metadata.alias ?? "",
description: auto.metadata.description ?? "",
title: auto.alias ?? "",
description: auto.description ?? "",
state: "unregistered",
tags: tagsDB.getTags(auto.metadata.id),
tags: tagsDB.getTags(auto.id),
issue:
"homeassistant did not load this automation, try to manually reload automations or restart homeassistant.",
},
@@ -13,7 +13,7 @@ export type UseAutomationManagerStateArgs = {
hassEntities: HassEntities;
onUpdateTags: (aid: string, tags: Record<string, string>) => void;
onAutomationAdd: (auto: AutomationData) => void;
onAutomationUpdate: (aid: string, auto: AutomationData) => void;
onAutomationUpdate: (auto: AutomationData) => void;
onAutomationStateChange: (eid: string, on: boolean) => void;
onAutomationRun: (eid: string) => void;
};
@@ -30,10 +30,12 @@ export const useAutomationManagerState = ({
const snackbr = useSnackbar();
const cookies = useAMSCookies();
const tagsDB = useTagDB(
configAutomations.map(({ metadata: { id }, tags }) => ({
id,
tags,
})),
configAutomations
.filter((a) => typeof a === "object")
.map(({ id, tags = {} }) => ({
id,
tags,
})),
onUpdateTags
);
const automationDB = useAutomationDB(hassEntities, configAutomations, tagsDB);
@@ -91,13 +93,13 @@ export const useAutomationManagerState = ({
}
}
const auto = automationDB.addNew();
methods.setSelectedAutomationId(auto.metadata.id, true);
methods.setSelectedAutomationId(auto.id, true);
},
editorUpdateAutomation(auto: AutomationData) {
if (methods.currentAutomationIsNew) {
onAutomationAdd(auto);
} else if (methods.currentAutomationId) {
onAutomationUpdate(methods.currentAutomationId, auto);
onAutomationUpdate(auto);
}
},
sideBarUpdateAutomation(
@@ -109,16 +111,13 @@ export const useAutomationManagerState = ({
if (previousAuto && previousAuto[1]) {
const previousAutoState = previousAuto[1];
if (
previousAutoState.metadata.alias !== a.title ||
previousAutoState.metadata.description !== a.description
previousAutoState.alias !== a.title ||
previousAutoState.description !== a.description
) {
onAutomationUpdate(aid, {
onAutomationUpdate({
...previousAutoState,
metadata: {
...previousAutoState.metadata,
alias: a.title,
description: a.description,
},
alias: a.title,
description: a.description,
});
}
} else {
@@ -4,41 +4,51 @@ import { AutomationManagerAuto } from "./types";
const automations: AutomationManagerAuto[] = [
createMockAuto({
Room: "Living Room",
Type: "Lights",
tags: {
Room: "Living Room",
Type: "Lights",
},
}),
createMockAuto({
Room: "Living Room",
Type: "Climate",
tags: {
Room: "Living Room",
Type: "Climate",
},
}),
createMockAuto({
Room: "Kitchen",
Type: "Climate",
tags: {
Room: "Kitchen",
Type: "Climate",
},
}),
createMockAuto({
Type: "Climate",
tags: {
Type: "Climate",
},
}),
createMockAuto({
Room: "Living Room",
tags: {
Room: "Living Room",
},
}),
createMockAuto({}),
].map<AutomationManagerAuto>((a) => ({
title: a.metadata.alias ?? "",
entityId: "automation." + a.metadata.id,
description: a.metadata.description ?? "",
title: a.alias ?? "",
entityId: "automation." + a.id,
description: a.description ?? "",
state: "on",
tags: a.tags,
id: a.metadata.id,
id: a.id,
isSelected: false,
}));
const bigList = bigMockAutoList.map<AutomationManagerAuto>((a) => ({
entityId: "automation." + a.metadata.id,
title: a.metadata.alias ?? "",
description: a.metadata.description ?? "",
entityId: "automation." + a.id,
title: a.alias ?? "",
description: a.description ?? "",
state: "on",
tags: a.tags,
id: a.metadata.id,
id: a.id,
isSelected: false,
}));
@@ -23,4 +23,22 @@
.automation-manager.loading .automation-manager--editor.loading {
flex: 1;
height: 100%;
}
.invalid-automation-modal-list {
display: flex;
max-height: 50vh;
overflow: auto;
flex-direction: column;
}
.invalid-automation-modal-list li {
display: flex;
flex-direction: column;
}
.invalid-automation-modal-list--errors ul {
max-height: 10vh;
overflow: auto;
}
@@ -79,17 +79,17 @@ export const Empty = make({
},
});
const auto1 = createMockAuto({
type: "button",
tags: { type: "button" },
});
export const One = make({
automations: [auto1],
haProps: {
loading: false,
entities: {
[`automation.${auto1.metadata.id}`]: {
entity_id: `automation.${auto1.metadata.id}`,
[`automation.${auto1.id}`]: {
entity_id: `automation.${auto1.id}`,
attributes: {
id: auto1.metadata.id,
id: auto1.id,
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
@@ -105,11 +105,11 @@ export const MissingAutoInConfig = make({
haProps: {
loading: false,
entities: {
[`automation.${auto1.metadata.id}`]: {
entity_id: `automation.${auto1.metadata.id}`,
[`automation.${auto1.id}`]: {
entity_id: `automation.${auto1.id}`,
attributes: {
id: auto1.metadata.id,
friendly_name: auto1.metadata.alias,
id: auto1.id,
friendly_name: auto1.alias,
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
@@ -120,12 +120,22 @@ export const MissingAutoInConfig = make({
entitySource: {},
},
});
export const CrashingAutomations = make({
haProps: {
loading: false,
entities: {},
entitySource: {},
},
automations: [""] as any,
});
export const BadAutomation = make({
haProps: {
loading: false,
entities: {
[`automation.${auto1.metadata.id}`]: {
entity_id: `automation.${auto1.metadata.id}`,
[`automation.${auto1.id}`]: {
entity_id: `automation.${auto1.id}`,
attributes: {
id: "test",
},
@@ -140,12 +150,10 @@ export const BadAutomation = make({
automations: [
{
tags: {},
metadata: {
id: "test",
mode: "single",
alias: "Light.Tank_Day",
description: "",
},
id: "test",
mode: "single",
alias: "Light.Tank_Day",
description: "",
trigger: [
{
platform: "sun",
@@ -155,7 +163,7 @@ export const BadAutomation = make({
{ whoAmI: "bad node is who" } as any,
],
condition: [{ whoAmI: "bad node is who" } as any],
sequence: [
action: [
{ scene: "scene.light_day" } as any,
{ whoAmI: "bad node is who" } as any,
{
@@ -171,3 +179,40 @@ export const BadAutomation = make({
},
],
});
export const OneCrashingOneGoodAutomations = make({
haProps: {
loading: false,
entities: {
[`automation.${auto1.id}`]: {
entity_id: `automation.${auto1.id}`,
attributes: {
id: auto1.id,
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
last_updated: "",
state: "on",
},
"1235": {
entity_id: `automation.1235`,
attributes: {
id: "1235",
},
context: { id: "", parent_id: null, user_id: null },
last_changed: "",
last_updated: "",
state: "on",
},
},
entitySource: {},
},
automations: [
auto1,
{
id: "1235",
tags: {},
} as any,
"" as any,
],
});
+135 -70
View File
@@ -1,6 +1,6 @@
import "./index.css";
import { FC, useEffect, useState } from "react";
import { FC, useEffect, useRef, useState } from "react";
import LinearProgress from "@mui/material/LinearProgress";
import Skeleton from "@mui/material/Skeleton";
@@ -9,6 +9,11 @@ import { HAEntitiesState } from "haService/HAEntities";
import { AutomationManagerLoaded } from "./Loaded";
import { Alert } from "@mui/material";
import { useSnackbar } from "notistack";
import { ErrorBoundary } from "components/ErrorBoundary";
import { getFailures } from "types/validators/helper";
import * as av from "types/validators/autmation";
import { useConfirm } from "material-ui-confirm";
import InputYaml from "components/Inputs/Base/InputYaml";
export type AutomationManagerProps = {
onAutomationStateChange: (eid: string, on: boolean) => void;
@@ -28,6 +33,8 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
triggerAutomation,
}) => {
const snackbr = useSnackbar();
const confirm = useConfirm();
const validationsShown = useRef(false);
const [isSaving, setIsSaving] = useState(false);
useEffect(() => {
@@ -35,6 +42,68 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
// eslint-disable-next-line
}, []);
useEffect(() => {
if (
api.state.automations.ready &&
api.state.automations.ok &&
!validationsShown.current
) {
const configAutomationsValidated = api.state.automations.data.data.map(
(a) => {
const failures = getFailures(a, av.AutomationData);
return {
automation: a,
failures,
};
}
);
const invalidAutomations = configAutomationsValidated.filter(
({ failures }) => failures !== null
);
if (invalidAutomations.length > 0) {
validationsShown.current = true;
confirm({
cancellationButtonProps: {
style: { display: "none" },
},
title: "Invalid Automations detected!",
content: (
<>
<ol className="invalid-automation-modal-list">
{invalidAutomations.map(({ automation, failures }, i) => (
<li key={i}>
<b>Automation</b>
<InputYaml
label=""
value={automation}
onChange={() => {}}
/>
<b>Errors</b>
<Alert
color="error"
className="invalid-automation-modal-list--errors"
>
<ul>
{failures &&
failures.map((f, fi) => (
<li key={fi}>
<b>{f.path}</b>: {f.message.join(", ")}
</li>
))}
</ul>
</Alert>
</li>
))}
</ol>
</>
),
})
.then(console.info)
.catch(console.error);
}
}
}, [api.state.automations, validationsShown.current]);
// handle bad states
if (!haEntities.ready && haEntities.error) {
return (
@@ -75,78 +144,74 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
}
// alias
const configAutomations = api.state.automations.data;
const hassEntities = haEntities.collection;
const configAutomations = api.state.automations.data;
return (
<AutomationManagerLoaded
configAutomations={configAutomations.data}
hassEntities={hassEntities}
onAutomationRun={triggerAutomation}
onAutomationStateChange={onAutomationStateChange}
onAutomationAdd={async (auto) => {
await api.updateAutomation({
index: configAutomations.totalItems + 1,
auto,
});
refreshAutomations();
}}
onAutomationDelete={(aid, eid) => {
const index = configAutomations.data.findIndex(
({ metadata }) => metadata.id === aid
);
let deleteSent = false;
if (index >= 0) {
api.removeAutomation({
index,
});
deleteSent = true;
}
const hassAuto = hassEntities[eid];
if (hassAuto) {
forceDeleteAutomation(eid);
deleteSent = true;
}
if (!deleteSent) {
snackbr.enqueueSnackbar(
"Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant",
{
variant: "error",
}
);
}
// refreshAutomations();
}}
onAutomationUpdate={(aid, auto) => {
const index = configAutomations.data.findIndex(
({ metadata }) => metadata.id === aid
);
if (index >= 0) {
api.updateAutomation({
index: configAutomations.data.findIndex(
({ metadata }) => metadata.id === aid
),
auto,
});
refreshAutomations();
} else {
snackbr.enqueueSnackbar(
"Failed to update automation, this may be resolved by a refresh or reboot of Home Assistant.",
{
variant: "error",
}
);
}
}}
onUpdateTags={async (aid, t) => {
setIsSaving(true);
await api.updateTags({
automation_id: aid,
tags: t,
});
setIsSaving(false);
<ErrorBoundary
additionalContext={{
configAutomations,
hassEntities,
}}
>
{isSaving && <LinearProgress />}
</AutomationManagerLoaded>
<AutomationManagerLoaded
configAutomations={configAutomations.data}
hassEntities={hassEntities}
onAutomationRun={triggerAutomation}
onAutomationStateChange={onAutomationStateChange}
onAutomationAdd={async (auto) => {
await api.updateAutomation(auto);
refreshAutomations();
}}
onAutomationDelete={(aid, eid) => {
const autoToDelete = configAutomations.data.find(
({ id }) => id === aid
);
let deleteSent = false;
if (autoToDelete) {
api.removeAutomation(autoToDelete);
deleteSent = true;
}
const hassAuto = hassEntities[eid];
if (hassAuto) {
forceDeleteAutomation(eid);
deleteSent = true;
}
if (!deleteSent) {
snackbr.enqueueSnackbar(
"Failed to delete automation, this may be resolved by a refresh or reboot of Home Assistant",
{
variant: "error",
}
);
}
// refreshAutomations();
}}
onAutomationUpdate={(auto) => {
api
.updateAutomation(auto)
.then(() => refreshAutomations())
.catch(() => {
snackbr.enqueueSnackbar(
"Failed to update automation, this may be resolved by a refresh or reboot of Home Assistant.",
{
variant: "error",
}
);
});
}}
onUpdateTags={async (aid, t) => {
setIsSaving(true);
await api.updateTags({
automation_id: aid,
tags: t,
});
setIsSaving(false);
}}
>
{isSaving && <LinearProgress />}
</AutomationManagerLoaded>
</ErrorBoundary>
);
};