diff --git a/webapp/src/components/AutomationManager/Loaded/automationDB.ts b/webapp/src/components/AutomationManager/Loaded/automationDB.ts new file mode 100644 index 0000000..96f8f44 --- /dev/null +++ b/webapp/src/components/AutomationManager/Loaded/automationDB.ts @@ -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); + + 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 = 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; +}; diff --git a/webapp/src/components/AutomationManager/Loaded/index.tsx b/webapp/src/components/AutomationManager/Loaded/index.tsx index 977c51a..6afd56b 100644 --- a/webapp/src/components/AutomationManager/Loaded/index.tsx +++ b/webapp/src/components/AutomationManager/Loaded/index.tsx @@ -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) => void; -}; +export type AutomationManagerLoadedProps = UseAutomationManagerStateArgs & {}; export const AutomationManagerLoaded: FC< PropsWithChildren -> = ({ 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 (
{children} {}} + automations={state.automations} + tagsDB={state.tagsDB} + selectedAutomationId={state.currentAutomationId} + onSelectedAutomationId={state.setSelectedAutomationId} + onAutomationAdd={() => state.addNew()} onAutomationDelete={() => {}} onAutomationUpdate={() => {}} /> -
- {state.current !== null ? ( - currentAutomation.length > 0 ? ( +
+ {state.currentAutomationId !== null ? ( + state.currentAutomation ? ( {}} - tagDB={tagsDB} + automation={state.currentAutomation} + onUpdate={state.updateAutomation} + tagDB={state.tagsDB} /> ) : (
- Failed to find an automation on disk with id {state.current}. + Failed to find an automation on disk with id{" "} + {state.currentAutomationId}.
) diff --git a/webapp/src/components/AutomationManager/Loaded/state.ts b/webapp/src/components/AutomationManager/Loaded/state.ts index c52862b..04be66e 100644 --- a/webapp/src/components/AutomationManager/Loaded/state.ts +++ b/webapp/src/components/AutomationManager/Loaded/state.ts @@ -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) => 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(initialCurrent); + const [selectedAutomation, setSelectedAutomation] = + useState(initialCurrent); return { - current, - setCurrent(i: string | null) { - setCurrent(i); + currentAutomationId: selectedAutomation, + setSelectedAutomation(i: string | null) { + setSelectedAutomation(i); setCookies("selectedAutomation", i === null ? undefined : i); }, }; diff --git a/webapp/src/components/AutomationManager/Sidebar/helpers.ts b/webapp/src/components/AutomationManager/Sidebar/helpers.ts new file mode 100644 index 0000000..5aea0d6 --- /dev/null +++ b/webapp/src/components/AutomationManager/Sidebar/helpers.ts @@ -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; + }); diff --git a/webapp/src/components/AutomationManager/Sidebar/index.css b/webapp/src/components/AutomationManager/Sidebar/index.css index d7f7769..dd5060f 100644 --- a/webapp/src/components/AutomationManager/Sidebar/index.css +++ b/webapp/src/components/AutomationManager/Sidebar/index.css @@ -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, diff --git a/webapp/src/components/AutomationManager/Sidebar/index.tsx b/webapp/src/components/AutomationManager/Sidebar/index.tsx index 17513c0..5b5a1cc 100644 --- a/webapp/src/components/AutomationManager/Sidebar/index.tsx +++ b/webapp/src/components/AutomationManager/Sidebar/index.tsx @@ -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 { diff --git a/webapp/src/components/AutomationManager/helpers.ts b/webapp/src/components/AutomationManager/helpers.ts deleted file mode 100644 index 7c4d5b6..0000000 --- a/webapp/src/components/AutomationManager/helpers.ts +++ /dev/null @@ -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 = - configAutomationMetadatas.reduce( - (all, n) => ({ - ...all, - [n.id]: n, - }), - {} - ); - - const out = Object.entries(haEntities) - .filter(([entityId, _]) => entityId.toLowerCase().startsWith("automation.")) - .map(([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; - }); diff --git a/webapp/src/components/AutomationManager/index.stories.tsx b/webapp/src/components/AutomationManager/index.stories.tsx index 06dd73f..7283515 100644 --- a/webapp/src/components/AutomationManager/index.stories.tsx +++ b/webapp/src/components/AutomationManager/index.stories.tsx @@ -12,12 +12,14 @@ const { make, componentMeta } = makeStory({ Component: (args: { automations?: AutomationData[]; haProps: MockHAEntitiesProps; - }) => ( - - ), + }) => { + return ( + + ); + }, meta: { title: "App/AutomationManager", args: { diff --git a/webapp/src/components/AutomationManager/index.tsx b/webapp/src/components/AutomationManager/index.tsx index e20e856..e7f5752 100644 --- a/webapp/src/components/AutomationManager/index.tsx +++ b/webapp/src/components/AutomationManager/index.tsx @@ -47,12 +47,18 @@ export const AutomationManager: FC = ({ } // alias - const configAutomations = api.state.automations.data.data; + const configAutomations = api.state.automations.data; const hassEntities = haEntites.collection.state; return ( + api.updateAutomation({ + index: configAutomations.totalItems + 1, + auto, + }) + } onUpdateTags={async (aid, t) => { setIsSaving(true); await api.updateTags({