@adcops/autocore-react 3.0.16 → 3.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -152,6 +152,7 @@ export declare class ValueInput extends React.Component<ValueInputProps, ValueIn
152
152
  * The component has been loaded into the DOM.
153
153
  */
154
154
  componentDidMount(): void;
155
+ componentDidUpdate(prevProps: ValueInputProps): void;
155
156
  private onBufferValue;
156
157
  /**
157
158
  * The user has elected to accept the input value. Validate and store, if valid.
@@ -1 +1 @@
1
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import React,{createRef}from"react";import{InputNumber}from"primereact/inputnumber";import{Button}from"primereact/button";import{EventEmitterContext}from"../core/EventEmitterContext";export class ValueInput extends React.Component{constructor(t){super(t),Object.defineProperty(this,"inputRef",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state={entryValue:t.value,currentValue:t.value,editing:!1},this.inputRef=createRef()}componentDidMount(){}onBufferValue(t){null!==t&&(this.state.editing?this.setState({entryValue:t}):this.setState({entryValue:this.state.currentValue,editing:!0},(()=>{setTimeout((()=>{this.inputRef.current&&this.inputRef.current.focus()}),0)})))}onAcceptValue(){null!==this.state.entryValue&&(this.setState({editing:!1,currentValue:this.state.entryValue}),this.props.onValueChanged&&this.props.onValueChanged(this.state.entryValue),void 0!==this.props.dispatchTopic&&this.context.dispatch({topic:this.props.dispatchTopic,payload:this.state.entryValue}))}onResetValue(){this.state.editing&&this.setState({currentValue:this.state.currentValue,entryValue:this.state.currentValue,editing:!1})}render(){return _jsxs("div",{children:[_jsxs("div",{className:"p-inputgroup flex-1",children:[_jsx("span",{className:"p-inputgroup-addon",children:this.props.label}),_jsx(InputNumber,{inputRef:this.inputRef,min:this.props.min,max:this.props.max,minFractionDigits:this.props.minPrecision,maxFractionDigits:this.props.maxPrecision,mode:this.props.mode,prefix:this.props.prefix,suffix:this.props.suffix,showButtons:this.props.showButtons,step:this.props.step,placeholder:this.props.placeholder,value:this.state.currentValue,onChange:t=>{this.onBufferValue(t.value)},buttonLayout:"horizontal",decrementButtonClassName:"p-button-danger",incrementButtonClassName:"p-button-success",incrementButtonIcon:"pi pi-plus",decrementButtonIcon:"pi pi-minus",locale:"en-US",currency:this.props.currency,onKeyDown:t=>{"Enter"===t.key?this.onAcceptValue():"Escape"===t.key&&this.onResetValue()},disabled:this.props.disabled,autoFocus:!1},this.state.editing?"editing":"not-editing"),_jsx(Button,{icon:"pi pi-check",disabled:this.props.disabled||!this.state.editing,className:"p-button-success",onClick:()=>this.onAcceptValue(),visible:this.state.editing,size:"small",autoFocus:!1}),_jsx(Button,{icon:"pi pi-times",disabled:this.props.disabled||!this.state.editing,className:"p-button-danger",onClickCapture:()=>this.onResetValue(),visible:this.state.editing,size:"small",autoFocus:!1})]}),void 0!==this.props.description&&_jsx("small",{children:this.props.description})]})}}Object.defineProperty(ValueInput,"contextType",{enumerable:!0,configurable:!0,writable:!0,value:EventEmitterContext}),Object.defineProperty(ValueInput,"defaultProps",{enumerable:!0,configurable:!0,writable:!0,value:{label:"",value:void 0,keyFilter:void 0,writeTopic:void 0,onValueChanged:void 0,description:void 0,prefix:void 0,suffix:void 0,disabled:!1,dispatchTopic:void 0,placeholder:void 0,validator:void 0,min:void 0,max:void 0,minPrecision:0,maxPrecision:3,mode:"decimal",showButtons:!1,step:1,locale:"en-US",currency:"USD"}});
1
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import React,{createRef}from"react";import{InputNumber}from"primereact/inputnumber";import{Button}from"primereact/button";import{EventEmitterContext}from"../core/EventEmitterContext";export class ValueInput extends React.Component{constructor(e){super(e),Object.defineProperty(this,"inputRef",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state={entryValue:e.value,currentValue:e.value,editing:!1},this.inputRef=createRef()}componentDidMount(){}componentDidUpdate(e){e.value!==this.props.value&&this.setState({currentValue:this.props.value,entryValue:this.props.value,editing:!1})}onBufferValue(e){null!==e&&(this.state.editing?this.setState({entryValue:e}):this.setState({entryValue:e,editing:!0},(()=>{setTimeout((()=>{this.inputRef.current&&this.inputRef.current.focus()}),0)})))}onAcceptValue(){null!==this.state.entryValue&&(this.setState({editing:!1,currentValue:this.state.entryValue}),this.props.onValueChanged&&this.props.onValueChanged(this.state.entryValue),void 0!==this.props.dispatchTopic&&this.context.dispatch({topic:this.props.dispatchTopic,payload:this.state.entryValue}))}onResetValue(){this.state.editing&&this.setState({currentValue:this.state.currentValue,entryValue:this.state.currentValue,editing:!1})}render(){return _jsxs("div",{children:[_jsxs("div",{className:"p-inputgroup flex-1",children:[_jsx("span",{className:"p-inputgroup-addon",children:this.props.label}),_jsx(InputNumber,{inputRef:this.inputRef,min:this.props.min,max:this.props.max,minFractionDigits:this.props.minPrecision,maxFractionDigits:this.props.maxPrecision,mode:this.props.mode,prefix:this.props.prefix,suffix:this.props.suffix,showButtons:this.props.showButtons,step:this.props.step,placeholder:this.props.placeholder,value:this.state.currentValue,onChange:e=>{this.onBufferValue(e.value)},buttonLayout:"horizontal",decrementButtonClassName:"p-button-danger",incrementButtonClassName:"p-button-success",incrementButtonIcon:"pi pi-plus",decrementButtonIcon:"pi pi-minus",locale:"en-US",currency:this.props.currency,onKeyDown:e=>{"Enter"===e.key?this.onAcceptValue():"Escape"===e.key&&this.onResetValue()},disabled:this.props.disabled,autoFocus:!1},this.state.editing?"editing":"not-editing"),_jsx(Button,{icon:"pi pi-check",disabled:this.props.disabled||!this.state.editing,className:"p-button-success",onClick:()=>this.onAcceptValue(),visible:this.state.editing,size:"small",autoFocus:!1}),_jsx(Button,{icon:"pi pi-times",disabled:this.props.disabled||!this.state.editing,className:"p-button-danger",onClickCapture:()=>this.onResetValue(),visible:this.state.editing,size:"small",autoFocus:!1})]}),void 0!==this.props.description&&_jsx("small",{children:this.props.description})]})}}Object.defineProperty(ValueInput,"contextType",{enumerable:!0,configurable:!0,writable:!0,value:EventEmitterContext}),Object.defineProperty(ValueInput,"defaultProps",{enumerable:!0,configurable:!0,writable:!0,value:{label:"",value:void 0,keyFilter:void 0,writeTopic:void 0,onValueChanged:void 0,description:void 0,prefix:void 0,suffix:void 0,disabled:!1,dispatchTopic:void 0,placeholder:void 0,validator:void 0,min:void 0,max:void 0,minPrecision:0,maxPrecision:3,mode:"decimal",showButtons:!1,step:1,locale:"en-US",currency:"USD"}});
@@ -102,6 +102,11 @@ export interface EventEmitterContextType {
102
102
  * @returns An object containing the current subscriptions, optionally filtered by topic.
103
103
  */
104
104
  getSubscriptions: (topic?: string) => Record<string, Subscription[]> | Subscription[];
105
+ /**
106
+ * Returns true if the Hub in use is connected to its source.
107
+ * @returns boolean
108
+ */
109
+ isConnected: () => boolean;
105
110
  }
106
111
  /**
107
112
  * A global context for managing event emission and subscription.
@@ -1 +1 @@
1
- import{jsx as _jsx}from"react/jsx-runtime";import{createContext,useState,useMemo}from"react";import{createHub,Hub}from"../hub";export{Hub};let globalSubscriptionId=1;export const EventEmitterContext=createContext({state:{subscriptions:{},nextSubscriptionId:1},dispatch:()=>{},subscribe:()=>0,invoke:async(t,s,e)=>Promise.resolve({data:{},success:!1,error_message:""}),unsubscribe:t=>{},hub:null,getSubscriptions:()=>[]});export const EventEmitterProvider=({children:t})=>{const[s,e]=useState({subscriptions:{},nextSubscriptionId:1}),i=useMemo((()=>createHub()),[]),r=t=>{const{topic:s,payload:i}=t;e((t=>(t.subscriptions[s]?.forEach((t=>t.callback(i))),{...t,eventData:i})))},o=(t,s)=>{globalSubscriptionId+=1;const i=globalSubscriptionId;return e((e=>({...e,subscriptions:{...e.subscriptions,[t]:[...e.subscriptions[t]||[],{id:i,callback:s}]},nextSubscriptionId:globalSubscriptionId+1}))),i},n=t=>{e((s=>{const e={...s.subscriptions};for(const s in e)e.hasOwnProperty(s)&&(e[s]=e[s].filter((s=>s.id!==t)),0===e[s].length&&delete e[s]);return{...s,subscriptions:e}}))},c=t=>t?s.subscriptions[t]||[]:s.subscriptions,u=useMemo((()=>({state:s,dispatch:r,subscribe:o,unsubscribe:n,invoke:i.invoke,hub:i,getSubscriptions:c})),[s,i]);return i.setContext(u),_jsx(EventEmitterContext.Provider,{value:u,children:t})};
1
+ import{jsx as _jsx}from"react/jsx-runtime";import{createContext,useState,useMemo,useCallback}from"react";import{createHub,Hub}from"../hub";export{Hub};let globalSubscriptionId=1;export const EventEmitterContext=createContext({state:{subscriptions:{},nextSubscriptionId:1},dispatch:()=>{},subscribe:()=>0,invoke:async(t,s,e)=>Promise.resolve({data:{},success:!1,error_message:""}),unsubscribe:t=>{},hub:null,getSubscriptions:()=>[],isConnected:()=>!1});export const EventEmitterProvider=({children:t})=>{const[s,e]=useState({subscriptions:{},nextSubscriptionId:1}),i=useMemo((()=>createHub()),[]),r=useCallback((t=>{const{topic:s,payload:i}=t;e((t=>((t.subscriptions[s]||[]).forEach((t=>t.callback(i))),{...t,eventData:i})))}),[]),o=useCallback(((t,s)=>{globalSubscriptionId+=1;const i=globalSubscriptionId;return e((e=>({...e,subscriptions:{...e.subscriptions,[t]:[...e.subscriptions[t]||[],{id:i,callback:s}]},nextSubscriptionId:globalSubscriptionId+1}))),i}),[]),c=useCallback((t=>{e((s=>{const e={...s.subscriptions};return Object.keys(e).forEach((s=>{e[s]=e[s].filter((s=>s.id!==t)),0===e[s].length&&delete e[s]})),{...s,subscriptions:e}}))}),[]),n=useCallback((t=>t?s.subscriptions[t]||[]:s.subscriptions),[]),u=useMemo((()=>({state:s,dispatch:r,subscribe:o,unsubscribe:c,invoke:i.invoke,hub:i,getSubscriptions:n,isConnected:i.isConnected})),[s,i]);return i.setContext(u),_jsx(EventEmitterContext.Provider,{value:u,children:t})};
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Custom hook for registering symbols and subscribing to updates on the
3
+ * ADS domain via the EventEmitterContext.
4
+ * This hook abstracts the common pattern of registering symbols and handling subscriptions
5
+ * to updates in components that need real-time data from a backend service.
6
+ *
7
+ * @param setters A mapping of state setter functions, where each key corresponds to a piece of state
8
+ * related to a symbol, and each value is the setter function for that state.
9
+ * @param symbols A mapping of state keys to their corresponding symbol names in the backend system.
10
+ * Each key should match a key in the `setters` object, and each value should be a string
11
+ * that represents the symbol name to register and subscribe to.
12
+ *
13
+ * ## Usage Example:
14
+ * ```typescript
15
+ * const setters = {
16
+ * speed: setSpeed,
17
+ * temperature: setTemperature
18
+ * };
19
+ *
20
+ * const symbols = {
21
+ * speed: "Sensor.speed",
22
+ * temperature: "Sensor.temperature"
23
+ * };
24
+ *
25
+ * useRegisterSymbols(setters, symbols);
26
+ * ```
27
+ *
28
+ * This will register and subscribe to updates for "Sensor.speed" and "Sensor.temperature",
29
+ * and update the `speed` and `temperature` states via `setSpeed` and `setTemperature` respectively
30
+ * whenever new data is received.
31
+ */
32
+ export declare const useAdsRegisterSymbols: (setters: Record<string, (value: any) => void>, symbols: Record<string, string>) => null;
@@ -0,0 +1 @@
1
+ import{useEffect,useContext,useRef}from"react";import{EventEmitterContext}from"../core/EventEmitterContext";export const useAdsRegisterSymbols=(e,t)=>{const{invoke:r,subscribe:n,unsubscribe:s,isConnected:c}=useContext(EventEmitterContext),o=useRef([]),u=useRef(!0);return useEffect((()=>{u.current=!0;const i=async()=>{for(const[s,c]of Object.entries(t))try{await r("ADS","register_symbol",{symbol_name:c});const t=n(`ADS/${c}`,(t=>{if(u.current){const r=e[s];r&&r(t.value)}}));o.current.push(t)}catch(e){}await r("ADS","refresh",{})};if(c())i();else{let e=n("HUB/connected",(()=>{i(),s(e)}));o.current.push(e)}return()=>{u.current=!1,o.current.forEach((e=>s(e))),o.current=[]}}),[]),null};
@@ -79,6 +79,7 @@ export declare abstract class HubBase {
79
79
  protected localFNameToBackendFNameMap: Map<string, string>;
80
80
  protected backendFNameToLocalFNameMap: Map<string, string>;
81
81
  protected context: EventEmitterContextType | null;
82
+ protected isConnected_: boolean;
82
83
  /**
83
84
  * Constructor
84
85
  */
@@ -100,6 +101,15 @@ export declare abstract class HubBase {
100
101
  * This does NOT get published to the front end.
101
102
  */
102
103
  abstract invoke(domain: string, fname: string, payload?: object): Promise<CommandMessageResult>;
104
+ /**
105
+ * Allos the derived class to set whether the hub is connected to its source.
106
+ * @param s boolean
107
+ */
108
+ protected setIsConnected: (s: boolean) => void;
109
+ /**
110
+ * Returns true if the Hub is connected to its source.
111
+ */
112
+ isConnected: () => boolean;
103
113
  /**
104
114
  * Convenience function to invoke a command with an optional topic and optional value.
105
115
  * This will invoke the specified command in the backend. It does not broadcast the
@@ -1 +1 @@
1
- export class HubBase{constructor(){Object.defineProperty(this,"localTopicToBackendTopicMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"backendTopicToLocalMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"localFNameToBackendFNameMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"backendFNameToLocalFNameMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:null})}setContext(a){this.context=a}invokeTopic(a,e,o,c){const t={topic:o,data:c};return this.invoke(a,e,t)}publish(a,e){const o=this.toLocalTopic(a);this.context?.dispatch({topic:o,payload:e})}mapTopic(a,e){this.localTopicToBackendTopicMap.set(a,e),this.backendTopicToLocalMap.set(e,a)}unmapTopic(a){if(this.localTopicToBackendTopicMap.has(a)){const e=this.localTopicToBackendTopicMap.get(a);this.localTopicToBackendTopicMap.delete(a),null!=e&&this.backendTopicToLocalMap.has(e)&&this.backendTopicToLocalMap.delete(e)}}mapFName(a,e){this.localFNameToBackendFNameMap.set(a,e),this.backendFNameToLocalFNameMap.set(e,a)}unmapFName(a){if(this.localFNameToBackendFNameMap.has(a)){const e=this.localFNameToBackendFNameMap.get(a);this.localFNameToBackendFNameMap.delete(a),null!=e&&this.backendFNameToLocalFNameMap.has(e)&&this.backendFNameToLocalFNameMap.delete(e)}}toBackendTopic(a){if(this.localTopicToBackendTopicMap.has(a)){const e=this.localTopicToBackendTopicMap.get(a);return null!=e?e:a}return a}toBackendFName(a){if(this.localFNameToBackendFNameMap.has(a)){const e=this.localFNameToBackendFNameMap.get(a);return null!=e?e:a}return a}toLocalTopic(a){if(this.backendTopicToLocalMap.has(a)){const e=this.backendTopicToLocalMap.get(a);return null!=e?e:a}return a}toLocalFName(a){if(this.backendFNameToLocalFNameMap.has(a)){const e=this.backendFNameToLocalFNameMap.get(a);return null!=e?e:a}return a}}export default HubBase;
1
+ export class HubBase{constructor(){Object.defineProperty(this,"localTopicToBackendTopicMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"backendTopicToLocalMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"localFNameToBackendFNameMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"backendFNameToLocalFNameMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isConnected_",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"setIsConnected",{enumerable:!0,configurable:!0,writable:!0,value:e=>{this.isConnected_=e}}),Object.defineProperty(this,"isConnected",{enumerable:!0,configurable:!0,writable:!0,value:()=>this.isConnected_})}setContext(e){this.context=e}invokeTopic(e,a,o,c){const t={topic:o,data:c};return this.invoke(e,a,t)}publish(e,a){const o=this.toLocalTopic(e);this.context?.dispatch({topic:o,payload:a})}mapTopic(e,a){this.localTopicToBackendTopicMap.set(e,a),this.backendTopicToLocalMap.set(a,e)}unmapTopic(e){if(this.localTopicToBackendTopicMap.has(e)){const a=this.localTopicToBackendTopicMap.get(e);this.localTopicToBackendTopicMap.delete(e),null!=a&&this.backendTopicToLocalMap.has(a)&&this.backendTopicToLocalMap.delete(a)}}mapFName(e,a){this.localFNameToBackendFNameMap.set(e,a),this.backendFNameToLocalFNameMap.set(a,e)}unmapFName(e){if(this.localFNameToBackendFNameMap.has(e)){const a=this.localFNameToBackendFNameMap.get(e);this.localFNameToBackendFNameMap.delete(e),null!=a&&this.backendFNameToLocalFNameMap.has(a)&&this.backendFNameToLocalFNameMap.delete(a)}}toBackendTopic(e){if(this.localTopicToBackendTopicMap.has(e)){const a=this.localTopicToBackendTopicMap.get(e);return null!=a?a:e}return e}toBackendFName(e){if(this.localFNameToBackendFNameMap.has(e)){const a=this.localFNameToBackendFNameMap.get(e);return null!=a?a:e}return e}toLocalTopic(e){if(this.backendTopicToLocalMap.has(e)){const a=this.backendTopicToLocalMap.get(e);return null!=a?a:e}return e}toLocalFName(e){if(this.backendFNameToLocalFNameMap.has(e)){const a=this.backendFNameToLocalFNameMap.get(e);return null!=a?a:e}return e}}export default HubBase;
@@ -1 +1 @@
1
- import{HubBase}from"./HubBase";function b64toBlob(e,t="application/octet-stream",s=512){const n=atob(e),o=[];for(let e=0;e<n.length;e+=s){const t=n.slice(e,e+s),r=new Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);const i=new Uint8Array(r);o.push(i)}return new Blob(o,{type:t})}function downloadBlob(e,t){const s=window.URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),window.URL.revokeObjectURL(s)}export class HubWebSocket extends HubBase{constructor(){super(),Object.defineProperty(this,"socket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"requestId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"pendingRequests",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"invoke",{enumerable:!0,configurable:!0,writable:!0,value:(e,t,s)=>new Promise(((n,o)=>{const r=++this.requestId;this.pendingRequests.set(r,{resolve:n,reject:o});let i={request_id:r,domain:e,fname:t,args:s,result:void 0};this.socket.send(JSON.stringify(i))}))}),Object.defineProperty(this,"handleUnsolicitedMessage",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if("BROADCAST"===e.fname&&e.domain.length>=1&&void 0!==e.result&&null!==e.result&&void 0!==e.result.data&&null!==e.result.data){let t=`${e.domain}/${e.result.data.topic}`;this.publish(t,e.result.data)}}}),Object.defineProperty(this,"disconnect",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.socket.close()}}),Object.defineProperty(this,"emit",{enumerable:!0,configurable:!0,writable:!0,value:(e,t)=>{this.socket.send(JSON.stringify({eventName:e,payload:t}))}});const e=window.location.hostname;let t;const s=`${"https:"===window.location.protocol?"wss://":"ws://"}${e}${t?":"+t:""}/ws/`;this.socket=new WebSocket(s);let n=this;this.socket.onopen=function(){n.publish("HUB/connected",!0)},this.socket.onmessage=e=>{const t=JSON.parse(e.data);if(t.request_id&&this.pendingRequests.has(t.request_id)){const{resolve:e,reject:s}=this.pendingRequests.get(t.request_id);if("FILE_DOWNLOAD"===t.fname&&void 0!==t.args.file_name&&null!==t.args.file_name&&t.args.file_name.length>0){let n=t.args.file_name.split("/");const o=n[n.length-1];if(t.result&&t.result.success){downloadBlob(b64toBlob(t.result.data),o),t.result.data=o,e(t.result)}else s(new Error(t.result?.error_message))}else t.result?.success?e(t.result):s(new Error(t.result?.error_message));this.pendingRequests.delete(t.request_id)}else this.handleUnsolicitedMessage(t)},this.socket.onerror=e=>{},this.socket.onclose=()=>{}}}
1
+ import{HubBase}from"./HubBase";function b64toBlob(e,t="application/octet-stream",s=512){const n=atob(e),o=[];for(let e=0;e<n.length;e+=s){const t=n.slice(e,e+s),r=new Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);const i=new Uint8Array(r);o.push(i)}return new Blob(o,{type:t})}function downloadBlob(e,t){const s=window.URL.createObjectURL(e),n=document.createElement("a");n.href=s,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),window.URL.revokeObjectURL(s)}export class HubWebSocket extends HubBase{constructor(){super(),Object.defineProperty(this,"socket",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"requestId",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"pendingRequests",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"invoke",{enumerable:!0,configurable:!0,writable:!0,value:(e,t,s)=>new Promise(((n,o)=>{const r=++this.requestId;this.pendingRequests.set(r,{resolve:n,reject:o});let i={request_id:r,domain:e,fname:t,args:s,result:void 0};this.socket.send(JSON.stringify(i))}))}),Object.defineProperty(this,"handleUnsolicitedMessage",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if("BROADCAST"===e.fname&&e.domain.length>=1&&void 0!==e.result&&null!==e.result&&void 0!==e.result.data&&null!==e.result.data){let t=`${e.domain}/${e.result.data.topic}`;this.publish(t,e.result.data)}}}),Object.defineProperty(this,"disconnect",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.socket.close()}}),Object.defineProperty(this,"emit",{enumerable:!0,configurable:!0,writable:!0,value:(e,t)=>{this.socket.send(JSON.stringify({eventName:e,payload:t}))}});const e=window.location.hostname;let t;const s=`${"https:"===window.location.protocol?"wss://":"ws://"}${e}${t?":"+t:""}/ws/`;this.socket=new WebSocket(s);let n=this;this.socket.onopen=function(){n.publish("HUB/connected",!0),n.setIsConnected(!0)},this.socket.onmessage=e=>{const t=JSON.parse(e.data);if(t.request_id&&this.pendingRequests.has(t.request_id)){const{resolve:e,reject:s}=this.pendingRequests.get(t.request_id);if("FILE_DOWNLOAD"===t.fname&&void 0!==t.args.file_name&&null!==t.args.file_name&&t.args.file_name.length>0){let n=t.args.file_name.split("/");const o=n[n.length-1];if(t.result&&t.result.success){downloadBlob(b64toBlob(t.result.data),o),t.result.data=o,e(t.result)}else s(new Error(t.result?.error_message))}else t.result?.success?e(t.result):s(new Error(t.result?.error_message));this.pendingRequests.delete(t.request_id)}else this.handleUnsolicitedMessage(t)},this.socket.onerror=e=>{},this.socket.onclose=()=>{n.setIsConnected(!1)}}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adcops/autocore-react",
3
- "version": "3.0.16",
3
+ "version": "3.0.18",
4
4
  "description": "A React component library for industrial user interfaces.",
5
5
  "private": false,
6
6
  "type": "module",
@@ -78,6 +78,10 @@
78
78
  "./components/*": {
79
79
  "import": "./dist/components/*",
80
80
  "types": "./dist/components/*.d.js"
81
+ },
82
+ "./hooks/*": {
83
+ "import": "./dist/hooks/*",
84
+ "types": "./dist/hooks/*.d.js"
81
85
  }
82
86
  }
83
87
  }
@@ -2,7 +2,7 @@
2
2
  * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
3
  * Created Date: 2024-04-24 16:01:53
4
4
  * -----
5
- * Last Modified: 2024-04-25 06:40:11
5
+ * Last Modified: 2024-04-25 18:57:03
6
6
  * -----
7
7
  *
8
8
  */
@@ -2,7 +2,7 @@
2
2
  * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
3
  * Created Date: 2024-03-20 13:05:42
4
4
  * -----
5
- * Last Modified: 2024-04-16 19:06:17
5
+ * Last Modified: 2024-04-25 16:40:53
6
6
  * -----
7
7
  *
8
8
  */
@@ -217,6 +217,17 @@ export class ValueInput extends React.Component<ValueInputProps, ValueInputState
217
217
  componentDidMount() {
218
218
  }
219
219
 
220
+ componentDidUpdate(prevProps: ValueInputProps) {
221
+ // Check if the value prop has changed
222
+ if (prevProps.value !== this.props.value) {
223
+ this.setState({
224
+ currentValue: this.props.value,
225
+ entryValue: this.props.value,
226
+ editing: false // Consider whether you want to reset editing state here
227
+ });
228
+ }
229
+ }
230
+
220
231
 
221
232
  private onBufferValue(val: number | null) {
222
233
  if (val === null)
@@ -224,7 +235,7 @@ export class ValueInput extends React.Component<ValueInputProps, ValueInputState
224
235
 
225
236
  if (!this.state.editing) {
226
237
  this.setState({
227
- entryValue: this.state.currentValue,
238
+ entryValue: val, //this.state.currentValue,
228
239
  editing: true
229
240
  }, () => {
230
241
 
@@ -2,18 +2,18 @@
2
2
  * Copyright (C) 2024 Automated Design Corp. All Rights Reserved.
3
3
  * Created Date: 2024-01-17 11:45:10
4
4
  * -----
5
- * Last Modified: 2024-04-24 12:11:16
5
+ * Last Modified: 2024-04-25 15:24:53
6
6
  * Modified By: ADC
7
7
  * -----
8
8
  *
9
9
  */
10
10
 
11
11
 
12
- import React, { createContext, ReactNode, useState, useMemo } from 'react';
13
- import {createHub, Hub} from "../hub";
14
- import {CommandMessageResult} from "../hub/CommandMessage";
12
+ import React, { createContext, ReactNode, useState, useMemo, useCallback } from 'react';
13
+ import { createHub, Hub } from "../hub";
14
+ import { CommandMessageResult } from "../hub/CommandMessage";
15
15
 
16
- export {Hub};
16
+ export { Hub };
17
17
 
18
18
  /**
19
19
  * Represents an event subsription.
@@ -38,7 +38,7 @@ export interface State {
38
38
  subscriptions: Record<string, Subscription[]>;
39
39
 
40
40
  /** Tracks the next subscription ID that will be assigned. */
41
- nextSubscriptionId: number;
41
+ nextSubscriptionId: number;
42
42
  }
43
43
 
44
44
  /**
@@ -104,7 +104,7 @@ export interface EventEmitterContextType {
104
104
  * Invoke/send a message to the back end.
105
105
  * This does NOT get published to the front end.
106
106
  */
107
- invoke( domain: string, fname: string, payload? : object) : Promise<CommandMessageResult>;
107
+ invoke(domain: string, fname: string, payload?: object): Promise<CommandMessageResult>;
108
108
 
109
109
  /**
110
110
  * Subscribe to events identified by the topic.
@@ -119,25 +119,32 @@ export interface EventEmitterContextType {
119
119
  * @param subscriptionId The id of the subscription returned by the subscribe method.
120
120
  * @returns
121
121
  */
122
- unsubscribe: (subscriptionId : number) => void;
122
+ unsubscribe: (subscriptionId: number) => void;
123
123
 
124
124
 
125
125
  /**
126
126
  * Global hub for publishing and receiving events throughout the interface, and for exchanging
127
127
  * data with the backend.
128
128
  */
129
- hub : Hub | null;
129
+ hub: Hub | null;
130
130
 
131
131
  /**
132
132
  * Retrieves the current subscriptions. Used for debugging purposes.
133
133
  * @param topic Optional. The topic to retrieve subscriptions for. If omitted, returns all subscriptions.
134
134
  * @returns An object containing the current subscriptions, optionally filtered by topic.
135
135
  */
136
- getSubscriptions: (topic?: string) => Record<string, Subscription[]> | Subscription[];
136
+ getSubscriptions: (topic?: string) => Record<string, Subscription[]> | Subscription[];
137
+
138
+
139
+ /**
140
+ * Returns true if the Hub in use is connected to its source.
141
+ * @returns boolean
142
+ */
143
+ isConnected: () => boolean;
137
144
  }
138
145
 
139
146
 
140
- let globalSubscriptionId = 1;
147
+ let globalSubscriptionId = 1;
141
148
 
142
149
  /**
143
150
  * A global context for managing event emission and subscription.
@@ -262,25 +269,27 @@ let globalSubscriptionId = 1;
262
269
  *
263
270
  */
264
271
  export const EventEmitterContext = createContext<EventEmitterContextType>({
265
- state: { subscriptions: {}, nextSubscriptionId : 1 },
272
+ state: { subscriptions: {}, nextSubscriptionId: 1 },
266
273
  dispatch: () => { },
267
274
  subscribe: () => { return 0; }, // Placeholder for subscription logic
268
- invoke: async (domain: string, fname: string, payload?: object) => {
275
+ invoke: async (domain: string, fname: string, payload?: object) => {
269
276
  domain;
270
277
  fname;
271
278
  payload;
272
- let ret :CommandMessageResult = {
279
+ let ret: CommandMessageResult = {
273
280
  data: {},
274
281
  success: false,
275
- error_message : ""
282
+ error_message: ""
276
283
  };
277
284
  // Placeholder for invoke logic
278
285
  // Implement the logic to send a message to the backend and return a promise
279
286
  return Promise.resolve(ret); // Example placeholder, replace with actual implementation
280
287
  },
281
- unsubscribe: (subscriptionId: number) => { subscriptionId;}, // Placeholder for unsubscription logic
288
+ unsubscribe: (subscriptionId: number) => { subscriptionId; }, // Placeholder for unsubscription logic
282
289
  hub: null,
283
- getSubscriptions: () => { return []; }
290
+ getSubscriptions: () => { return []; },
291
+ isConnected: () => { return false }
292
+
284
293
  });
285
294
 
286
295
 
@@ -318,21 +327,23 @@ export const EventEmitterContext = createContext<EventEmitterContextType>({
318
327
  * ```
319
328
  */
320
329
  export const EventEmitterProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
321
- const [state, setState] = useState<State>({ subscriptions: {}, nextSubscriptionId : 1 });
330
+ const [state, setState] = useState<State>({ subscriptions: {}, nextSubscriptionId: 1 });
322
331
 
323
332
  // Memoize the hub instance so it's only created once
324
333
  const hub = useMemo(() => createHub(), []);
325
334
 
326
- const dispatch = (action: Action) => {
335
+ const dispatch = useCallback((action: Action) => {
327
336
  const { topic, payload } = action;
328
337
 
329
338
  setState(prevState => {
330
- prevState.subscriptions[topic]?.forEach(sub => sub.callback(payload));
339
+ const callbacks = prevState.subscriptions[topic] || [];
340
+ callbacks.forEach(sub => sub.callback(payload));
331
341
  return { ...prevState, eventData: payload };
332
- });
333
- };
342
+ });
343
+
344
+ }, []);
334
345
 
335
- const subscribe = (topic: string, callback: React.Dispatch<any>) : number => {
346
+ const subscribe = useCallback((topic: string, callback: React.Dispatch<any>): number => {
336
347
 
337
348
  globalSubscriptionId += 1;
338
349
  const subscriptionId = globalSubscriptionId; // state.nextSubscriptionId;
@@ -340,39 +351,31 @@ export const EventEmitterProvider: React.FC<{ children: ReactNode }> = ({ childr
340
351
  setState(prevState => ({
341
352
  ...prevState,
342
353
  subscriptions: {
343
- ...prevState.subscriptions,
344
- [topic]: [...(prevState.subscriptions[topic] || []), { id: subscriptionId, callback }]
354
+ ...prevState.subscriptions,
355
+ [topic]: [...(prevState.subscriptions[topic] || []), { id: subscriptionId, callback }]
345
356
  },
346
357
  nextSubscriptionId: globalSubscriptionId + 1 // prevState.nextSubscriptionId + 1
347
- }));
348
-
349
- return subscriptionId;
350
- };
358
+ }));
359
+
360
+ return subscriptionId;
361
+ }, []);
351
362
 
352
363
 
353
- const unsubscribe = (subscriptionId: number) => {
364
+ const unsubscribe = useCallback((subscriptionId: number) => {
354
365
  setState(prevState => {
355
366
  const newSubscriptions = { ...prevState.subscriptions };
356
-
357
- // Iterate through all topics
358
- for (const topic in newSubscriptions) {
359
- if (newSubscriptions.hasOwnProperty(topic)) {
360
- // Filter out the subscription with the given ID
361
- newSubscriptions[topic] = newSubscriptions[topic].filter(sub => sub.id !== subscriptionId);
362
-
363
- // If the topic now has no subscriptions, you can optionally delete the topic key
364
- if (newSubscriptions[topic].length === 0) {
365
- delete newSubscriptions[topic];
366
- }
367
+ Object.keys(newSubscriptions).forEach(topic => {
368
+ newSubscriptions[topic] = newSubscriptions[topic].filter(sub => sub.id !== subscriptionId);
369
+ if (newSubscriptions[topic].length === 0) {
370
+ delete newSubscriptions[topic];
367
371
  }
368
- }
369
-
372
+ });
370
373
  return { ...prevState, subscriptions: newSubscriptions };
371
- });
372
- };
374
+ });
375
+ }, []);
373
376
 
374
377
 
375
- const getSubscriptions = (topic?: string): Record<string, Subscription[]> | Subscription[] => {
378
+ const getSubscriptions = useCallback((topic?: string): Record<string, Subscription[]> | Subscription[] => {
376
379
  if (topic) {
377
380
  // Return subscriptions for the provided topic, or an empty array if the topic doesn't exist
378
381
  return state.subscriptions[topic] || [];
@@ -380,18 +383,19 @@ export const EventEmitterProvider: React.FC<{ children: ReactNode }> = ({ childr
380
383
  // Return all subscriptions
381
384
  return state.subscriptions;
382
385
  }
383
- };
386
+ }, []);
384
387
 
385
388
  // Provide the memoized hub instance in the context value
386
389
  const contextValue = useMemo(() => ({
387
- state,
388
- dispatch,
389
- subscribe,
390
- unsubscribe,
390
+ state,
391
+ dispatch,
392
+ subscribe,
393
+ unsubscribe,
391
394
  invoke: hub.invoke,
392
395
  hub,
393
- getSubscriptions
394
- }), [state, hub]);
396
+ getSubscriptions,
397
+ isConnected: hub.isConnected
398
+ }), [state, hub]);
395
399
 
396
400
 
397
401
  hub.setContext(contextValue);
@@ -0,0 +1,97 @@
1
+ /*
2
+ * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
+ * Created Date: 2024-04-25 09:17:05
4
+ * -----
5
+ * Last Modified: 2024-04-25 16:03:15
6
+ * -----
7
+ *
8
+ */
9
+
10
+
11
+ import { useEffect, useContext, useRef } from 'react';
12
+ import {EventEmitterContext} from "../core/EventEmitterContext";
13
+
14
+ /**
15
+ * Custom hook for registering symbols and subscribing to updates on the
16
+ * ADS domain via the EventEmitterContext.
17
+ * This hook abstracts the common pattern of registering symbols and handling subscriptions
18
+ * to updates in components that need real-time data from a backend service.
19
+ *
20
+ * @param setters A mapping of state setter functions, where each key corresponds to a piece of state
21
+ * related to a symbol, and each value is the setter function for that state.
22
+ * @param symbols A mapping of state keys to their corresponding symbol names in the backend system.
23
+ * Each key should match a key in the `setters` object, and each value should be a string
24
+ * that represents the symbol name to register and subscribe to.
25
+ *
26
+ * ## Usage Example:
27
+ * ```typescript
28
+ * const setters = {
29
+ * speed: setSpeed,
30
+ * temperature: setTemperature
31
+ * };
32
+ *
33
+ * const symbols = {
34
+ * speed: "Sensor.speed",
35
+ * temperature: "Sensor.temperature"
36
+ * };
37
+ *
38
+ * useRegisterSymbols(setters, symbols);
39
+ * ```
40
+ *
41
+ * This will register and subscribe to updates for "Sensor.speed" and "Sensor.temperature",
42
+ * and update the `speed` and `temperature` states via `setSpeed` and `setTemperature` respectively
43
+ * whenever new data is received.
44
+ */
45
+ export const useAdsRegisterSymbols = (setters: Record<string, (value: any) => void>, symbols: Record<string, string>) => {
46
+ const { invoke, subscribe, unsubscribe, isConnected } = useContext(EventEmitterContext);
47
+ const subscriptions = useRef<number[]>([]);
48
+ const isMounted = useRef(true);
49
+
50
+ useEffect(() => {
51
+ isMounted.current = true;
52
+
53
+ const registerAndSubscribe = async () => {
54
+ for (const [key, symbolName] of Object.entries(symbols)) {
55
+ try {
56
+ await invoke("ADS", "register_symbol", { symbol_name: symbolName });
57
+ //console.log(`Subscribe... ADS/${symbolName}`);
58
+ const subscriptionId = subscribe(`ADS/${symbolName}`, (data) => {
59
+ if (isMounted.current) {
60
+ const setter = setters[key];
61
+ if (setter) {
62
+ setter(data.value);
63
+ }
64
+ }
65
+ });
66
+ subscriptions.current.push(subscriptionId);
67
+ } catch (err) {
68
+ console.error(`Failed to register symbol ${symbolName}: ${err}`);
69
+ }
70
+ }
71
+ await invoke("ADS", "refresh", {});
72
+ };
73
+
74
+ if (!isConnected() ) {
75
+ //console.log("SCHEDULE LATER...");
76
+ let connectionSubId = subscribe("HUB/connected", () => {
77
+ registerAndSubscribe();
78
+ unsubscribe(connectionSubId);
79
+ });
80
+ subscriptions.current.push(connectionSubId);
81
+ }
82
+ else {
83
+ //console.log("ALREADY CONNECTED...");
84
+ registerAndSubscribe();
85
+ }
86
+
87
+
88
+ return () => {
89
+ //console.log("UNSUBSCRIBE");
90
+ isMounted.current = false;
91
+ subscriptions.current.forEach(subscriptionId => unsubscribe(subscriptionId));
92
+ subscriptions.current = [];
93
+ };
94
+ }, []); // Ensure setters and symbols are included if they can change
95
+
96
+ return null; // This hook does not render anything
97
+ };
@@ -3,7 +3,7 @@
3
3
  * Created Date: 2023-12-15 14:21:33
4
4
  * Author: Thomas C. Bitsky Jr.
5
5
  * -----
6
- * Last Modified: 2024-04-24 11:56:16
6
+ * Last Modified: 2024-04-25 14:44:14
7
7
  * Modified By: ADC
8
8
  * -----
9
9
  *
@@ -95,6 +95,8 @@ export abstract class HubBase {
95
95
 
96
96
  protected context : EventEmitterContextType | null = null;
97
97
 
98
+ protected isConnected_ : boolean = false;
99
+
98
100
 
99
101
  /**
100
102
  * Constructor
@@ -125,6 +127,21 @@ export abstract class HubBase {
125
127
  abstract invoke(domain: string, fname: string, payload? : object) : Promise<CommandMessageResult>;
126
128
 
127
129
 
130
+ /**
131
+ * Allos the derived class to set whether the hub is connected to its source.
132
+ * @param s boolean
133
+ */
134
+ protected setIsConnected = (s : boolean) => {
135
+ this.isConnected_ = s;
136
+ }
137
+
138
+ /**
139
+ * Returns true if the Hub is connected to its source.
140
+ */
141
+ isConnected = () : boolean => {
142
+ return this.isConnected_;
143
+ }
144
+
128
145
  /**
129
146
  * Convenience function to invoke a command with an optional topic and optional value.
130
147
  * This will invoke the specified command in the backend. It does not broadcast the
@@ -2,7 +2,7 @@
2
2
  * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
3
  * Created Date: 2024-04-17 09:13:07
4
4
  * -----
5
- * Last Modified: 2024-04-25 07:21:33
5
+ * Last Modified: 2024-04-25 14:42:02
6
6
  * -----
7
7
  *
8
8
  */
@@ -149,7 +149,7 @@ export class HubWebSocket extends HubBase {
149
149
  this.socket.onopen = function() {
150
150
  console.log("WebSocket connection established.");
151
151
  self.publish("HUB/connected", true);
152
- //ws.send("Hello, server!"); // Send a message to the server
152
+ self.setIsConnected(true);
153
153
  };
154
154
 
155
155
 
@@ -214,7 +214,8 @@ export class HubWebSocket extends HubBase {
214
214
  // The Websocket connection has closed.
215
215
  //
216
216
  this.socket.onclose = () => {
217
- console.log('WebSocket connection closed.');
217
+ self.setIsConnected(false);
218
+ console.log('WebSocket connection closed.');
218
219
  };
219
220
  }
220
221