diff --git a/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx b/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx index 4def2ea..fadb04c 100644 --- a/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx +++ b/webapp/src/components/NodeEditor/OptionManager/ActionDevice.tsx @@ -13,8 +13,16 @@ export const ActionDeviceState: OptionManager = { isReady: () => true, Component: ({ state, setState, ha }) => { const update = updateActionData(state, setState); - const options = ha.deviceExtras.useDeviceActions(state.device_id); - const caps = ha.deviceExtras.useDeviceCapalities(state as any); + const options = ha.deviceExtras.useDeviceActions( + state.device_id + ? { + deviceId: state.device_id, + } + : undefined + ); + const caps = ha.deviceExtras.useDeviceCapalities( + state.device_id && state.type && state.domain ? (state as any) : undefined + ); // aliases let actions: DeviceAction[] = []; if (options.length > 0 && state.type) { @@ -33,7 +41,7 @@ export const ActionDeviceState: OptionManager = { <> update({ device_id: device_id ?? "" })} + onChange={(device_id) => setState({ device_id: device_id ?? "" })} /> {options.length > 0 && ( { - if (errorCode === ERR_HASS_HOST_REQUIRED) { - return "Missing HASS host" - } - if (errorCode === ERR_CANNOT_CONNECT) { - return "Failed to connect" - } - if (errorCode === ERR_CONNECTION_LOST) { - return "Connection Lost" - } - if (errorCode === ERR_INVALID_AUTH) { - return "Invalid Host" - } - if (errorCode === ERR_INVALID_HTTPS_TO_HTTP) { - return "Invalid https to http" - } - return errorCode; -} + if (errorCode === ERR_HASS_HOST_REQUIRED) { + return "Missing HASS host"; + } + if (errorCode === ERR_CANNOT_CONNECT) { + return "Failed to connect"; + } + if (errorCode === ERR_CONNECTION_LOST) { + return "Connection Lost"; + } + if (errorCode === ERR_INVALID_AUTH) { + return "Invalid Host"; + } + if (errorCode === ERR_INVALID_HTTPS_TO_HTTP) { + return "Invalid https to http"; + } + return errorCode; +}; const createConnection = async () => { - try { - return _createConnection({ - auth: createLongLivedTokenAuth(wsURL, 'xxx'), - }); - } catch (error) { - // eslint-disable-next-line - throw { - originalError: JSON.stringify(error), - message: translateErrorCodes(error as any), - } - } -} + try { + return _createConnection({ + auth: createLongLivedTokenAuth(wsURL, "xxx"), + }); + } catch (error) { + // eslint-disable-next-line + throw { + originalError: JSON.stringify(error), + message: translateErrorCodes(error as any), + }; + } +}; async function startHAConnection() { - let connection: Connection; - try { - connection = await createConnection(); - } catch (error) { - haConnection = { - status: 'error', - error: { - originalError: JSON.stringify(error), - message: translateErrorCodes(error as any), - } - } - throw error - } + let connection: Connection; + try { + connection = await createConnection(); + } catch (error) { haConnection = { - status: 'loaded', - connection, - } - return haConnection; + status: "error", + error: { + originalError: JSON.stringify(error), + message: translateErrorCodes(error as any), + }, + }; + throw error; + } + haConnection = { + status: "loaded", + connection, + }; + return haConnection; } -startHAConnection().then(console.log).catch(console.error); +startHAConnection().then(console.info).catch(console.error); export const useHAConnection = (): HAConnection => { - const [conn, setConn] = useState(haConnection); - const timeID = useRef(undefined); - useEffect(() => { - if (conn.status !== haConnection.status) { - setConn(haConnection); - } - const waiter = () => { - if (conn.status !== haConnection.status) { - setConn(haConnection); - } - timeID.current = window.setTimeout(() => { - waiter() - }, conn.status === 'loading' ? 500 : 5000) - } - waiter() - return () => window.clearTimeout(timeID.current) - }, [conn, setConn]) - return conn; -}; \ No newline at end of file + const [conn, setConn] = useState(haConnection); + const timeID = useRef(undefined); + useEffect(() => { + if (conn.status !== haConnection.status) { + setConn(haConnection); + } + const waiter = () => { + if (conn.status !== haConnection.status) { + setConn(haConnection); + } + timeID.current = window.setTimeout( + () => { + waiter(); + }, + conn.status === "loading" ? 500 : 5000 + ); + }; + waiter(); + return () => window.clearTimeout(timeID.current); + }, [conn, setConn]); + return conn; +}; diff --git a/webapp/src/haService/extras.ts b/webapp/src/haService/extras.ts index 5618679..e189448 100644 --- a/webapp/src/haService/extras.ts +++ b/webapp/src/haService/extras.ts @@ -1,3 +1,4 @@ +import { MessageBase } from "home-assistant-js-websocket"; import { OptionsObject, useSnackbar } from "notistack"; import { useEffect, useRef, useState } from "react"; import { HASendMessage } from "./types"; @@ -17,68 +18,79 @@ export type DeviceTypeCapability = { }>; }; export const getDeviceExtraWsCalls = (callHA: HASendMessage) => { - return { - useDeviceActions(deviceId?: string) { - const lastDeviceId = useRef(null); - const [options, setOptions] = useState< - Array<{ - type: string; - actions: DeviceTypeAction[]; - }> - >([]); + const createUseThing = function ( + convertArgsToMessage: (a: Args) => MessageBase, + transformHAData: (ha: HAData) => STData, + defaultSTData: STData + ) { + return function useThis(args?: Args) { + const lastThing = useRef(null); + const [stData, setStData] = useState(defaultSTData); useEffect(() => { - if (deviceId && lastDeviceId.current !== deviceId) { - lastDeviceId.current = deviceId; - callHA({ - type: "device_automation/action/list", - device_id: deviceId, - }).then((data: any[]) => { - if (lastDeviceId.current === deviceId) { - const dataMap: Record = data.reduce( - (all = {}, opt: any) => { - if (!all[opt.type]) { - all[opt.type] = []; - } - all[opt.type].push(opt); - return all; - }, - {} - ); - setOptions( - Object.keys(dataMap).map((type) => ({ - type, - actions: dataMap[type], - })) - ); - } - }); - } - }, [deviceId]); - return options; - }, - useDeviceCapalities(action?: DeviceTypeAction) { - const snackbr = useSnackbar(); - const lastAction = useRef(null); - const [caps, setCaps] = useState>({}); - useEffect(() => { - const currentAction = JSON.stringify(action); - if (action && lastAction.current !== currentAction) { - lastAction.current = currentAction; - callHA({ - type: "device_automation/action/capabilities", - action, - }) - .then((data: DeviceTypeCapability) => { - if (lastAction.current === currentAction) { - setCaps(data); + const currentThing = JSON.stringify(args); + if (args && currentThing && lastThing.current !== currentThing) { + lastThing.current = currentThing; + const msg = convertArgsToMessage(args); + callHA(msg) + .then((raw: HAData) => { + if (lastThing.current === currentThing) { + setStData(transformHAData(raw)); } }) - .catch((err) => { - console.warn(err); + .catch((error) => { + console.warn({ msg, args, currentThing, error }); }); + } else if (lastThing.current !== currentThing) { + lastThing.current = currentThing; + setStData(defaultSTData); } - }, [action]); - return caps; - }, + }, [args]); + return stData; + }; + }; + + return { + useDeviceActions: createUseThing< + { deviceId: string }, + any[], + Array<{ + type: string; + actions: DeviceTypeAction[]; + }> + >( + ({ deviceId }) => ({ + type: "device_automation/action/list", + device_id: deviceId, + }), + (data) => { + const dataMap: Record = data.reduce( + (all = {}, opt: any) => { + if (!all[opt.type]) { + all[opt.type] = []; + } + all[opt.type].push(opt); + return all; + }, + {} + ); + return Object.keys(dataMap).map((type) => ({ + type, + actions: dataMap[type], + })); + }, + [] + ), + useDeviceCapalities: createUseThing< + DeviceTypeAction, + DeviceTypeCapability, + Partial + >( + (action) => ({ + type: "device_automation/action/capabilities", + action, + }), + (data) => data, + {} + ), }; }; diff --git a/webapp/src/haService/services.stories.tsx b/webapp/src/haService/services.stories.tsx index 0a72673..4548e69 100644 --- a/webapp/src/haService/services.stories.tsx +++ b/webapp/src/haService/services.stories.tsx @@ -37,7 +37,7 @@ const Test: FC = () => { // ) // }) - // console.log(flattened) + // console.info(flattened) // const summary: Record }>> = {} // const fields: Record }>> = {} diff --git a/webapp/src/haService/types.ts b/webapp/src/haService/types.ts index 5d9f105..199b22b 100644 --- a/webapp/src/haService/types.ts +++ b/webapp/src/haService/types.ts @@ -1,3 +1,5 @@ +import { MessageBase } from "home-assistant-js-websocket"; + export type EntityRegisteryItem = { area_id: null | string; config_entry_id: null | string; @@ -23,6 +25,4 @@ export type DeviceRegistryItem = { export type HassDevices = Array; export type HassEntitiesRegistry = Array; -export type HASendMessage = ( - sendMsg: { type: string } & Record -) => Promise; +export type HASendMessage = (sendMsg: MessageBase) => Promise; diff --git a/webapp/src/index.tsx b/webapp/src/index.tsx index e64eb07..05fbfe1 100644 --- a/webapp/src/index.tsx +++ b/webapp/src/index.tsx @@ -1,25 +1,24 @@ -import React from 'react'; -import ReactDOM from 'react-dom'; -import './styles/root.css'; -import App from './App'; -import reportWebVitals from './reportWebVitals'; +import React from "react"; +import ReactDOM from "react-dom"; +import "./styles/root.css"; +import App from "./App"; +import reportWebVitals from "./reportWebVitals"; ReactDOM.render( , - document.getElementById('root') + document.getElementById("root") ); // If you want to start measuring performance in your app, pass a function -// to log results (for example: reportWebVitals(console.log)) +// to log results (for example: reportWebVitals(console.info)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals -reportWebVitals(); - +reportWebVitals(console.info); // import { createRoot } from 'react-dom/client'; // const container = document.getElementById('root'); // const root = createRoot(container!); // root.render( // -// ); \ No newline at end of file +// );