@adcops/autocore-react 3.0.16 → 3.0.19

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.
@@ -12,6 +12,7 @@ import React from 'react';
12
12
  type FileListProps = {
13
13
  domain?: string;
14
14
  enableUpload?: boolean;
15
+ subdir?: string;
15
16
  };
16
17
  /**
17
18
  * `FileList` is a React functional component that displays a list of files retrieved from a specified domain
@@ -1 +1 @@
1
- import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import React,{useState,useContext,useEffect}from"react";import{DataTable}from"primereact/datatable";import{Column}from"primereact/column";import{Toolbar}from"primereact/toolbar";import{Button}from"primereact/button";import{ConfirmPopup,confirmPopup}from"primereact/confirmpopup";import{MessageSeverity}from"primereact/api";import{EventEmitterContext}from"../core/EventEmitterContext";export const FileList=({domain:e="DATASTORE",enableUpload:t=!1})=>{const{invoke:a,dispatch:o}=useContext(EventEmitterContext),[r,i]=useState(),s=async()=>{try{let t=await a(e,"list_files",{}),o=[];for(let e=0;e<t.data.length;++e){const a=t.data[e];o.push({id:e+1,name:a})}i(o)}catch(e){o({topic:"autocore-react/alert/error",payload:{message:`Failed to upload file list: ${e}`,timeoutSec:7,severity:MessageSeverity.ERROR}})}},n=`${e} File Listing`,l=_jsx(React.Fragment,{children:_jsx("span",{style:{fontWeight:600},children:n})}),m=_jsxs(React.Fragment,{children:[t&&_jsx(Button,{icon:"pi pi-upload",className:"p-button-rounded p-mr-2","aria-label":"Upload",size:"small",rounded:!0,text:!0}),_jsx(Button,{icon:"pi pi-refresh",onClick:()=>{s()},className:"p-button-rounded p-mr-2","aria-label":"Refresh",size:"small",rounded:!0,text:!0})]}),c=(t,r)=>{confirmPopup({target:r.currentTarget,message:`Are you want to delete file ${t.name}?\nWARNING: This cannot be undone.`,icon:"pi pi-info-circle",defaultFocus:"reject",acceptClassName:"p-button-danger",accept:()=>(async t=>{try{await a(e,"delete_file",{file_name:t})}catch(e){o({topic:"autocore-react/alert/error",payload:{message:`Failed deleting file: ${e}`,timeoutSec:7,severity:MessageSeverity.ERROR}})}s()})(t.name)})};return useEffect((()=>(s(),()=>{})),[e,t]),_jsxs("div",{children:[_jsx(Toolbar,{start:l,end:m,style:{padding:"1mm"}}),_jsx(ConfirmPopup,{}),_jsxs(DataTable,{value:r,children:[_jsx(Column,{field:"name",header:"Name"}),_jsx(Column,{body:t=>_jsxs(_Fragment,{children:[_jsx(Button,{icon:"pi pi-download",onClick:()=>(async t=>{try{await a(e,"download_file",{file_name:t.name})}catch(e){o({topic:"autocore-react/alert/error",payload:{message:`Failed to downloading file: ${e}`,timeoutSec:7,severity:MessageSeverity.ERROR}})}})(t),className:"p-button-rounded p-button-success p-mr-2",style:{marginRight:"2mm"},size:"small"}),_jsx(Button,{icon:"pi pi-trash",onClick:e=>c(t,e),className:"p-button-rounded p-button-danger",size:"small"})]}),header:"Actions"})]})]})};export default FileList;
1
+ import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import React,{useState,useContext,useEffect}from"react";import{DataTable}from"primereact/datatable";import{Column}from"primereact/column";import{Toolbar}from"primereact/toolbar";import{Button}from"primereact/button";import{ConfirmPopup,confirmPopup}from"primereact/confirmpopup";import{MessageSeverity}from"primereact/api";import{EventEmitterContext}from"../core/EventEmitterContext";export const FileList=({domain:e="DATASTORE",enableUpload:t=!1,subdir:a})=>{const{invoke:o,dispatch:r}=useContext(EventEmitterContext),[i,s]=useState(),n=async()=>{try{const t=void 0!==a?{subdir:a}:{};let r=await o(e,"list_files",t),i=[];for(let e=0;e<r.data.length;++e){const t=r.data[e];i.push({id:e+1,name:t})}s(i)}catch(e){r({topic:"autocore-react/alert/error",payload:{message:`Failed to upload file list: ${e}`,timeoutSec:7,severity:MessageSeverity.ERROR}})}},l=`File Listing [/${void 0!==a?a:""}]`,c=_jsx(React.Fragment,{children:_jsx("span",{style:{fontWeight:600},children:l})}),m=_jsxs(React.Fragment,{children:[t&&_jsx(Button,{icon:"pi pi-upload",className:"p-button-rounded p-mr-2","aria-label":"Upload",size:"small",rounded:!0,text:!0}),_jsx(Button,{icon:"pi pi-refresh",onClick:()=>{n()},className:"p-button-rounded p-mr-2","aria-label":"Refresh",size:"small",rounded:!0,text:!0})]}),p=(t,a)=>{confirmPopup({target:a.currentTarget,message:`Are you want to delete file ${t.name}?\nWARNING: This cannot be undone.`,icon:"pi pi-info-circle",defaultFocus:"reject",acceptClassName:"p-button-danger",accept:()=>(async t=>{try{await o(e,"delete_file",{file_name:t})}catch(e){r({topic:"autocore-react/alert/error",payload:{message:`Failed deleting file: ${e}`,timeoutSec:7,severity:MessageSeverity.ERROR}})}n()})(t.name)})};return useEffect((()=>(n(),()=>{})),[e,t]),_jsxs("div",{children:[_jsx(Toolbar,{start:c,end:m,style:{padding:"1mm"}}),_jsx(ConfirmPopup,{}),_jsxs(DataTable,{value:i,children:[_jsx(Column,{field:"name",header:"Name"}),_jsx(Column,{body:t=>_jsxs(_Fragment,{children:[_jsx(Button,{icon:"pi pi-download",onClick:()=>(async t=>{try{await o(e,"download_file",{file_name:t.name})}catch(e){r({topic:"autocore-react/alert/error",payload:{message:`Failed to downloading file: ${e}`,timeoutSec:7,severity:MessageSeverity.ERROR}})}})(t),className:"p-button-rounded p-button-success p-mr-2",style:{marginRight:"2mm"},size:"small"}),_jsx(Button,{icon:"pi pi-trash",onClick:e=>p(t,e),className:"p-button-rounded p-button-danger",size:"small"})]}),header:"Actions"})]})]})};export default FileList;
@@ -0,0 +1,10 @@
1
+ import React from 'react';
2
+ type FileSelectProps = {
3
+ domain?: string;
4
+ subdir?: string;
5
+ onFileSelected?: (fileName: string) => void;
6
+ onAccept?: (fileName: string) => void;
7
+ onCancel?: () => void;
8
+ };
9
+ export declare const FileSelect: React.FC<FileSelectProps>;
10
+ export default FileSelect;
@@ -0,0 +1 @@
1
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useState,useContext,useEffect}from"react";import{DataTable}from"primereact/datatable";import{Column}from"primereact/column";import{Button}from"primereact/button";import{EventEmitterContext}from"../core/EventEmitterContext";export const FileSelect=({domain:e="DATASTORE",subdir:t,onFileSelected:n,onAccept:a,onCancel:l})=>{const{invoke:i}=useContext(EventEmitterContext),[o,s]=useState([]),[c,m]=useState(null),r=e=>{m(e),n&&n(e.name)};return useEffect((()=>{(async()=>{try{const n=t?{subdir:t}:{},a=(await i(e,"list_files",n)).data.map(((e,t)=>({id:t+1,name:e})));s(a)}catch(e){}})()}),[e,t]),_jsxs("div",{children:[_jsxs(DataTable,{value:o,selectionMode:"single",selection:c,onSelectionChange:e=>r(e.value),children:[_jsx(Column,{field:"name",header:"File Name"}),_jsx(Column,{body:e=>_jsx(Button,{label:c?.name===e.name?"Selected":"Select",icon:c?.name===e.name?"pi pi-check-circle":"pi pi-circle-off",onClick:()=>r(e),className:"p-button-rounded "+(c?.name===e.name?"p-button-success":"p-button-outlined"),"aria-label":"Select",size:"small"}),header:"Select"})]}),_jsxs("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"10px"},children:[_jsx(Button,{label:"Cancel",icon:"pi pi-times",className:"p-button-text",onClick:l}),_jsx(Button,{label:"Accept",icon:"pi pi-check",className:"p-button",onClick:()=>{void 0!==a&&null!==c&&a(null!==c?void 0!==t?`${t}/${c.name}`:c.name:"")},disabled:!c})]})]})};export default FileSelect;
@@ -0,0 +1,27 @@
1
+ /*
2
+ * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
+ * Created Date: 2024-04-27 12:46:35
4
+ * -----
5
+ * Last Modified: 2024-04-27 13:10:43
6
+ * -----
7
+ *
8
+ */
9
+
10
+
11
+
12
+ .custom-progress-bar {
13
+ position: relative;
14
+ width: 100%; /* Ensure the progress bar fills the container */
15
+ }
16
+
17
+ .centered-value {
18
+ position: absolute;
19
+ width: 100%;
20
+ text-align: center;
21
+ font-weight: 600;
22
+ z-index: 10;
23
+ top: 50%;
24
+ left: 50%;
25
+ transform: translate(-50%, -50%); /* Centering magic */
26
+ }
27
+
@@ -0,0 +1,9 @@
1
+ import React from 'react';
2
+ import './ProgressBarWithValue.css';
3
+ interface ProgressBarWithValueProps {
4
+ value: number;
5
+ max?: number;
6
+ label?: string;
7
+ }
8
+ export declare const ProgressBarWithValue: React.FC<ProgressBarWithValueProps>;
9
+ export default ProgressBarWithValue;
@@ -0,0 +1 @@
1
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{ProgressBar}from"primereact/progressbar";import"./ProgressBarWithValue.css";export const ProgressBarWithValue=({value:r,max:e,label:s})=>{let a=r,t=!1;return void 0!==e&&(e>0?a=r/e*100:(a=0,t=!0)),_jsxs("div",{className:"custom-progress-bar",children:[_jsx(ProgressBar,{showValue:!1,value:a,mode:t?"indeterminate":"determinate"}),_jsxs("div",{className:"centered-value",children:[s?`${s} `:""," ",r," ",e?`of ${e}`:""]})]})};export default ProgressBarWithValue;
@@ -90,6 +90,7 @@ export declare class TextInput extends React.Component<TextInputProps, TextInput
90
90
  * The component has been loaded into the DOM.
91
91
  */
92
92
  componentDidMount(): void;
93
+ componentDidUpdate(prevProps: TextInputProps): void;
93
94
  /**
94
95
  * Check the new value against the validator RegEx, if one was specified.
95
96
  * @param val The new value.
@@ -1 +1 @@
1
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import React from"react";import{InputText}from"primereact/inputtext";import{Button}from"primereact/button";import{EventEmitterContext}from"../core/EventEmitterContext.js";export class TextInput extends React.Component{constructor(t){super(t),Object.defineProperty(this,"validateValue",{enumerable:!0,configurable:!0,writable:!0,value:t=>void 0===this.props.validator||null===this.props.validator||this.props.validator.test(t)}),this.state={entryValue:t.value,isValid:void 0!==t.value&&this.validateValue(t.value),editing:!1}}componentDidMount(){}onAcceptValue(){void 0!==this.state.entryValue&&this.validateValue(this.state.entryValue)?(this.setState({isValid:!0,editing:!1}),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})):this.setState({isValid:!1})}onResetValue(){this.setState({entryValue:this.props.value,isValid:void 0!==this.props.value&&this.validateValue(this.props.value),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}),void 0!==this.props.prefix&&_jsx("span",{className:"p-inputgroup-addon",children:this.props.prefix}),_jsx(InputText,{keyfilter:this.props.keyFilter,placeholder:this.props.placeholder,value:this.state.entryValue,onChange:t=>{this.setState({entryValue:t.target.value,editing:!0})},className:this.state.isValid?"":"p-invalid",onKeyDown:t=>{"Enter"===t.key?this.onAcceptValue():"Escape"===t.key&&this.onResetValue()},disabled:this.props.disabled}),void 0!==this.props.suffix&&_jsx("span",{className:"p-inputgroup-addon",children:this.props.suffix}),_jsx(Button,{icon:"pi pi-check",disabled:this.props.disabled||!this.state.editing,className:"p-button-success",onClick:()=>this.onAcceptValue(),visible:this.state.editing}),_jsx(Button,{icon:"pi pi-times",disabled:this.props.disabled||!this.state.editing,className:"p-button-danger",onClickCapture:()=>this.onResetValue(),visible:this.state.editing})]}),void 0!==this.props.description&&_jsx("small",{children:this.props.description})]})}}Object.defineProperty(TextInput,"contextType",{enumerable:!0,configurable:!0,writable:!0,value:EventEmitterContext}),Object.defineProperty(TextInput,"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}});
1
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import React from"react";import{InputText}from"primereact/inputtext";import{Button}from"primereact/button";import{EventEmitterContext}from"../core/EventEmitterContext.js";export class TextInput extends React.Component{constructor(t){super(t),Object.defineProperty(this,"validateValue",{enumerable:!0,configurable:!0,writable:!0,value:t=>void 0===this.props.validator||null===this.props.validator||this.props.validator.test(t)}),this.state={entryValue:t.value,isValid:void 0!==t.value&&this.validateValue(t.value),editing:!1}}componentDidMount(){}componentDidUpdate(t){t.value!==this.props.value&&this.setState({entryValue:this.props.value,editing:!1})}onAcceptValue(){void 0!==this.state.entryValue&&this.validateValue(this.state.entryValue)?(this.setState({isValid:!0,editing:!1}),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})):this.setState({isValid:!1})}onResetValue(){this.setState({entryValue:this.props.value,isValid:void 0!==this.props.value&&this.validateValue(this.props.value),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}),void 0!==this.props.prefix&&_jsx("span",{className:"p-inputgroup-addon",children:this.props.prefix}),_jsx(InputText,{keyfilter:this.props.keyFilter,placeholder:this.props.placeholder,value:this.state.entryValue,onChange:t=>{this.setState({entryValue:t.target.value,editing:!0})},className:this.state.isValid?"":"p-invalid",onKeyDown:t=>{"Enter"===t.key?this.onAcceptValue():"Escape"===t.key&&this.onResetValue()},disabled:this.props.disabled}),void 0!==this.props.suffix&&_jsx("span",{className:"p-inputgroup-addon",children:this.props.suffix}),_jsx(Button,{icon:"pi pi-check",disabled:this.props.disabled||!this.state.editing,className:"p-button-success",onClick:()=>this.onAcceptValue(),visible:this.state.editing}),_jsx(Button,{icon:"pi pi-times",disabled:this.props.disabled||!this.state.editing,className:"p-button-danger",onClickCapture:()=>this.onResetValue(),visible:this.state.editing})]}),void 0!==this.props.description&&_jsx("small",{children:this.props.description})]})}}Object.defineProperty(TextInput,"contextType",{enumerable:!0,configurable:!0,writable:!0,value:EventEmitterContext}),Object.defineProperty(TextInput,"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}});
@@ -16,6 +16,7 @@ export interface ToggleGroupProps extends SelectButtonProps {
16
16
  invisibleTopic?: string;
17
17
  actionMode?: ActionMode;
18
18
  invert?: boolean;
19
+ onValueChanged?: (value: boolean | number) => void;
19
20
  }
20
21
  export declare const ToggleGroup: React.FC<ToggleGroupProps>;
21
22
  export default ToggleGroup;
@@ -1 +1 @@
1
- import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useState,useEffect,useContext}from"react";import{SelectButton}from"primereact/selectbutton";import{EventEmitterContext}from"../core/EventEmitterContext";import{IndicatorColor}from"../core/IndicatorColor";export{IndicatorColor};import{ActionMode}from"../core/ActionMode";export{ActionMode};import clsx from"clsx";export const ToggleGroup=({label:o,topic:t,onColor:e,offColor:n,command:r,commandTopic:i,commandArgs:l,disableTopic:s,invisibleTopic:a,actionMode:c,invert:d,...u})=>{const[p]=useState((()=>`toggleGroup-${Math.random().toString(36).substr(2,9)}`)),[m,f]=useState(void 0),[g,v]=useState(!1),[x,b]=useState(!1),[h,I]=useState(!1),C=useContext(EventEmitterContext);useEffect((()=>(t&&C.subscribe(t,y),s&&C.subscribe(s,A),a&&C.subscribe(a,j),()=>{})),[t,s,a]);const y=o=>{f(o)},A=o=>{v(o)},j=o=>{b(o)},M=()=>{h||(I(!0),c!==ActionMode.Tap&&c!==ActionMode.Pressed||S(!0))},E=()=>{h&&(I(!1),c===ActionMode.Tap?S(!1):c===ActionMode.Released&&S(!0))},S=o=>{if(r&&r.length>0){const t={topic:i,value:o,...l};C.dispatch({topic:r,payload:t})}};let T=m;void 0!==u.value&&(T=u.value);let $=((o,t,e)=>{if(!t||0===t.length)return IndicatorColor.IndicatorInvalid;let n=Array.isArray(e)?e:void 0!==e?[e]:[IndicatorColor.IndicatorInvalid],r=typeof o;if("boolean"===r)return o?n[0]:n.length>1?n[1]:n[0];if("number"===r&&t.length>o){if(n.length>o){return n[o]}return n[0]}if("string"===r){let e=t.indexOf(o);return-1!==e&&e<n.length?n[e]:n[0]}return null!=e?Array.isArray(e)?e[0]:e:IndicatorColor.IndicatorInvalid})(T,u.options,e);void 0===T&&($=IndicatorColor.IndicatorInvalid);const _=void 0!==u.options&&null!==u.options&&void 0!==u.options.length&&u.options.length>2,N=`${p}-togglegroup-selectbutton-container`;return _jsxs("div",{className:"flex",children:[_jsx("style",{children:`\n ${void 0!==n?`\n .${N} .p-selectbutton .p-button {\n background-color: ${n};\n }\n `:""}\n .${N} .p-selectbutton .p-button.p-highlight {\n background-color: ${$} !important;\n border-color: ${$} !important;\n }\n `}),_jsx("div",{className:N,children:_jsxs("div",{className:"p-inputgroup",children:[_jsx("span",{className:"p-inputgroup-addon",style:{flexGrow:1},children:o}),_jsx(SelectButton,{...u,options:u.options,disabled:g||u.disabled,multiple:_,className:clsx(p,u.className,{"p-invalid":void 0===u.value}),style:x?{display:"none"}:{},value:((o,t)=>{if(null==t||0===t.length)return;let e=typeof o;if("boolean"==e){return o&&t.length>1?t[1]:t[0]}if("number"==e){let e=o;if(void 0!==e&&e<t.length)return t[e]}else if("string"==e)return o})(T,u.options),allowEmpty:!1,onMouseDown:M,onTouchStart:M,onMouseUp:E,onTouchEnd:E})]})})]})};export default ToggleGroup;
1
+ import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";import{useState,useEffect,useContext}from"react";import{SelectButton}from"primereact/selectbutton";import{EventEmitterContext}from"../core/EventEmitterContext";import{IndicatorColor}from"../core/IndicatorColor";export{IndicatorColor};import{ActionMode}from"../core/ActionMode";export{ActionMode};import clsx from"clsx";export const ToggleGroup=({label:o,topic:t,onColor:e,offColor:n,command:r,commandTopic:i,commandArgs:l,disableTopic:s,invisibleTopic:a,actionMode:c,invert:d,onValueChanged:u,...p})=>{const[m]=useState((()=>`toggleGroup-${Math.random().toString(36).substr(2,9)}`)),[f,g]=useState(void 0),[v,h]=useState(!1),[b,x]=useState(!1),[C,I]=useState(!1),y=useContext(EventEmitterContext);useEffect((()=>(t&&y.subscribe(t,A),s&&y.subscribe(s,j),a&&y.subscribe(a,M),()=>{})),[t,s,a]);const A=o=>{g(o)},j=o=>{h(o)},M=o=>{x(o)},E=()=>{C||(I(!0),c!==ActionMode.Tap&&c!==ActionMode.Pressed||T(!0))},S=()=>{C&&(I(!1),c===ActionMode.Tap?T(!1):c===ActionMode.Released&&T(!0))},T=o=>{if(r&&r.length>0){const t={topic:i,value:o,...l};y.dispatch({topic:r,payload:t})}};let $=f;void 0!==p.value&&($=p.value);let _=((o,t,e)=>{if(!t||0===t.length)return IndicatorColor.IndicatorInvalid;let n=Array.isArray(e)?e:void 0!==e?[e]:[IndicatorColor.IndicatorInvalid],r=typeof o;if("boolean"===r)return o?n[0]:n.length>1?n[1]:n[0];if("number"===r&&t.length>o){if(n.length>o){return n[o]}return n[0]}if("string"===r){let e=t.indexOf(o);return-1!==e&&e<n.length?n[e]:n[0]}return null!=e?Array.isArray(e)?e[0]:e:IndicatorColor.IndicatorInvalid})($,p.options,e);void 0===$&&(_=IndicatorColor.IndicatorInvalid);const N=void 0!==p.options&&null!==p.options&&void 0!==p.options.length&&p.options.length>2,G=`${m}-togglegroup-selectbutton-container`;return _jsxs("div",{className:"flex",children:[_jsx("style",{children:`\n ${void 0!==n?`\n .${G} .p-selectbutton .p-button {\n background-color: ${n};\n }\n `:""}\n .${G} .p-selectbutton .p-button.p-highlight {\n background-color: ${_} !important;\n border-color: ${_} !important;\n }\n `}),_jsx("div",{className:G,children:_jsxs("div",{className:"p-inputgroup",children:[_jsx("span",{className:"p-inputgroup-addon",style:{flexGrow:1},children:o}),_jsx(SelectButton,{...p,options:p.options,disabled:v||p.disabled,multiple:N,className:clsx(m,p.className,{"p-invalid":void 0===p.value}),style:b?{display:"none"}:{},value:((o,t)=>{if(null==t||0===t.length)return;let e=typeof o;if("boolean"==e){return o&&t.length>1?t[1]:t[0]}if("number"==e){let e=o;if(void 0!==e&&e<t.length)return t[e]}else if("string"==e)return o})($,p.options),allowEmpty:!1,onMouseDown:E,onTouchStart:E,onMouseUp:S,onTouchEnd:S,onChange:o=>(o=>{if(null!=u)if(void 0===p.options||null===p.options||0===p.options.length)u(!!N&&0);else{let t=0;for(let e=0;e<p.options.length;++e)if(o===p.options[e]){t=e;break}u(N?t:t>0)}})(o.value)})]})})]})};export default ToggleGroup;
@@ -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,96 @@
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;
33
+ /**
34
+ * Custom hook to create a function that sends a specified value to a remote device or server.
35
+ * This hook abstracts the repetitive logic involved in sending these values,
36
+ * such as invoking the command and handling errors.
37
+ *
38
+ * @param {string} domain The domain under which the backend function is grouped.
39
+ * @param {string} fname The name of the function to be called on the backend.
40
+ * @param {string} symbolName The symbol name that identifies the specific value or setting in the backend.
41
+ * @returns {Function} A function that accepts a value (number or boolean) and sends it to the configured backend.
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * import React, { useState } from 'react';
46
+ * import { Button } from 'primereact/button';
47
+ * import useWriteValue from './useWriteValue'; // adjust the import path as necessary
48
+ *
49
+ * const Component: React.FC = () => {
50
+ * const [value, setValue] = useState<number>(0);
51
+ * const writeToBackend = useAdsWriteValue("ADS", "write_value", "GNV.mySymbol");
52
+ *
53
+ * return (
54
+ * <div>
55
+ * <input
56
+ * type="number"
57
+ * value={value}
58
+ * onChange={(e) => setValue(Number(e.target.value))}
59
+ * />
60
+ * <Button
61
+ * label="Send to Backend"
62
+ * onClick={() => writeToBackend(value)}
63
+ * />
64
+ * </div>
65
+ * );
66
+ * };
67
+ */
68
+ export declare function useAdsWriteValue(symbolName: string): (value: object | boolean | number | string) => Promise<void>;
69
+ /**
70
+ * Custom hook to send a "tap" action, which sends true followed by false after a short delay,
71
+ * to a specified symbol in the backend. This is used to simulate a button tap or momentary switch.
72
+ *
73
+ * @param {string} domain - The domain under which the backend function is grouped.
74
+ * @param {string} fname - The function name to be called on the backend.
75
+ * @param {string} symbolName - The symbol name to target for the tap action.
76
+ * @returns {Function} A function that triggers the tap action.
77
+ *
78
+ * @example
79
+ * ```tsx
80
+ * import React from 'react';
81
+ * import { Button } from 'primereact/button';
82
+ * import useTapValue from './useTapValue'; // Ensure the correct import path
83
+ *
84
+ * const MyComponent: React.FC = () => {
85
+ * const sendTapAction = useTapValue("ADS", "write_value", "GNV.myButton");
86
+ *
87
+ * return (
88
+ * <Button
89
+ * label="Tap Button"
90
+ * onClick={() => sendTapAction()}
91
+ * />
92
+ * );
93
+ * };
94
+ * ```
95
+ */
96
+ export declare function useAdsTapValue(symbolName: string): () => Promise<void>;
@@ -0,0 +1 @@
1
+ import{useContext,useRef,useEffect}from"react";import{EventEmitterContext}from"../core/EventEmitterContext";function sleep(e){return new Promise((t=>setTimeout(t,e)))}export const useAdsRegisterSymbols=(e,t)=>{const{invoke:n,subscribe:r,unsubscribe:s,isConnected:o}=useContext(EventEmitterContext),u=useRef([]),c=useRef(!0);return useEffect((()=>{c.current=!0;const a=async()=>{for(const[s,o]of Object.entries(t))try{await n("ADS","register_symbol",{symbol_name:o});const t=r(`ADS/${o}`,(t=>{if(c.current){const n=e[s];n&&n(t.value)}}));u.current.push(t)}catch(e){}await n("ADS","refresh",{})};if(o())a();else{let e=r("HUB/connected",(()=>{a(),s(e)}));u.current.push(e)}return()=>{c.current=!1,u.current.forEach((e=>s(e))),u.current=[]}}),[]),null};export function useAdsWriteValue(e){const{invoke:t}=useContext(EventEmitterContext);return async n=>{try{await t("ADS","write_value",{symbol_name:e,value:n})}catch(e){}}}export function useAdsTapValue(e){const{invoke:t}=useContext(EventEmitterContext),n="write_value";return async()=>{try{await t("ADS",n,{symbol_name:e,value:!0}),await sleep(300),await t("ADS",n,{symbol_name:e,value:!1})}catch(e){}}}
@@ -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.19",
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-29 11:01:41
6
6
  * -----
7
7
  *
8
8
  */
@@ -34,7 +34,11 @@ type FileListProps = {
34
34
  domain?: string,
35
35
  /// Enable the upload button so that files can be uploaded to the datastore.
36
36
  /// Default: false
37
- enableUpload?: boolean
37
+ enableUpload?: boolean,
38
+
39
+ /// The subdirectory of the datastore to list.
40
+ /// If blank, the base directory is listed.
41
+ subdir? : string
38
42
  }
39
43
 
40
44
  /**
@@ -69,7 +73,8 @@ type FileItem = {
69
73
  */
70
74
  export const FileList: React.FC<FileListProps> = ({
71
75
  domain = "DATASTORE",
72
- enableUpload = false
76
+ enableUpload = false,
77
+ subdir
73
78
  }) => {
74
79
 
75
80
  const { invoke, dispatch } = useContext(EventEmitterContext);
@@ -81,7 +86,8 @@ export const FileList: React.FC<FileListProps> = ({
81
86
  */
82
87
  const listFiles = async () => {
83
88
  try {
84
- let res = await invoke(domain, "list_files", {});
89
+ const args = subdir !== undefined ? {"subdir" : subdir} : {};
90
+ let res = await invoke(domain, "list_files", args);
85
91
 
86
92
  let items = [];
87
93
  for (let i = 0; i < res.data.length; ++i) {
@@ -157,7 +163,7 @@ export const FileList: React.FC<FileListProps> = ({
157
163
  listFiles();
158
164
  };
159
165
 
160
- const title = `${domain} File Listing`;
166
+ const title = `File Listing [/${subdir !== undefined ? subdir : ''}]`;
161
167
  const toolbarStartContents = (
162
168
  <React.Fragment>
163
169
  <span style={{ fontWeight: 600 }}>{title}</span>
@@ -0,0 +1,115 @@
1
+ /*
2
+ * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
+ * Created Date: 2024-04-28 16:06:59
4
+ * -----
5
+ * Last Modified: 2024-04-28 20:05:41
6
+ * -----
7
+ *
8
+ */
9
+
10
+
11
+ import React, { useState, useContext, useEffect } from 'react';
12
+ import { DataTable } from 'primereact/datatable';
13
+ import { Column } from 'primereact/column';
14
+ import { Button } from 'primereact/button';
15
+
16
+ import { EventEmitterContext } from "../core/EventEmitterContext";
17
+
18
+ type FileSelectProps = {
19
+ domain?: string,
20
+ subdir?: string,
21
+ onFileSelected?: (fileName: string) => void,
22
+ onAccept?: (fileName: string) => void,
23
+ onCancel?: () => void
24
+ }
25
+
26
+ type FileItem = {
27
+ id: number;
28
+ name: string;
29
+ };
30
+
31
+ export const FileSelect: React.FC<FileSelectProps> = ({
32
+ domain = "DATASTORE",
33
+ subdir,
34
+ onFileSelected,
35
+ onAccept,
36
+ onCancel
37
+ }) => {
38
+ const { invoke } = useContext(EventEmitterContext);
39
+ const [files, setFiles] = useState<FileItem[]>([]);
40
+ const [selectedFile, setSelectedFile] = useState<FileItem | null>(null);
41
+
42
+ const listFiles = async () => {
43
+ try {
44
+ const args = subdir ? { "subdir": subdir } : {};
45
+ const res = await invoke(domain, "list_files", args);
46
+ const items = res.data.map((item: string, index: number) => ({
47
+ id: index + 1,
48
+ name: item
49
+ }));
50
+ setFiles(items);
51
+ } catch (error) {
52
+ console.error("Failed to list files:", error);
53
+ }
54
+ };
55
+
56
+ const handleSelect = (file: FileItem) => {
57
+ setSelectedFile(file);
58
+ if (onFileSelected) onFileSelected(file.name);
59
+ };
60
+
61
+ const makeReturnFileName = () => {
62
+ if (selectedFile !== null) {
63
+ if (subdir !== undefined) {
64
+ return `${subdir}/${selectedFile.name}`;
65
+ }
66
+ else {
67
+ return selectedFile.name;
68
+ }
69
+ }
70
+ else {
71
+ return "";
72
+ }
73
+ }
74
+
75
+ useEffect(() => {
76
+ listFiles();
77
+ }, [domain, subdir]);
78
+
79
+ return (
80
+ <div>
81
+ <DataTable
82
+ value={files}
83
+ selectionMode="single"
84
+ selection={selectedFile}
85
+ onSelectionChange={e => handleSelect(e.value as FileItem)}
86
+ >
87
+ <Column field="name" header="File Name" />
88
+ <Column body={(rowData: FileItem) => (
89
+ <Button
90
+ label={selectedFile?.name === rowData.name ? "Selected" : "Select"}
91
+ icon={selectedFile?.name === rowData.name ? "pi pi-check-circle" : "pi pi-circle-off"}
92
+ onClick={() => handleSelect(rowData)}
93
+ className={`p-button-rounded ${selectedFile?.name === rowData.name ? "p-button-success" : "p-button-outlined"}`}
94
+ aria-label="Select"
95
+ size="small"
96
+ />
97
+ )} header="Select" />
98
+ </DataTable>
99
+ <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '10px' }}>
100
+ <Button label="Cancel" icon="pi pi-times" className="p-button-text" onClick={onCancel} />
101
+ <Button
102
+ label="Accept"
103
+ icon="pi pi-check"
104
+ className="p-button"
105
+ onClick={() => { if (onAccept !== undefined && selectedFile !== null) onAccept(makeReturnFileName()) }}
106
+ disabled={!selectedFile}
107
+ />
108
+ </div>
109
+ </div>
110
+ );
111
+ };
112
+
113
+ export default FileSelect;
114
+
115
+
@@ -0,0 +1,27 @@
1
+ /*
2
+ * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
+ * Created Date: 2024-04-27 12:46:35
4
+ * -----
5
+ * Last Modified: 2024-04-27 13:10:43
6
+ * -----
7
+ *
8
+ */
9
+
10
+
11
+
12
+ .custom-progress-bar {
13
+ position: relative;
14
+ width: 100%; /* Ensure the progress bar fills the container */
15
+ }
16
+
17
+ .centered-value {
18
+ position: absolute;
19
+ width: 100%;
20
+ text-align: center;
21
+ font-weight: 600;
22
+ z-index: 10;
23
+ top: 50%;
24
+ left: 50%;
25
+ transform: translate(-50%, -50%); /* Centering magic */
26
+ }
27
+
@@ -0,0 +1,49 @@
1
+ /*
2
+ * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
+ * Created Date: 2024-04-27 12:46:15
4
+ * -----
5
+ * Last Modified: 2024-04-27 13:25:56
6
+ * -----
7
+ *
8
+ */
9
+
10
+
11
+ import React from 'react';
12
+ import { ProgressBar } from 'primereact/progressbar';
13
+ import './ProgressBarWithValue.css'; // Import your custom CSS
14
+
15
+ interface ProgressBarWithValueProps {
16
+ value: number;
17
+ max?: number;
18
+ label? : string;
19
+ }
20
+
21
+ export const ProgressBarWithValue: React.FC<ProgressBarWithValueProps> = ({ value, max, label }) => {
22
+ let progressValue = value;
23
+ let indeterminate = false;
24
+
25
+ if (max !== undefined) {
26
+ if (max > 0) {
27
+ progressValue = (value / max) * 100; // Calculate percentage
28
+ }
29
+ else { // max === 0
30
+ progressValue = 0;
31
+ indeterminate = true;
32
+ }
33
+ }
34
+
35
+ return (
36
+ <div className="custom-progress-bar">
37
+ <ProgressBar
38
+ showValue={false}
39
+ value={progressValue}
40
+ mode={indeterminate ? 'indeterminate' : 'determinate'}
41
+ />
42
+ <div className="centered-value">
43
+ {label ? `${label} ` : ''} {value} {max ? `of ${max}` : ''}
44
+ </div>
45
+ </div>
46
+ );
47
+ };
48
+
49
+ export default ProgressBarWithValue;
@@ -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-03-21 08:35:18
5
+ * Last Modified: 2024-04-27 17:33:46
6
6
  * -----
7
7
  *
8
8
  */
@@ -143,6 +143,16 @@ export class TextInput extends React.Component<TextInputProps, TextInputState> {
143
143
  componentDidMount() {
144
144
  }
145
145
 
146
+
147
+ componentDidUpdate(prevProps: TextInputProps) {
148
+ // Check if the value prop has changed
149
+ if (prevProps.value !== this.props.value) {
150
+ this.setState({
151
+ entryValue: this.props.value,
152
+ editing: false
153
+ });
154
+ }
155
+ }
146
156
 
147
157
 
148
158
  /**
@@ -2,7 +2,7 @@
2
2
  * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
3
  * Created Date: 2024-03-12 10:14:48
4
4
  * -----
5
- * Last Modified: 2024-04-16 09:16:59
5
+ * Last Modified: 2024-04-29 10:43:49
6
6
  * -----
7
7
  *
8
8
  */
@@ -33,6 +33,7 @@ export interface ToggleGroupProps extends SelectButtonProps {
33
33
  invisibleTopic?: string;
34
34
  actionMode?: ActionMode;
35
35
  invert?: boolean;
36
+ onValueChanged? : (value: boolean | number) => void;
36
37
  }
37
38
 
38
39
  export const ToggleGroup: React.FC<ToggleGroupProps> = ({
@@ -47,6 +48,7 @@ export const ToggleGroup: React.FC<ToggleGroupProps> = ({
47
48
  invisibleTopic,
48
49
  actionMode,
49
50
  invert,
51
+ onValueChanged: onValueChange,
50
52
  ...restProps
51
53
  }) => {
52
54
 
@@ -239,6 +241,40 @@ export const ToggleGroup: React.FC<ToggleGroupProps> = ({
239
241
 
240
242
  const toggleGroupName = `${uniqueId}-togglegroup-selectbutton-container`;
241
243
 
244
+
245
+ const handleValueChange = (label : string) => {
246
+
247
+ if (onValueChange !== undefined && onValueChange !== null) {
248
+
249
+
250
+ if (restProps.options === undefined || restProps.options === null || restProps.options.length === 0) {
251
+ if (isMultiple)
252
+ onValueChange(0);
253
+ else
254
+ onValueChange(false);
255
+ }
256
+ else {
257
+ let index = 0;
258
+ for (let i=0;i<restProps.options.length;++i) {
259
+ if (label === restProps.options[i] ) {
260
+ index = i;
261
+ break;
262
+ }
263
+ }
264
+
265
+ if (isMultiple)
266
+ onValueChange(index);
267
+ else
268
+ onValueChange(index > 0);
269
+
270
+ }
271
+
272
+
273
+ }
274
+
275
+
276
+ }
277
+
242
278
  return (
243
279
  <div className="flex">
244
280
  {
@@ -275,6 +311,7 @@ export const ToggleGroup: React.FC<ToggleGroupProps> = ({
275
311
  onTouchStart={handleOnPressed}
276
312
  onMouseUp={handleOnReleased}
277
313
  onTouchEnd={handleOnReleased}
314
+ onChange={(e) => handleValueChange(e.value)}
278
315
  />
279
316
  </div>
280
317
  </div>
@@ -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,208 @@
1
+ /*
2
+ * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
+ * Created Date: 2024-04-26 09:04:40
4
+ * -----
5
+ * Last Modified: 2024-04-28 20:07:12
6
+ * -----
7
+ *
8
+ */
9
+
10
+
11
+
12
+ import { useContext, useRef, useEffect } from 'react';
13
+ import { EventEmitterContext } from '../core/EventEmitterContext';
14
+
15
+
16
+ /**
17
+ * Sleep for a given number of milliseconds.
18
+ * @param ms Number of milliseconds to sleep.
19
+ */
20
+ function sleep(ms: number): Promise<void> {
21
+ return new Promise(resolve => setTimeout(resolve, ms));
22
+ }
23
+
24
+
25
+
26
+
27
+ /**
28
+ * Custom hook for registering symbols and subscribing to updates on the
29
+ * ADS domain via the EventEmitterContext.
30
+ * This hook abstracts the common pattern of registering symbols and handling subscriptions
31
+ * to updates in components that need real-time data from a backend service.
32
+ *
33
+ * @param setters A mapping of state setter functions, where each key corresponds to a piece of state
34
+ * related to a symbol, and each value is the setter function for that state.
35
+ * @param symbols A mapping of state keys to their corresponding symbol names in the backend system.
36
+ * Each key should match a key in the `setters` object, and each value should be a string
37
+ * that represents the symbol name to register and subscribe to.
38
+ *
39
+ * ## Usage Example:
40
+ * ```typescript
41
+ * const setters = {
42
+ * speed: setSpeed,
43
+ * temperature: setTemperature
44
+ * };
45
+ *
46
+ * const symbols = {
47
+ * speed: "Sensor.speed",
48
+ * temperature: "Sensor.temperature"
49
+ * };
50
+ *
51
+ * useRegisterSymbols(setters, symbols);
52
+ * ```
53
+ *
54
+ * This will register and subscribe to updates for "Sensor.speed" and "Sensor.temperature",
55
+ * and update the `speed` and `temperature` states via `setSpeed` and `setTemperature` respectively
56
+ * whenever new data is received.
57
+ */
58
+ export const useAdsRegisterSymbols = (setters: Record<string, (value: any) => void>, symbols: Record<string, string>) => {
59
+ const { invoke, subscribe, unsubscribe, isConnected } = useContext(EventEmitterContext);
60
+ const subscriptions = useRef<number[]>([]);
61
+ const isMounted = useRef(true);
62
+
63
+ useEffect(() => {
64
+ isMounted.current = true;
65
+
66
+ const registerAndSubscribe = async () => {
67
+ for (const [key, symbolName] of Object.entries(symbols)) {
68
+ try {
69
+ await invoke("ADS", "register_symbol", { symbol_name: symbolName });
70
+ //console.log(`Subscribe... ADS/${symbolName}`);
71
+ const subscriptionId = subscribe(`ADS/${symbolName}`, (data) => {
72
+ if (isMounted.current) {
73
+ const setter = setters[key];
74
+ if (setter) {
75
+ setter(data.value);
76
+ }
77
+ }
78
+ });
79
+ subscriptions.current.push(subscriptionId);
80
+ } catch (err) {
81
+ console.error(`Failed to register symbol ${symbolName}: ${err}`);
82
+ }
83
+ }
84
+ await invoke("ADS", "refresh", {});
85
+ };
86
+
87
+ if (!isConnected() ) {
88
+ //console.log("SCHEDULE LATER...");
89
+ let connectionSubId = subscribe("HUB/connected", () => {
90
+ registerAndSubscribe();
91
+ unsubscribe(connectionSubId);
92
+ });
93
+ subscriptions.current.push(connectionSubId);
94
+ }
95
+ else {
96
+ //console.log("ALREADY CONNECTED...");
97
+ registerAndSubscribe();
98
+ }
99
+
100
+
101
+ return () => {
102
+ //console.log("UNSUBSCRIBE");
103
+ isMounted.current = false;
104
+ subscriptions.current.forEach(subscriptionId => unsubscribe(subscriptionId));
105
+ subscriptions.current = [];
106
+ };
107
+ }, []); // Ensure setters and symbols are included if they can change
108
+
109
+ return null; // This hook does not render anything
110
+ };
111
+
112
+
113
+ /**
114
+ * Custom hook to create a function that sends a specified value to a remote device or server.
115
+ * This hook abstracts the repetitive logic involved in sending these values,
116
+ * such as invoking the command and handling errors.
117
+ *
118
+ * @param {string} domain The domain under which the backend function is grouped.
119
+ * @param {string} fname The name of the function to be called on the backend.
120
+ * @param {string} symbolName The symbol name that identifies the specific value or setting in the backend.
121
+ * @returns {Function} A function that accepts a value (number or boolean) and sends it to the configured backend.
122
+ *
123
+ * @example
124
+ * ```tsx
125
+ * import React, { useState } from 'react';
126
+ * import { Button } from 'primereact/button';
127
+ * import useWriteValue from './useWriteValue'; // adjust the import path as necessary
128
+ *
129
+ * const Component: React.FC = () => {
130
+ * const [value, setValue] = useState<number>(0);
131
+ * const writeToBackend = useAdsWriteValue("ADS", "write_value", "GNV.mySymbol");
132
+ *
133
+ * return (
134
+ * <div>
135
+ * <input
136
+ * type="number"
137
+ * value={value}
138
+ * onChange={(e) => setValue(Number(e.target.value))}
139
+ * />
140
+ * <Button
141
+ * label="Send to Backend"
142
+ * onClick={() => writeToBackend(value)}
143
+ * />
144
+ * </div>
145
+ * );
146
+ * };
147
+ */
148
+ export function useAdsWriteValue(symbolName: string) {
149
+ const { invoke } = useContext(EventEmitterContext);
150
+ const domain = "ADS";
151
+ const fname = "write_value";
152
+
153
+ // Return a function that takes a value and sends it to the backend
154
+ return async (value: object | boolean | number | string ) => {
155
+ try {
156
+ await invoke(domain, fname, { symbol_name: symbolName, value });
157
+ } catch (err) {
158
+ console.error(`Error writing tag ${symbolName}: ${err}`);
159
+ }
160
+ };
161
+ }
162
+
163
+
164
+
165
+
166
+ /**
167
+ * Custom hook to send a "tap" action, which sends true followed by false after a short delay,
168
+ * to a specified symbol in the backend. This is used to simulate a button tap or momentary switch.
169
+ *
170
+ * @param {string} domain - The domain under which the backend function is grouped.
171
+ * @param {string} fname - The function name to be called on the backend.
172
+ * @param {string} symbolName - The symbol name to target for the tap action.
173
+ * @returns {Function} A function that triggers the tap action.
174
+ *
175
+ * @example
176
+ * ```tsx
177
+ * import React from 'react';
178
+ * import { Button } from 'primereact/button';
179
+ * import useTapValue from './useTapValue'; // Ensure the correct import path
180
+ *
181
+ * const MyComponent: React.FC = () => {
182
+ * const sendTapAction = useTapValue("ADS", "write_value", "GNV.myButton");
183
+ *
184
+ * return (
185
+ * <Button
186
+ * label="Tap Button"
187
+ * onClick={() => sendTapAction()}
188
+ * />
189
+ * );
190
+ * };
191
+ * ```
192
+ */
193
+ export function useAdsTapValue(symbolName: string): () => Promise<void> {
194
+ const { invoke } = useContext(EventEmitterContext);
195
+ const domain = "ADS";
196
+ const fname = "write_value";
197
+
198
+ return async () => {
199
+ try {
200
+ await invoke(domain, fname, { symbol_name: symbolName, value: true });
201
+ await sleep(300); // Sleep for 300ms before writing false
202
+ await invoke(domain, fname, { symbol_name: symbolName, value: false });
203
+ } catch (err) {
204
+ console.error(`Error handling tap action for ${symbolName}: ${err}`);
205
+ }
206
+ };
207
+ }
208
+
@@ -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