diff --git a/webapp/src/components/AutomationList/AutomationMetadataBox.tsx b/webapp/src/components/AutomationList/AutomationMetadataBox.tsx index 5982997..b3afab6 100644 --- a/webapp/src/components/AutomationList/AutomationMetadataBox.tsx +++ b/webapp/src/components/AutomationList/AutomationMetadataBox.tsx @@ -6,6 +6,7 @@ import { InputAutoComplete } from "components/Inputs/InputAutoComplete"; import { TagDB } from "./TagDB"; import DeleteIcon from "@mui/icons-material/ClearTwoTone"; import { InputTextView } from "components/Inputs/InputTextView"; +import { useHAEntities } from "haService/HAEntities"; export const MetadataBox: FC<{ metadata: AutomationMetadata; diff --git a/webapp/src/components/AutomationListV2/ListBoxGroup/index.css b/webapp/src/components/AutomationListV2/ListBoxGroup/index.css new file mode 100644 index 0000000..6004bdc --- /dev/null +++ b/webapp/src/components/AutomationListV2/ListBoxGroup/index.css @@ -0,0 +1,35 @@ +.automation-list--list-box-group--title { + margin: 0.5em; +} + +.automation-list--list-box-group--title .icon { + font-size: 1.2em; +} + +.automation-list--list-box-group--title:hover, +.automation-list--list-box-group.selected .automation-list--list-box-group--title { + color: var(--mui-primary-main); + cursor: pointer; + user-select: none; +} + +.automation-list--list-box-group { + border-color: var(--mui-text-secondary); + border-width: 0.125px; + border-bottom-style: solid; + border-radius: 10px; + border-bottom-right-radius: 0; +} + +.automation-list--list-box-group--list.close { + height: 0; + opacity: 0; + display: none; +} + +.automation-list--list-box-group .automation-list--list-box-group { + margin-left: 0.5em; + margin-bottom: 0.5em; + border-left: 1px solid var(--mui-text-secondary); + border-top-left-radius: 0; +} \ No newline at end of file diff --git a/webapp/src/components/AutomationListV2/ListBoxGroup/index.stories.tsx b/webapp/src/components/AutomationListV2/ListBoxGroup/index.stories.tsx new file mode 100644 index 0000000..24c58d9 --- /dev/null +++ b/webapp/src/components/AutomationListV2/ListBoxGroup/index.stories.tsx @@ -0,0 +1,123 @@ +import "styles/root.css"; +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { Page } from "components/Page"; +import { ListBoxGroup } from "."; + +export default { + title: "App/AutomationList/ListBoxGroup", + component: ListBoxGroup, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: { + title: "Example", + type: "items", + isSelected: false, + data: [ + { + id: "1", + title: "Example", + entityId: "automation.1", + description: "Amazing automation!", + tags: {}, + state: "on", + isSelected: false, + }, + { + id: "2", + title: "Example 2", + entityId: "automation.2", + description: "Cool!", + state: "on", + isSelected: false, + tags: { + room: "main bedroom", + routine: "night time", + }, + }, + ], + }, +} as ComponentMeta; + +const Template: ComponentStory = (args) => { + return ( + + + + ); +}; + +export const Basic = Template.bind({}); +export const Nested = Template.bind({}); +Nested.args = { + title: "Top Group", + type: "group", + isSelected: false, + data: [ + { + title: "Subgroup 1", + type: "group", + isSelected: true, + data: [ + { + type: "items", + isSelected: true, + title: "Subsub group", + data: [ + { + id: "1", + entityId: "automation.1", + description: "", + title: "Automation #1", + state: "on", + isSelected: true, + tags: {}, + }, + { + id: "2", + entityId: "automation.2", + description: "another one", + title: "Automation #2", + state: "off", + isSelected: false, + tags: {}, + }, + { + id: "3", + entityId: "automation.3", + description: "bad one", + title: "Automation #3", + state: "offing", + isSelected: false, + tags: { + type: "bad", + }, + }, + ], + }, + ], + }, + { + title: "Subgroup 2", + type: "group", + isSelected: false, + data: [], + }, + { + title: "Other", + type: "items", + isSelected: false, + data: [ + { + id: "4", + entityId: "automation.4", + description: "Cool thing", + title: "Automation #4", + isSelected: false, + state: "on", + tags: { + type: "good", + }, + }, + ], + }, + ], +}; diff --git a/webapp/src/components/AutomationListV2/ListBoxGroup/index.tsx b/webapp/src/components/AutomationListV2/ListBoxGroup/index.tsx new file mode 100644 index 0000000..e318d16 --- /dev/null +++ b/webapp/src/components/AutomationListV2/ListBoxGroup/index.tsx @@ -0,0 +1,110 @@ +import "./index.css"; + +import { FC, useState } from "react"; +import { MetadataBox } from "../MetadataBox"; +import { AutomationListAutoUpdatable, AutomationListItem } from "../types"; + +export type ListBoxGroupProps = AutomationListItem & { + onTagUpdate: (t: Record, aid: string) => void; + onAutomationUpdate: ( + a: AutomationListAutoUpdatable, + aid: string, + eid: string + ) => void; + onAutomationDelete: (aid: string) => void; + onSelect: (aid: string) => void; + initialOpenState?: boolean; +}; +export const ListBoxGroup: FC = ({ + title, + type, + data, + isSelected, + initialOpenState, + ...events +}) => { + const [open, setOpen] = useState(initialOpenState ?? false); + + const openIcon = !open ? "⊕" : "⊖"; + const totalAutomations = countAutomations({ + title, + type, + data, + } as any); + + return ( +
+
setOpen(!open)} + className="automation-list--list-box-group--title" + > + {title} {openIcon} ( + {totalAutomations} automation + {totalAutomations === 1 ? "" : "s"}) +
+
+ {type === "items" + ? data.map((auto) => ( + events.onAutomationDelete(auto.id)} + onSelect={() => events.onSelect(auto.id)} + onTagUpdate={(t) => events.onTagUpdate(t, auto.id)} + onDescriptionUpdate={(description) => + events.onAutomationUpdate( + { + ...auto, + description, + }, + auto.id, + auto.entityId + ) + } + onTitleUpdate={(title) => + events.onAutomationUpdate( + { + ...auto, + title, + }, + auto.id, + auto.entityId + ) + } + onStateUpdate={(state) => + events.onAutomationUpdate( + { + ...auto, + state, + }, + auto.id, + auto.entityId + ) + } + /> + )) + : data.map((group, i) => ( + + ))} +
+
+ ); +}; + +const countAutomations = (item: AutomationListItem): number => { + if (item.type === "items") { + return item.data.length; + } else { + return item.data.reduce((total = 0, n) => total + countAutomations(n), 0); + } +}; diff --git a/webapp/src/components/AutomationListV2/MetadataBox/index.css b/webapp/src/components/AutomationListV2/MetadataBox/index.css new file mode 100644 index 0000000..51256ac --- /dev/null +++ b/webapp/src/components/AutomationListV2/MetadataBox/index.css @@ -0,0 +1,118 @@ +.automation-list--metadatabox { + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-around; + gap: 0.25em; + + padding: 0.25em; + background-color: var(--mui-background-paper); + + border-style: solid; + border-width: 1px; + border-color: transparent; + border-radius: 10px; +} + +.automation-list--metadatabox:hover, .automation-list--metadatabox.selected { + border-color: var(--mui-action-focus); + background-color: var(--mui-action-focus); +} + +.automation-list--metadatabox .metadatabox--title .input-text-view { + max-width: fit-content; +} + +.automation-list--metadatabox .metadatabox--title { + flex: 1; +} + +.automation-list--metadatabox .metadatabox--title .title { + font-size: 1.25em; + font-weight: bold; +} + +.automation-list--metadatabox .metadatabox--title .issue { + padding: 0 0.5em; + user-select: none; + max-width: fit-content; +} + +.automation-list--metadatabox .metadatabox--title .description { + font-size: 0.9em; +} + +.automation-list--metadatabox .delete:hover { + cursor: pointer; + color: var(--mui-error-light); + background-color: var(--mui-error-dark); +} + +.automation-list--metadatabox .select:hover, +.automation-list--metadatabox.selected.automation-list--metadatabox .select { + cursor: pointer; + color: var(--mui-primary-light); + background-color: var(--mui-primary-dark); +} + +.automation-list--metadatabox.selected.automation-list--metadatabox .select:hover { + color: var(--mui-secondary-light); + background-color: var(--mui-secondary-dark); + cursor: default; +} + +.automation-list--metadatabox .metadatabox--switch { + display: flex; + cursor: pointer; + flex-direction: column; + justify-content: center; + align-items: center; + text-align: center; + font-size: 0.75em; + user-select: none; + max-width: 5em; +} + +.automation-list--metadatabox .metadatabox--tags { + display: flex; + flex-direction: row; + flex-wrap: wrap; + gap: 0.25em; + margin-top: 0.25em; +} + +.automation-list--metadatabox .metadatabox--tags .tag, +.automation-list--metadatabox .metadatabox--tags .tag-add { + display: flex; + max-width: fit-content; + align-items: center; + gap: 0.25em; + + border-color: var(--mui-grey-400); + border-style: solid; + border-width: 1px; + border-radius: 0.5em; + padding: 0.1em 0.5em; +} + +.automation-list--metadatabox .metadatabox--tags .tag-add { + cursor: pointer; + color: var(--mui-success-light); + border-color: var(--mui-success-main); +} + +.automation-list--metadatabox .metadatabox--tags .tag-add:hover { + background-color: var(--mui-success-light); + color: var(--mui-success-contrastText); +} + +.automation-list--metadatabox .metadatabox--tags .tag .delete-tag { + font-size: 1em; +} + +.automation-list--metadatabox .metadatabox--tags .tag .delete-tag:hover { + cursor: pointer; + color: var(--mui-error-light); + outline: 1px solid var(--mui-error-dark); + border-radius: 20px; +} \ No newline at end of file diff --git a/webapp/src/components/AutomationListV2/MetadataBox/index.stories.tsx b/webapp/src/components/AutomationListV2/MetadataBox/index.stories.tsx new file mode 100644 index 0000000..6403add --- /dev/null +++ b/webapp/src/components/AutomationListV2/MetadataBox/index.stories.tsx @@ -0,0 +1,45 @@ +import "styles/root.css"; +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { Page } from "components/Page"; +import { MetadataBox } from "."; + +export default { + title: "App/AutomationList/MetadataBox", + component: MetadataBox, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: { + title: "Example", + description: "Cool!", + state: "on", + isSelected: false, + tags: { + room: "main bedroom", + routine: "night time", + }, + }, +} as ComponentMeta; + +const Template: ComponentStory = (args) => { + return ( + + + + ); +}; + +export const Basic = Template.bind({}); +export const IsSelected = Template.bind({}); +IsSelected.args = { + ...IsSelected.args, + isSelected: true, +}; +export const InvalidState = Template.bind({}); +InvalidState.args = { + ...InvalidState.args, + state: "unavailable", +}; +export const WithIssue = Template.bind({}); +WithIssue.args = { + ...WithIssue.args, + issue: "look at me", +}; diff --git a/webapp/src/components/AutomationListV2/MetadataBox/index.tsx b/webapp/src/components/AutomationListV2/MetadataBox/index.tsx new file mode 100644 index 0000000..eb88168 --- /dev/null +++ b/webapp/src/components/AutomationListV2/MetadataBox/index.tsx @@ -0,0 +1,101 @@ +import "./index.css"; +import { FC } from "react"; + +import Switch from "@mui/material/Switch"; +import Alert from "@mui/material/Alert"; + +import DeleteIcon from "@mui/icons-material/ClearTwoTone"; +import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; +import SelectIcon from "@mui/icons-material/HighlightAltSharp"; + +import { InputTextView } from "components/Inputs/InputTextView"; +import { ButtonIcon } from "components/Icons/ButtonIcons"; +import { cleanUpUndefined } from "components/NodeEditor/OptionManager/OptionManager"; +import { AutomationListAuto } from "../types"; + +export type MetadataBoxProps = AutomationListAuto & { + onDelete: () => void; + onSelect: () => void; + onStateUpdate: (s: "on" | "off") => void; + onTagUpdate: (t: Record) => void; + onTitleUpdate: (t: string) => void; + onDescriptionUpdate: (t: string) => void; +}; +export const MetadataBox: FC = (props) => { + const isValidState = ["on", "off"].includes(props.state); + return ( +
+
+ + props.onStateUpdate(props.state === "on" ? "off" : "on") + } + disabled={!isValidState} + color={!isValidState ? "error" : "info"} + /> + {!isValidState && `Invalid state: '${props.state}'`} +
+
+ + +
+ {Object.entries(props.tags).map(([tagName, tagValue]) => ( + + + props.onTagUpdate( + cleanUpUndefined({ + ...props.tags, + [tagName]: undefined, + }) + ) + } + className="delete-tag" + /> + {tagName}: {tagValue} + + ))} + {}}> + + + +
+ {props.issue ? ( + + {props.issue} + + ) : ( + <> + )} +
+ } + onClick={props.onSelect} + /> + } + onClick={props.onDelete} + /> +
+ ); +}; diff --git a/webapp/src/components/AutomationListV2/TagDB.ts b/webapp/src/components/AutomationListV2/TagDB.ts new file mode 100644 index 0000000..84bf3bb --- /dev/null +++ b/webapp/src/components/AutomationListV2/TagDB.ts @@ -0,0 +1,31 @@ +import { AutomationData } from "types/automations"; + +export type TagDB = ReturnType; +export const makeTagDB = (automations: AutomationData[]) => { + const allTags: Record> = {}; + const automationTags: Record> = {}; + automations.forEach(({ metadata: { id }, tags }) => { + automationTags[id] = tags; + Object.keys(tags).forEach((tagName) => { + const tagValue = tags[tagName]; + if (!allTags[tagName]) { + allTags[tagName] = new Set(); + } + allTags[tagName].add(tagValue); + }); + }); + const allTagNames = Object.keys(allTags); + return { + getTags(automationId: string) { + return automationTags[automationId] ?? {}; + }, + getTagNames(myTags: string[]): string[] { + return allTagNames.filter((n) => !myTags.includes(n)).sort(); + }, + getTagValues(tagName: string): string[] { + return allTags[tagName] + ? Array.from(allTags[tagName].values()).sort() + : []; + }, + }; +}; diff --git a/webapp/src/components/AutomationListV2/automationGrouper.test.ts b/webapp/src/components/AutomationListV2/automationGrouper.test.ts new file mode 100644 index 0000000..79911d9 --- /dev/null +++ b/webapp/src/components/AutomationListV2/automationGrouper.test.ts @@ -0,0 +1,137 @@ +import { convertGroupingToItems, makeGrouping } from "./automationGrouper"; +import { bigMockAutoList, createMockAuto } from "utils/mocks"; +import { AutomationListAuto } from "./types"; + +const automations: AutomationListAuto[] = [ + createMockAuto({ + Room: "Living Room", + Type: "Lights", + }), + createMockAuto({ + Room: "Living Room", + Type: "Climate", + }), + createMockAuto({ + Room: "Kitchen", + Type: "Climate", + }), + createMockAuto({ + Type: "Climate", + }), + createMockAuto({ + Room: "Living Room", + }), + createMockAuto({}), +].map((a) => ({ + title: a.metadata.alias ?? "", + entityId: "automation." + a.metadata.id, + description: a.metadata.description ?? "", + state: "on", + tags: a.tags, + id: a.metadata.id, + isSelected: false, +})); + +const bigList = bigMockAutoList.map((a) => ({ + entityId: "automation." + a.metadata.id, + title: a.metadata.alias ?? "", + description: a.metadata.description ?? "", + state: "on", + tags: a.tags, + id: a.metadata.id, + isSelected: false, +})); + +test("no grouping", () => { + const grouped = makeGrouping(automations, [], automations[0].id); + expect(grouped.top).toStrictEqual([0]); + expect(grouped.getAutomations(0)).toStrictEqual([0, 1, 2, 3, 4, 5]); +}); +test("1 grouping", () => { + const grouped = makeGrouping(automations, ["Room"], automations[0].id); + expect(grouped.top).toHaveLength(3); + expect(grouped.getAutomations(0)).toStrictEqual([0, 1, 4]); + expect(grouped.getAutomations(1)).toStrictEqual([2]); + expect(grouped.getAutomations(2)).toStrictEqual([3, 5]); +}); +test("2 groupings", () => { + const grouped = makeGrouping( + automations, + ["Room", "Type"], + automations[0].id + ); + expect(grouped.top).toHaveLength(3); + expect(grouped.getAutomations(grouped.top[0])).toHaveLength(0); + expect(grouped.getSubGroups(grouped.top[0])).toHaveLength(3); + expect(grouped.getAutomations(grouped.top[1])).toHaveLength(0); + expect(grouped.getSubGroups(grouped.top[1])).toHaveLength(1); + expect(grouped.getAutomations(grouped.top[2])).toHaveLength(2); + expect(grouped.getSubGroups(grouped.top[2])).toHaveLength(0); +}); +test("bigAutoList groupings has not duplicate ids", () => { + const grouped = makeGrouping(bigList, ["Room", "Remote"], bigList[0].id); + const flattenAndCount = (gid: number): Record => { + const subgroups = grouped.getSubGroups(gid); + if (subgroups.length > 0) { + return flattenAndConsolidate(subgroups); + } else { + return grouped + .getAutomations(gid) + .reduce((sum: Record, b) => { + sum[b] = (sum[b] ?? []).concat(gid); + return sum; + }, {}); + } + }; + const flattenAndConsolidate = (gids: number[]): Record => + gids.map(flattenAndCount).reduce((a, b) => { + for (const k of Object.keys(b).map(Number)) { + a[k] = (a[k] ?? []).concat(b[k]); + } + return a; + }, {}); + const countedAutos = flattenAndConsolidate(grouped.top); + for (const key of Object.keys(countedAutos).map(Number)) { + expect(countedAutos[key]).toHaveLength(1); + } +}); + +test("convert grouper to items when no tags are selected", () => { + const grouping = makeGrouping(automations, [], null); + const items = grouping.top.map((i) => + convertGroupingToItems(i, automations, grouping) + ); + expect(items.filter((i) => i.type === "group")).toHaveLength(0); + expect(items).toHaveLength(1); + expect(items[0].data).toHaveLength(automations.length); +}); + +test("convert grouper to items when 1 tag is selected", () => { + const grouping = makeGrouping(automations, ["Room"], null); + const items = grouping.top.map((i) => + convertGroupingToItems(i, automations, grouping) + ); + expect(grouping.top).toHaveLength(3); + expect(items.filter((i) => i.type === "group")).toHaveLength(0); + expect(items).toHaveLength(3); + expect(items[0].data).toHaveLength(3); + expect(items[1].data).toHaveLength(1); + expect(items[2].data).toHaveLength(2); + expect(items[0].title).toEqual("Living Room"); + expect(items[1].title).toEqual("Kitchen"); + expect(items[2].title).toEqual(""); +}); + +test("convert grouper to items when 2 tag is selected", () => { + const grouping = makeGrouping(automations, ["Room", "Type"], null); + const items = grouping.top.map((i) => + convertGroupingToItems(i, automations, grouping) + ); + expect(grouping.top).toHaveLength(3); + expect(items.filter((i) => i.type === "group")).toHaveLength(2); + expect(items.filter((i) => i.type === "items")).toHaveLength(1); + expect(items).toHaveLength(3); + expect(items[0].data).toHaveLength(3); + expect(items[1].data).toHaveLength(1); + expect(items[2].data).toHaveLength(2); +}); diff --git a/webapp/src/components/AutomationListV2/automationGrouper.tsx b/webapp/src/components/AutomationListV2/automationGrouper.tsx new file mode 100644 index 0000000..620cb4b --- /dev/null +++ b/webapp/src/components/AutomationListV2/automationGrouper.tsx @@ -0,0 +1,173 @@ +import { AutomationListAuto, AutomationListItem } from "./types"; + +const makeGrouper = () => { + const groupIdNames: string[] = []; + const groupSubGroups: Array> = []; // groupIdx => Array + const groupAutomations: number[][] = []; // groupIdx => Array + const groupData: Array<{ + name: string; + selected: boolean; + isOther: boolean; + isTop: boolean; + }> = []; // source of truth for groupIdx + const topGroups: number[] = []; + + return { + groupIdNames, + groupSubGroups, + groupAutomations, + groupData, + topGroups, + addNew( + groupId: string, + groupName: string, + theChosenOne: boolean, + isTopLevel: boolean, + isOther: boolean = false + ): number { + groupIdNames.push(groupId); + groupSubGroups.push(new Set()); + groupAutomations.push([]); + groupData.push({ + name: groupName, + selected: theChosenOne, + isTop: isTopLevel, + isOther, + }); + const groupIdx = groupIdNames.length - 1; + if (isTopLevel) { + topGroups.push(groupIdx); + } + return groupIdx; + }, + updateGroup( + groupIdx: number, + update: { + isChosen: boolean; + lastGroupIdx: number | null; + autoIdx: number | null; + } + ) { + if (update.isChosen) { + groupData[groupIdx].selected = true; + } + if (update.lastGroupIdx !== null) { + groupSubGroups[update.lastGroupIdx].add(groupIdx); + } + if (update.autoIdx !== null) { + groupAutomations[groupIdx].push(update.autoIdx); + } + }, + }; +}; + +export type AutomationGrouping = ReturnType; +export const makeGrouping = ( + autos: AutomationListAuto[], + selectedTags: string[], + selectedAutomationId: string | null +) => { + const grouper = makeGrouper(); + + if (selectedTags.length === 0) { + grouper.addNew("$", "", selectedAutomationId !== null, true, true); + grouper.groupAutomations = [autos.map((_, i) => i)]; + } else { + autos.forEach((auto, autoIdx) => { + const theChosenOne = selectedAutomationId === auto.id; + let lastGroupIdx: number | null = null; + let lastGroupId: string = "$"; + for (let ti = 0; ti < selectedTags.length; ti++) { + const isTopLevel = ti === 0; + const selTag = selectedTags[ti]; + if (selTag in auto.tags) { + const groupName = auto.tags[selTag]; + const groupId = `${lastGroupId}>${selTag}:${groupName}`; + let groupIdx = grouper.groupIdNames.indexOf(groupId); + if (groupIdx < 0) { + groupIdx = grouper.addNew( + groupId, + groupName, + theChosenOne, + isTopLevel + ); + } + grouper.updateGroup(groupIdx, { + isChosen: theChosenOne, + lastGroupIdx, + autoIdx: ti === selectedTags.length - 1 ? autoIdx : null, + }); + lastGroupIdx = groupIdx; + lastGroupId = groupId; + } else { + const groupId = `${lastGroupId}>${selTag}:$`; + let groupIdx = grouper.groupIdNames.indexOf(groupId); + if (groupIdx < 0) { + groupIdx = grouper.addNew( + groupId, + "", + theChosenOne, + isTopLevel, + true + ); + } + grouper.updateGroup(groupIdx, { + isChosen: theChosenOne, + lastGroupIdx, + autoIdx, + }); + break; + } + } + }); + } + const sortGroupIds = (groupIds: number[]) => + groupIds.sort((a, b) => { + const adata = grouper.groupData[a]; + const bdata = grouper.groupData[b]; + if (adata.isOther) { + return 1; + } else { + return adata.name > bdata.name ? -1 : 1; + } + }); + return { + top: sortGroupIds(grouper.topGroups), + getSubGroups(groupIdx: number) { + return sortGroupIds( + Array.from(grouper.groupSubGroups[groupIdx].values()) + ); + }, + getAutomations(groupIdx: number) { + return grouper.groupAutomations[groupIdx]; + }, + getData(groupIdx: number) { + return grouper.groupData[groupIdx]; + }, + }; +}; + +export const convertGroupingToItems = ( + currentGroupIdx: number, + autos: AutomationListAuto[], + grouping: AutomationGrouping +): AutomationListItem => { + const groupData = grouping.getData(currentGroupIdx); + const automationIds = grouping.getAutomations(currentGroupIdx); + + if (automationIds.length > 0) { + return { + type: "items", + title: groupData.name, + data: automationIds.map((i) => autos[i]), + isSelected: groupData.selected, + }; + } + const subgroups = grouping.getSubGroups(currentGroupIdx); + return { + type: "group", + title: groupData.name, + data: subgroups.map((i) => convertGroupingToItems(i, autos, grouping)), + isSelected: groupData.selected, + }; +}; diff --git a/webapp/src/components/AutomationListV2/helpers.ts b/webapp/src/components/AutomationListV2/helpers.ts new file mode 100644 index 0000000..253eba0 --- /dev/null +++ b/webapp/src/components/AutomationListV2/helpers.ts @@ -0,0 +1,85 @@ +import { HassEntities } from "home-assistant-js-websocket"; +import { AutomationMetadata } from "types/automations"; +import { TagDB } from "./TagDB"; +import { AutomationListAuto } from "./types"; + +export const consolidateAutomations = ( + haEntities: HassEntities, + configAutomationMetadatas: AutomationMetadata[], + selectedAutomationId: string, + tagsDB: TagDB +): AutomationListAuto[] => { + 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, + isSelected: selectedAutomationId === autoId, + }; + }); + + Object.values(configData).forEach((autoMetadata) => { + out.push({ + id: autoMetadata.id, + entityId: "", + title: autoMetadata.alias ?? "", + description: autoMetadata.description ?? "", + state: "unregistered", + tags: tagsDB.getTags(autoMetadata.id), + isSelected: selectedAutomationId === autoMetadata.id, + issue: + "homeassistant did not load this automation, try to manually reload automations or restart homeassistant.", + }); + }); + + return out; +}; + +export const filterAutomations = ( + autos: AutomationListAuto[], + searchText: string +): AutomationListAuto[] => + 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/AutomationListV2/index.css b/webapp/src/components/AutomationListV2/index.css new file mode 100644 index 0000000..76dee87 --- /dev/null +++ b/webapp/src/components/AutomationListV2/index.css @@ -0,0 +1,12 @@ +.automation-list.loading { + min-height: 100%; + height: 100%; + max-height: 100vh; + margin-left: 5em; + margin-right: 5em; +} + +.automation-list { + max-height: 100vh; + overflow: auto; +} \ No newline at end of file diff --git a/webapp/src/components/AutomationListV2/index.stories.tsx b/webapp/src/components/AutomationListV2/index.stories.tsx new file mode 100644 index 0000000..ebba24a --- /dev/null +++ b/webapp/src/components/AutomationListV2/index.stories.tsx @@ -0,0 +1,124 @@ +import "styles/root.css"; +import { ComponentMeta, ComponentStory } from "@storybook/react"; +import { Page } from "components/Page"; +import { AutomationList } from "."; +import { createHAEntitiesState, useHAEntities } from "haService/HAEntities"; +import { makeTagDB } from "./TagDB"; +import { useConnectedApiService } from "apiService"; +import { useMockHAEntities } from "haService/HAEntities.mock"; +import { createMockAuto } from "utils/mocks"; +import { useState } from "react"; + +export default { + title: "App/AutomationList", + component: AutomationList, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: { + title: "Example", + description: "Cool!", + state: "on", + tags: { + room: "main bedroom", + routine: "night time", + }, + }, +} as ComponentMeta; + +export const Loading: ComponentStory = (args) => { + return ( + + + + ); +}; + +export const Mocked: ComponentStory = (args) => { + const [mockAutos, setAutos] = useState([ + createMockAuto({ room: "bedroom" }), + createMockAuto({ room: "bathroom", type: "routine" }), + createMockAuto({ type: "routine" }), + createMockAuto(), + createMockAuto({ type: "missing in ws" }), + ]); + const [mockEntitiesStates, setMES] = useState>({ + ...mockAutos.slice(0, 4).reduce((all, auto, i) => { + const eid = `automation.number_${i}`; + return { + ...all, + [eid]: i % 2 == 0 ? "on" : "off", + }; + }, {}), + "automation.number_not_in_config": "on", + }); + const mockEntities = mockAutos.slice(0, 4).reduce((all, auto, i) => { + const eid = `automation.number_${i}`; + return { + ...all, + [eid]: { + entity_id: eid, + attributes: { + id: auto.metadata.id, + }, + state: mockEntitiesStates[eid] ?? "n/a", + }, + }; + }, {}); + const haEntities = useMockHAEntities({ + loading: false, + entities: { + ...mockEntities, + "automation.number_not_in_config": { + entity_id: "automation.number_not_in_config", + state: mockEntitiesStates["automation.number_not_in_config"] ?? "n/a", + attributes: { + id: "1235", + friendly_name: "What am I?", + }, + } as any, + }, + entitySource: {}, + }); + return ( + + metadata)} + onAutomationDelete={(aid) => { + args.onAutomationDelete(aid); + setAutos(mockAutos.filter(({ metadata }) => metadata.id !== aid)); + }} + onAutomationUpdate={(a, aid, eid) => { + args.onAutomationUpdate(a, aid, eid); + const index = mockAutos.findIndex( + ({ metadata }) => metadata.id === aid + ); + if (index >= 0) { + setAutos([ + ...mockAutos.slice(0, index), + { + ...mockAutos[index], + metadata: { + ...mockAutos[index].metadata, + alias: a.title, + description: a.description, + }, + }, + ...mockAutos.slice(index + 1), + ]); + } + setMES({ + ...mockEntitiesStates, + [eid]: a.state, + }); + }} + onTagUpdate={() => {}} + /> + + ); +}; diff --git a/webapp/src/components/AutomationListV2/index.tsx b/webapp/src/components/AutomationListV2/index.tsx new file mode 100644 index 0000000..0a0b01f --- /dev/null +++ b/webapp/src/components/AutomationListV2/index.tsx @@ -0,0 +1,92 @@ +import "./index.css"; + +import { FC, useState } from "react"; + +import Skeleton from "@mui/material/Skeleton"; + +import { HAEntitiesState } from "haService/HAEntities"; +import { AutomationMetadata } from "types/automations"; +import InputText from "components/Inputs/InputText"; +import InputMultiSelect from "components/Inputs/InputMultiSelect"; + +import { ListBoxGroup } from "./ListBoxGroup"; +import { consolidateAutomations, filterAutomations } from "./helpers"; +import { TagDB } from "./TagDB"; +import { convertGroupingToItems, makeGrouping } from "./automationGrouper"; +import { AutomationListAutoUpdatable } from "./types"; + +export type AutomationListProps = { + configAutomationMetadatas: AutomationMetadata[]; + tagsDB: TagDB; + haEntites: HAEntitiesState; + onTagUpdate: (t: Record, aid: string) => void; + onAutomationUpdate: ( + a: AutomationListAutoUpdatable, + aid: string, + eid: string + ) => void; + onAutomationDelete: (aid: string) => void; +}; +export const AutomationList: FC = ({ + configAutomationMetadatas, + tagsDB, + haEntites, + ...events +}) => { + const [searchText, setSearchText] = useState(""); + const [selectedTagIdx, setSelectedTagIdx] = useState([]); + const [selectedAutomationId, setSelectedAutomationId] = + useState(null); + + if (!haEntites.ready) { + return ; + } + const tags = tagsDB.getTagNames([]); + let automations = consolidateAutomations( + haEntites.collection.state, + configAutomationMetadatas, + selectedAutomationId ?? "", + tagsDB + ); + + if (searchText.trim().length > 0) { + automations = filterAutomations( + automations, + searchText.toLocaleLowerCase() + ); + } + + const grouping = makeGrouping( + automations, + selectedTagIdx.map((i) => tags[i]), + selectedAutomationId + ); + + const items = grouping.top.map((i) => + convertGroupingToItems(i, automations, grouping) + ); + + return ( +
+
+ + +
+ {items.map((item, i) => ( + + ))} +
+ ); +}; diff --git a/webapp/src/components/AutomationListV2/types.ts b/webapp/src/components/AutomationListV2/types.ts new file mode 100644 index 0000000..e5f58c5 --- /dev/null +++ b/webapp/src/components/AutomationListV2/types.ts @@ -0,0 +1,26 @@ +export type AutomationListAutoUpdatable = { + title: string; + description: string; + state: "on" | "off" | string; +}; +export type AutomationListAuto = AutomationListAutoUpdatable & { + id: string; + entityId: string; + tags: Record; + issue?: string; + isSelected: boolean; +}; + +export type AutomationListItem = { + title: string; + isSelected: boolean; +} & ( + | { + type: "group"; + data: Array; + } + | { + type: "items"; + data: Array; + } +); diff --git a/webapp/src/components/DAGGraph/index.tsx b/webapp/src/components/DAGGraph/index.tsx index 6aaf943..1c8a996 100644 --- a/webapp/src/components/DAGGraph/index.tsx +++ b/webapp/src/components/DAGGraph/index.tsx @@ -19,7 +19,6 @@ export const DAGAutomationGraph: FC<{ isFlipped: boolean; additionalControls?: ReactNode; }> = (props) => { - console.log({ props }); const { namer } = useHA(); const [modalState, setModalState] = useState(undefined); diff --git a/webapp/src/components/Inputs/InputTextView.tsx b/webapp/src/components/Inputs/InputTextView.tsx index 7b09646..672af06 100644 --- a/webapp/src/components/Inputs/InputTextView.tsx +++ b/webapp/src/components/Inputs/InputTextView.tsx @@ -1,6 +1,6 @@ import "./InputTextView.css"; -import { FC, useState } from "react"; +import { FC, PropsWithChildren, useState } from "react"; import CheckCircleOutlineOutlinedIcon from "@mui/icons-material/CheckCircleOutlineOutlined"; import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined"; import TextField from "@mui/material/TextField"; @@ -13,9 +13,11 @@ export type InputTextViewProps = { placeholder?: string; }; -export const InputTextView: FC = (props) => { +export const InputTextView: FC> = ( + props +) => { const [viewMode, setViewMode] = useState(props.initialViewMode ?? true); - + const [text, setText] = useState(props.value); const className = [ "input-text-view", viewMode ? "view" : "edit", @@ -33,6 +35,7 @@ export const InputTextView: FC = (props) => { )} + {props.children} ); } else { @@ -41,11 +44,19 @@ export const InputTextView: FC = (props) => { className={className} placeholder={props.placeholder} variant="filled" - value={props.value} - onChange={(e) => props.onChange(e.target.value)} + value={text} + onChange={(e) => setText(e.target.value)} InputProps={{ endAdornment: ( - setViewMode(true)} /> + <> + { + setViewMode(true); + props.onChange(text); + }} + /> + {props.children} + ), }} /> diff --git a/webapp/src/components/Page/index.css b/webapp/src/components/Page/index.css index d956ed1..a60d3ed 100644 --- a/webapp/src/components/Page/index.css +++ b/webapp/src/components/Page/index.css @@ -11,8 +11,8 @@ /* font */ font-size: 16px; font-family: Tahoma, Geneva, sans-serif; - /* color : var(--mui-grey-400); */ + color: var(--mui-text-primary); /* background */ - /* background-color: var(--mui-common-black); */ + background-color: var(--mui-background-default); } \ No newline at end of file diff --git a/webapp/src/components/Page/index.tsx b/webapp/src/components/Page/index.tsx index b2618b7..8913a5a 100644 --- a/webapp/src/components/Page/index.tsx +++ b/webapp/src/components/Page/index.tsx @@ -66,13 +66,7 @@ export const InternalPage: FC<{ }, [conn, snackbar]); return ( -
+