@adcops/autocore-react 3.0.20 → 3.0.21
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.
- package/dist/components/FileList.d.ts +33 -0
- package/dist/components/FileList.js +1 -1
- package/dist/components/ValueDisplay.d.ts +49 -3
- package/dist/components/ValueDisplay.js +1 -1
- package/dist/hooks/adsHooks.d.ts +49 -0
- package/dist/hooks/adsHooks.js +1 -1
- package/dist/hooks/index.d.ts +2 -0
- package/dist/hooks/index.js +1 -0
- package/dist/hooks/useScaledValue.d.ts +57 -0
- package/dist/hooks/useScaledValue.js +1 -0
- package/package.json +1 -1
- package/src/components/FileList.tsx +176 -43
- package/src/components/FileSelect.tsx +1 -1
- package/src/components/ValueDisplay.tsx +72 -17
- package/src/hooks/adsHooks.tsx +76 -2
- package/src/hooks/index.ts +12 -0
- package/src/hooks/useScaledValue.tsx +89 -0
|
@@ -6,6 +6,9 @@
|
|
|
6
6
|
* using specific commands via websockets.
|
|
7
7
|
*/
|
|
8
8
|
import React from 'react';
|
|
9
|
+
/**
|
|
10
|
+
* Defines properties for the file list.
|
|
11
|
+
*/
|
|
9
12
|
/**
|
|
10
13
|
* Defines properties for the file list.
|
|
11
14
|
*/
|
|
@@ -13,6 +16,36 @@ type FileListProps = {
|
|
|
13
16
|
domain?: string;
|
|
14
17
|
enableUpload?: boolean;
|
|
15
18
|
subdir?: string;
|
|
19
|
+
/**
|
|
20
|
+
* A comma-separated list of file MIME types or file extensions.
|
|
21
|
+
* Default: .json
|
|
22
|
+
*
|
|
23
|
+
* ### Example: Filter by Extension:
|
|
24
|
+
* ```
|
|
25
|
+
* accept=".jpg,.png,.pdf" // Restricts uploads to JPG, PNG, and PDF files only
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* ### Example: Filter by mime type.
|
|
29
|
+
* ```
|
|
30
|
+
* accept="image/*,application/pdf" // Allows any image type and PDF files
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* ### Example: All files
|
|
34
|
+
* ```
|
|
35
|
+
* accept="/*"
|
|
36
|
+
* ```
|
|
37
|
+
*
|
|
38
|
+
*/
|
|
39
|
+
filter?: string;
|
|
40
|
+
/**
|
|
41
|
+
* Callback when an operation completes successfully.
|
|
42
|
+
* @returns void
|
|
43
|
+
*/
|
|
44
|
+
onSuccess?: (message: string) => void;
|
|
45
|
+
/***
|
|
46
|
+
* Callback when an operation results in an error.
|
|
47
|
+
*/
|
|
48
|
+
onError?: (message: string) => void;
|
|
16
49
|
};
|
|
17
50
|
/**
|
|
18
51
|
* `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{
|
|
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{FileUpload}from"primereact/fileupload";import{EventEmitterContext}from"../core/EventEmitterContext";export const FileList=({domain:e="DATASTORE",enableUpload:t=!1,subdir:o,filter:a=".json",onSuccess:n,onError:i})=>{const[r,l]=useState(0),{invoke:s}=useContext(EventEmitterContext),[c,m]=useState(),d=e=>null!==e?void 0!==o?`${o}/${e}`:e:"",p=async()=>{try{const t=void 0!==o?{subdir:o}:{};let a=await s(e,"list_files",t),n=[];for(let e=0;e<a.data.length;++e){const t=a.data[e];n.push({id:e+1,name:t})}m(n)}catch(e){i&&i(`Failed to upload file list: ${e}`)}};const u=()=>{l((e=>e+1))},f=`File Listing [/${void 0!==o?o:""}]`,x=_jsx(React.Fragment,{children:_jsx("span",{style:{fontWeight:600},children:f})}),b=_jsxs(React.Fragment,{children:[t&&_jsx(FileUpload,{customUpload:!0,auto:!0,uploadHandler:async t=>{const o=t.files[0];let a=d(o.name);const r=new FileReader;r.onload=async t=>{const r=t.target?.result,l=function c(e){let t="",o=new Uint8Array(e),a=o.byteLength;for(let e=0;e<a;e++)t+=String.fromCharCode(o[e]);return window.btoa(t)}(r);try{await s(e,"write_file",{file_name:a,value:l}),n&&n(`Uploaded file ${o.name}`),p()}catch(e){i&&i(`Failed to upload file: ${e}`)}u()},r.onerror=e=>{i&&i(`Error reading file: ${e}`)},r.readAsArrayBuffer(o)},accept:a,maxFileSize:25e3,mode:"basic",chooseLabel:"",chooseOptions:{icon:"pi pi-upload",className:"p-button-icon-only p-button-text p-button-rounded p-mr-2"}},r),_jsx(Button,{icon:"pi pi-refresh",onClick:()=>{p()},className:"p-button-rounded p-mr-2","aria-label":"Refresh",size:"small",rounded:!0,text:!0})]}),_=(t,o)=>{confirmPopup({target:o.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=>{let o=d(t);try{await s(e,"delete_file",{file_name:o}),n&&n(`Deleted file: ${t}`),p()}catch(e){i&&i(`Failed to delete file: ${e}`)}p()})(t.name)})};return useEffect((()=>(p(),()=>{})),[e,t]),_jsxs("div",{children:[_jsx(Toolbar,{start:x,end:b,style:{padding:"1mm"}}),_jsx(ConfirmPopup,{}),_jsxs(DataTable,{value:c,children:[_jsx(Column,{field:"name",header:"Name"}),_jsx(Column,{body:t=>_jsxs(_Fragment,{children:[_jsx(Button,{icon:"pi pi-download",onClick:()=>(async t=>{let o=d(t.name);try{await s(e,"download_file",{file_name:o}),n&&n(`Downloaded file: ${t.name}`)}catch(e){i&&i(`Failed downloading file: ${e}`)}})(t),className:"p-button-rounded p-button-success p-mr-2",style:{marginRight:"2mm"},size:"small"}),_jsx(Button,{icon:"pi pi-trash",onClick:e=>_(t,e),className:"p-button-rounded p-button-danger",size:"small"})]}),header:"Actions"})]})]})};export default FileList;
|
|
@@ -59,9 +59,55 @@ interface State {
|
|
|
59
59
|
fontSize?: string;
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
|
-
* `ValueDisplay` is a React component
|
|
63
|
-
*
|
|
64
|
-
*
|
|
62
|
+
* `ValueDisplay` is a React component designed to display a value which can be a string, number, or null.
|
|
63
|
+
* It supports formatting numeric values using the `numerableFormat` function, and is capable of dynamic positioning
|
|
64
|
+
* and sizing within its parent container. The component integrates with an `EventEmitterContext` to listen for
|
|
65
|
+
* updates to its value based on a specified topic, making it ideal for real-time data display scenarios.
|
|
66
|
+
*
|
|
67
|
+
* The component can be absolutely positioned based on `x` and `y` props, and its size can be adjusted using
|
|
68
|
+
* `width` and `height` props. If `useAbsolutePositioning` is true, it will position itself based on the provided
|
|
69
|
+
* coordinates; otherwise, it will position relatively.
|
|
70
|
+
*
|
|
71
|
+
* ### Props:
|
|
72
|
+
* - `value`: The initial value to display, which can be updated via props or context events.
|
|
73
|
+
* - `x`, `y`: Coordinates for absolute positioning within the parent container.
|
|
74
|
+
* - `width`, `height`: Dimensions of the component. If height is not provided, it defaults to the width.
|
|
75
|
+
* - `format`: A string specifying the format for numeric values (see numerable.js documentation for format strings).
|
|
76
|
+
* - `formatOptions`: Additional formatting options as per numerable.js.
|
|
77
|
+
* - `className`: Custom class for CSS styling.
|
|
78
|
+
* - `useAbsolutePositioning`: Boolean to toggle absolute positioning.
|
|
79
|
+
* - `topic`: Optional string to subscribe to context updates for dynamic value changes.
|
|
80
|
+
*
|
|
81
|
+
* ### Usage Example:
|
|
82
|
+
* ```tsx
|
|
83
|
+
* import React from 'react';
|
|
84
|
+
* import ReactDOM from 'react-dom';
|
|
85
|
+
* import { ValueDisplay } from './components/ValueDisplay';
|
|
86
|
+
*
|
|
87
|
+
* const App = () => {
|
|
88
|
+
* return (
|
|
89
|
+
* <div>
|
|
90
|
+
* <ValueDisplay
|
|
91
|
+
* value={1234.56}
|
|
92
|
+
* x={100}
|
|
93
|
+
* y={200}
|
|
94
|
+
* width={150}
|
|
95
|
+
* height={50}
|
|
96
|
+
* format="0,0.00"
|
|
97
|
+
* className="numeric-display"
|
|
98
|
+
* useAbsolutePositioning={true}
|
|
99
|
+
* topic="priceUpdate"
|
|
100
|
+
* />
|
|
101
|
+
* </div>
|
|
102
|
+
* );
|
|
103
|
+
* };
|
|
104
|
+
*
|
|
105
|
+
* ReactDOM.render(<App />, document.getElementById('root'));
|
|
106
|
+
* ```
|
|
107
|
+
*
|
|
108
|
+
* In this example, `ValueDisplay` is used to show a numeric value formatted as a string with two decimal places.
|
|
109
|
+
* It is positioned absolutely at coordinates (100, 200) with a specified width and height. The component listens
|
|
110
|
+
* for updates on the "priceUpdate" topic to dynamically update its displayed value.
|
|
65
111
|
*/
|
|
66
112
|
declare class ValueDisplay extends Component<Props, State> {
|
|
67
113
|
/** Defines the context type to subscribe to changes using EventEmitter. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as _jsx}from"react/jsx-runtime";import{Component}from"react";import{format as numerableFormat}from"numerable";import clsx from"clsx";import{EventEmitterContext}from"../core/EventEmitterContext";class ValueDisplay extends Component{constructor(e){super(e),Object.defineProperty(this,"unsubscribeTopicId",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.state={subscribedValue:e.value,fontSize:"100%"}}componentDidMount(){const{topic:e}=this.props;if(e){const{subscribe:t}=this.context;this.unsubscribeTopicId=t(e,(e=>{this.setState({subscribedValue:e})}))}}componentDidUpdate(e){this.props.value!==e.value&&this.setState({subscribedValue:this.props.value})}componentWillUnmount(){if(this.unsubscribeTopicId){const{unsubscribe:e}=this.context;e(this.unsubscribeTopicId)}}render(){const{x:e,y:t,width:i,height:s,format:o,formatOptions:r,className:n,useAbsolutePositioning:a}=this.props,{subscribedValue:l,fontSize:
|
|
1
|
+
import{jsx as _jsx}from"react/jsx-runtime";import{Component}from"react";import{format as numerableFormat}from"numerable";import clsx from"clsx";import{EventEmitterContext}from"../core/EventEmitterContext";class ValueDisplay extends Component{constructor(e){super(e),Object.defineProperty(this,"unsubscribeTopicId",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.state={subscribedValue:e.value,fontSize:"100%"}}componentDidMount(){const{topic:e}=this.props;if(e){const{subscribe:t}=this.context;this.unsubscribeTopicId=t(e,(e=>{this.setState({subscribedValue:e})}))}}componentDidUpdate(e){this.props.value!==e.value&&this.setState({subscribedValue:this.props.value})}componentWillUnmount(){if(this.unsubscribeTopicId){const{unsubscribe:e}=this.context;e(this.unsubscribeTopicId)}}render(){const{x:e,y:t,width:i,height:s,format:o,formatOptions:r,className:n,useAbsolutePositioning:a}=this.props,{subscribedValue:l,fontSize:u}=this.state,{scale:c,xOffset:p,yOffset:b}=this.context,m={position:a?"absolute":"relative",display:a?"":"inline-block",verticalAlign:"middle",fontSize:u&&c>1?100*c+"%":u,top:a&&t?`${b+c*t}px`:void 0,left:a&&e?`${p+c*e}px`:void 0,width:i?i*c+"px":void 0,height:s?s*c+"px":void 0,lineHeight:s?s*c+"px":void 0,whiteSpace:"nowrap"};let d;return d="number"==typeof l||"string"==typeof l&&!isNaN(Number(l))?numerableFormat(l,o,r):l,_jsx("div",{className:clsx(n),style:m,children:d})}}Object.defineProperty(ValueDisplay,"contextType",{enumerable:!0,configurable:!0,writable:!0,value:EventEmitterContext});export{ValueDisplay};
|
package/dist/hooks/adsHooks.d.ts
CHANGED
|
@@ -66,6 +66,55 @@ export declare const useAdsRegisterSymbols: (setters: Record<string, (value: any
|
|
|
66
66
|
* };
|
|
67
67
|
*/
|
|
68
68
|
export declare function useAdsWriteValue(symbolName: string): (value: object | boolean | number | string) => Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* useAdsWriteScaledValue is a custom React hook that enables writing scaled numerical values to a backend system.
|
|
71
|
+
* It applies a specified scale and offset to a numeric value before sending it over an ADS connection.
|
|
72
|
+
* This hook is ideal for scenarios where numeric data needs to be adjusted according to dynamically configurable
|
|
73
|
+
* scale factors before being persisted or processed by a backend system.
|
|
74
|
+
*
|
|
75
|
+
* @param symbolName The symbol name in the backend system where the value will be written.
|
|
76
|
+
* @param scale The scale factor to be applied to the value.
|
|
77
|
+
* @param offset The offset to be applied after scaling the value.
|
|
78
|
+
* @returns A function that takes a numeric value, applies the scaling and offset, and sends the modified value to the backend.
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* This example demonstrates how to use the `useAdsWriteScaledValue` hook within a component that allows users
|
|
82
|
+
* to input a value in inches, which is then automatically converted to millimeters (if the scale is set for such conversion)
|
|
83
|
+
* based on a dynamic scale factor managed in the component's state.
|
|
84
|
+
*
|
|
85
|
+
* ```tsx
|
|
86
|
+
* import React, { useState } from 'react';
|
|
87
|
+
* import { useAdsWriteScaledValue } from './hooks';
|
|
88
|
+
*
|
|
89
|
+
* const MeasurementInput: React.FC = () => {
|
|
90
|
+
* const [scale, setScale] = useState<number>(1 / 25.4); // Initial scale for converting inches to millimeters.
|
|
91
|
+
* const [offset, setOffset] = useState<number>(0); // No offset by default.
|
|
92
|
+
*
|
|
93
|
+
* // The hook is used here with the scale and offset state variables.
|
|
94
|
+
* const writeMeasurement = useAdsWriteScaledValue("GIO.axisX.position", scale, offset);
|
|
95
|
+
*
|
|
96
|
+
* // This function is called when the input field value changes.
|
|
97
|
+
* const handleMeasurementChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
98
|
+
* const valueInInches = parseFloat(event.target.value);
|
|
99
|
+
* writeMeasurement(valueInInches); // Write the scaled value (converted to millimeters).
|
|
100
|
+
* };
|
|
101
|
+
*
|
|
102
|
+
* return (
|
|
103
|
+
* <div>
|
|
104
|
+
* <label>Enter measurement in inches:</label>
|
|
105
|
+
* <input type="number" onChange={handleMeasurementChange} />
|
|
106
|
+
* </div>
|
|
107
|
+
* );
|
|
108
|
+
* };
|
|
109
|
+
*
|
|
110
|
+
* export default MeasurementInput;
|
|
111
|
+
* ```
|
|
112
|
+
*
|
|
113
|
+
* In this component, `writeMeasurement` is a function returned by the `useAdsWriteScaledValue` hook that takes a value in inches,
|
|
114
|
+
* converts it to millimeters using the current `scale`, and writes the result to a backend symbol. The `scale` and `offset` can be adjusted
|
|
115
|
+
* dynamically if needed, for instance, based on user selection or other external configurations.
|
|
116
|
+
*/
|
|
117
|
+
export declare function useAdsWriteScaledValue(symbolName: string, scale: number, offset: number): (value: number) => Promise<void>;
|
|
69
118
|
/**
|
|
70
119
|
* Custom hook to send a "tap" action, which sends true followed by false after a short delay,
|
|
71
120
|
* to a specified symbol in the backend. This is used to simulate a button tap or momentary switch.
|
package/dist/hooks/adsHooks.js
CHANGED
|
@@ -1 +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){}}}
|
|
1
|
+
import{useContext,useRef,useEffect,useCallback}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 useAdsWriteScaledValue(e,t,n){const{invoke:r}=useContext(EventEmitterContext);return useCallback((async s=>{const o=(s-n)/t;try{await r("ADS","write_value",{symbol_name:e,value:o})}catch(e){}}),[e,t,n,r])}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){}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{useAdsRegisterSymbols,useAdsWriteValue,useAdsTapValue}from"./adsHooks";export{useScaledValue,kMillimeters2Inches}from"./useScaledValue";
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export declare const kMillimeters2Inches: number;
|
|
2
|
+
type UseScaledValueReturn = [number, (newValue: number) => void];
|
|
3
|
+
/**
|
|
4
|
+
* A custom React hook for converting values between different scales,
|
|
5
|
+
* with support for dynamically updating the scale and offset. This hook manages values
|
|
6
|
+
* in a base unit and allows for easy conversion to a display unit, updating
|
|
7
|
+
* reactively to changes in the conversion factors.
|
|
8
|
+
*
|
|
9
|
+
* @param initialValue - The initial value in the base unit.
|
|
10
|
+
* @param scale - The dynamic scale factor used for conversion to the display unit.
|
|
11
|
+
* @param offset - An optional offset applied after scaling (default is 0).
|
|
12
|
+
* @returns A tuple containing the display value and a setter function for updating
|
|
13
|
+
* the value in the display unit.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* Here's how to use `useScaledValue` in a component that fetches a scale factor from a backend
|
|
17
|
+
* and allows the user to input values in a converted scale, which are then handled in a base unit:
|
|
18
|
+
*
|
|
19
|
+
* ```tsx
|
|
20
|
+
* import React, { useState, useEffect } from 'react';
|
|
21
|
+
* import { useScaledValue } from './hooks/useScaledValue';
|
|
22
|
+
*
|
|
23
|
+
* const MeasurementInput: React.FC = () => {
|
|
24
|
+
* const [units, setUnits] = useState<number>(1); // Start with a default scale of 1
|
|
25
|
+
* const [xPosition, setXPosition] = useScaledValue(0, units);
|
|
26
|
+
*
|
|
27
|
+
* useEffect(() => {
|
|
28
|
+
* async function fetchScale() {
|
|
29
|
+
* try {
|
|
30
|
+
* // Simulate fetching scale factor from a backend
|
|
31
|
+
* const res = await invoke("GNV", "read_value", { group: "ux", key: "kSelectedUnits" });
|
|
32
|
+
* setUnits(res.data); // Update scale based on backend response
|
|
33
|
+
* } catch (error) {
|
|
34
|
+
* console.error('Failed to fetch units', error);
|
|
35
|
+
* }
|
|
36
|
+
* }
|
|
37
|
+
* fetchScale();
|
|
38
|
+
* }, []);
|
|
39
|
+
*
|
|
40
|
+
* return (
|
|
41
|
+
* <input
|
|
42
|
+
* type="number"
|
|
43
|
+
* value={xPosition.toFixed(2)} // Display the value formatted to 2 decimal places
|
|
44
|
+
* onChange={(e) => setXPosition(parseFloat(e.target.value))}
|
|
45
|
+
* />
|
|
46
|
+
* );
|
|
47
|
+
* };
|
|
48
|
+
*
|
|
49
|
+
* export default MeasurementInput;
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* In this example, `useScaledValue` is used to manage a measurement input in a dynamic unit system.
|
|
53
|
+
* The component fetches the conversion scale from the backend upon component mounting and updates the
|
|
54
|
+
* input display accordingly. The user's input is converted back to the base unit before being processed.
|
|
55
|
+
*/
|
|
56
|
+
export declare function useScaledValue(initialValue: number, scale: number, offset?: number): UseScaledValueReturn;
|
|
57
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{useCallback,useState}from"react";export const kMillimeters2Inches=1/25.4;export function useScaledValue(e,t,a=0){const[s,c]=useState(e*t+a);return[s,useCallback((e=>{c(e*t+a)}),[t,a])]}
|
package/package.json
CHANGED
|
@@ -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-
|
|
5
|
+
* Last Modified: 2024-05-02 11:18:50
|
|
6
6
|
* -----
|
|
7
7
|
*
|
|
8
8
|
*/
|
|
@@ -21,10 +21,14 @@ import { Column } from 'primereact/column';
|
|
|
21
21
|
import { Toolbar } from 'primereact/toolbar';
|
|
22
22
|
import { Button } from 'primereact/button';
|
|
23
23
|
import { ConfirmPopup, confirmPopup } from 'primereact/confirmpopup';
|
|
24
|
-
import {
|
|
24
|
+
import { FileUpload, FileUploadHandlerEvent} from 'primereact/fileupload';
|
|
25
25
|
|
|
26
26
|
import { EventEmitterContext } from '../core/EventEmitterContext';
|
|
27
27
|
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Defines properties for the file list.
|
|
31
|
+
*/
|
|
28
32
|
/**
|
|
29
33
|
* Defines properties for the file list.
|
|
30
34
|
*/
|
|
@@ -38,7 +42,40 @@ type FileListProps = {
|
|
|
38
42
|
|
|
39
43
|
/// The subdirectory of the datastore to list.
|
|
40
44
|
/// If blank, the base directory is listed.
|
|
41
|
-
subdir
|
|
45
|
+
subdir?: string
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A comma-separated list of file MIME types or file extensions.
|
|
49
|
+
* Default: .json
|
|
50
|
+
*
|
|
51
|
+
* ### Example: Filter by Extension:
|
|
52
|
+
* ```
|
|
53
|
+
* accept=".jpg,.png,.pdf" // Restricts uploads to JPG, PNG, and PDF files only
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* ### Example: Filter by mime type.
|
|
57
|
+
* ```
|
|
58
|
+
* accept="image/*,application/pdf" // Allows any image type and PDF files
|
|
59
|
+
* ```
|
|
60
|
+
*
|
|
61
|
+
* ### Example: All files
|
|
62
|
+
* ```
|
|
63
|
+
* accept="/*"
|
|
64
|
+
* ```
|
|
65
|
+
*
|
|
66
|
+
*/
|
|
67
|
+
filter?: string,
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Callback when an operation completes successfully.
|
|
71
|
+
* @returns void
|
|
72
|
+
*/
|
|
73
|
+
onSuccess? : (message:string) => void;
|
|
74
|
+
|
|
75
|
+
/***
|
|
76
|
+
* Callback when an operation results in an error.
|
|
77
|
+
*/
|
|
78
|
+
onError? : (message:string) => void;
|
|
42
79
|
}
|
|
43
80
|
|
|
44
81
|
/**
|
|
@@ -74,19 +111,37 @@ type FileItem = {
|
|
|
74
111
|
export const FileList: React.FC<FileListProps> = ({
|
|
75
112
|
domain = "DATASTORE",
|
|
76
113
|
enableUpload = false,
|
|
77
|
-
subdir
|
|
114
|
+
subdir,
|
|
115
|
+
filter=".json",
|
|
116
|
+
onSuccess,
|
|
117
|
+
onError
|
|
78
118
|
}) => {
|
|
79
119
|
|
|
80
|
-
const
|
|
120
|
+
const [uploadKey, setUploadKey] = useState(0);
|
|
121
|
+
const { invoke } = useContext(EventEmitterContext);
|
|
81
122
|
|
|
82
123
|
const [files, setFiles] = useState<FileItem[]>();
|
|
83
124
|
|
|
125
|
+
const makeTargetName = (s : string) => {
|
|
126
|
+
if (s !== null) {
|
|
127
|
+
if (subdir !== undefined) {
|
|
128
|
+
return `${subdir}/${s}`;
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
return s;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
return "";
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
84
139
|
/**
|
|
85
140
|
* Retrieve a list of files from an autocore-server DataStoreServelet.
|
|
86
141
|
*/
|
|
87
142
|
const listFiles = async () => {
|
|
88
143
|
try {
|
|
89
|
-
const args = subdir !== undefined ? {"subdir"
|
|
144
|
+
const args = subdir !== undefined ? { "subdir": subdir } : {};
|
|
90
145
|
let res = await invoke(domain, "list_files", args);
|
|
91
146
|
|
|
92
147
|
let items = [];
|
|
@@ -101,17 +156,9 @@ export const FileList: React.FC<FileListProps> = ({
|
|
|
101
156
|
setFiles(items);
|
|
102
157
|
}
|
|
103
158
|
catch (error) {
|
|
104
|
-
console.error("Failed to upload file list: " + error);
|
|
105
|
-
|
|
106
|
-
dispatch({
|
|
107
|
-
topic: "autocore-react/alert/error",
|
|
108
|
-
payload: {
|
|
109
|
-
message: `Failed to upload file list: ${error}`,
|
|
110
|
-
timeoutSec: 7,
|
|
111
|
-
severity: MessageSeverity.ERROR
|
|
112
|
-
}
|
|
113
|
-
});
|
|
114
159
|
|
|
160
|
+
if (onError)
|
|
161
|
+
onError(`Failed to upload file list: ${error}`);
|
|
115
162
|
}
|
|
116
163
|
|
|
117
164
|
|
|
@@ -122,18 +169,17 @@ export const FileList: React.FC<FileListProps> = ({
|
|
|
122
169
|
* @param file The file item selected in the DataTable
|
|
123
170
|
*/
|
|
124
171
|
const handleDownload = async (file: FileItem) => {
|
|
172
|
+
|
|
173
|
+
let target = makeTargetName(file.name);
|
|
174
|
+
|
|
125
175
|
try {
|
|
126
|
-
await invoke(domain, "download_file", { file_name:
|
|
176
|
+
await invoke(domain, "download_file", { file_name: target });
|
|
177
|
+
if (onSuccess)
|
|
178
|
+
onSuccess(`Downloaded file: ${file.name}`);
|
|
127
179
|
} catch (error) {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
payload: {
|
|
132
|
-
message: `Failed to downloading file: ${error}`,
|
|
133
|
-
timeoutSec: 7,
|
|
134
|
-
severity: MessageSeverity.ERROR
|
|
135
|
-
}
|
|
136
|
-
});
|
|
180
|
+
|
|
181
|
+
if (onError)
|
|
182
|
+
onError(`Failed downloading file: ${error}`);
|
|
137
183
|
}
|
|
138
184
|
|
|
139
185
|
};
|
|
@@ -144,25 +190,105 @@ export const FileList: React.FC<FileListProps> = ({
|
|
|
144
190
|
*/
|
|
145
191
|
const handleDelete = async (file_name: string) => {
|
|
146
192
|
|
|
193
|
+
let target = makeTargetName(file_name);
|
|
194
|
+
|
|
147
195
|
try {
|
|
148
|
-
await invoke(domain, "delete_file", { file_name:
|
|
196
|
+
await invoke(domain, "delete_file", { file_name: target });
|
|
197
|
+
if (onSuccess)
|
|
198
|
+
onSuccess(`Deleted file: ${file_name}`);
|
|
199
|
+
|
|
200
|
+
listFiles(); // Refresh the file list after successful upload
|
|
201
|
+
|
|
149
202
|
} catch (error) {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
dispatch({
|
|
153
|
-
topic: "autocore-react/alert/error",
|
|
154
|
-
payload: {
|
|
155
|
-
message: `Failed deleting file: ${error}`,
|
|
156
|
-
timeoutSec: 7,
|
|
157
|
-
severity: MessageSeverity.ERROR
|
|
158
|
-
}
|
|
159
|
-
});
|
|
203
|
+
if (onError)
|
|
204
|
+
onError(`Failed to delete file: ${error}`);
|
|
160
205
|
}
|
|
161
206
|
|
|
162
207
|
|
|
163
208
|
listFiles();
|
|
164
209
|
};
|
|
165
210
|
|
|
211
|
+
/**
|
|
212
|
+
* Handles the upload of files selected through the PrimeReact FileUpload component.
|
|
213
|
+
* This function is triggered when a user selects files for upload and it processes each file asynchronously.
|
|
214
|
+
*
|
|
215
|
+
* The function reads the selected file as an ArrayBuffer, converts it to a Base64-encoded string, and then
|
|
216
|
+
* sends it to the server using a custom function `invoke` which interacts with the server via API calls.
|
|
217
|
+
* Upon successful upload, a success message is dispatched to the application's notification system. If the
|
|
218
|
+
* upload fails, an error message is similarly dispatched.
|
|
219
|
+
*
|
|
220
|
+
* Usage of this function requires that it be attached to a FileUpload component's event handler in the React component.
|
|
221
|
+
*
|
|
222
|
+
* @param {FileUploadSelectEvent} event - The event object provided by the FileUpload component, containing the files selected by the user.
|
|
223
|
+
*
|
|
224
|
+
* The `FileUploadSelectEvent` type should include:
|
|
225
|
+
* - `files`: An array of `File` objects that the user has selected for upload.
|
|
226
|
+
*
|
|
227
|
+
* This function utilizes the `FileReader` API to read the contents of the file. It checks if the read result
|
|
228
|
+
* is an instance of `ArrayBuffer` before proceeding to convert it to a Base64 string. Errors during file reading
|
|
229
|
+
* or uploading are caught and appropriate actions are taken (e.g., logging the error, dispatching error notifications).
|
|
230
|
+
*
|
|
231
|
+
* Note:
|
|
232
|
+
* - Ensure that the `invoke` function is properly implemented to handle the API request for file uploading.
|
|
233
|
+
* - Adjust the maximum file size and the types of files accepted by the FileUpload component according to your application's requirements.
|
|
234
|
+
* - This handler assumes a single file handling scenario. If multiple file uploads are needed, modifications to the iteration over `event.files` may be required.
|
|
235
|
+
*/
|
|
236
|
+
const handleUpload = async (event: FileUploadHandlerEvent) => {
|
|
237
|
+
const files = event.files;
|
|
238
|
+
const file = files[0]; // Assuming single file upload
|
|
239
|
+
|
|
240
|
+
let target = makeTargetName(file.name);
|
|
241
|
+
|
|
242
|
+
const reader = new FileReader();
|
|
243
|
+
reader.onload = async (e: ProgressEvent<FileReader>) => {
|
|
244
|
+
|
|
245
|
+
// Convert array buffer to base64
|
|
246
|
+
const arrayBuffer = e.target?.result as ArrayBuffer;
|
|
247
|
+
const base64String = arrayBufferToBase64(arrayBuffer);
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
await invoke(domain, "write_file", { file_name: target, value: base64String });
|
|
251
|
+
|
|
252
|
+
if (onSuccess)
|
|
253
|
+
onSuccess(`Uploaded file ${file.name}`);
|
|
254
|
+
|
|
255
|
+
// Refresh the file list after successful upload
|
|
256
|
+
listFiles();
|
|
257
|
+
|
|
258
|
+
} catch (error: any) {
|
|
259
|
+
if (onError)
|
|
260
|
+
onError(`Failed to upload file: ${error}`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Reset upload state of button so it show the file upload dialog again.
|
|
264
|
+
resetUpload();
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
reader.onerror = (error) => {
|
|
268
|
+
if (onError)
|
|
269
|
+
onError(`Error reading file: ${error}`);
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
reader.readAsArrayBuffer(file);
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
function arrayBufferToBase64(buffer: ArrayBuffer): string {
|
|
277
|
+
let binary = '';
|
|
278
|
+
let bytes = new Uint8Array(buffer);
|
|
279
|
+
let len = bytes.byteLength;
|
|
280
|
+
for (let i = 0; i < len; i++) {
|
|
281
|
+
binary += String.fromCharCode(bytes[i]);
|
|
282
|
+
}
|
|
283
|
+
return window.btoa(binary);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
const resetUpload = () => {
|
|
288
|
+
setUploadKey(prevKey => prevKey + 1); // Increment key to force re-render
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
|
|
166
292
|
const title = `File Listing [/${subdir !== undefined ? subdir : ''}]`;
|
|
167
293
|
const toolbarStartContents = (
|
|
168
294
|
<React.Fragment>
|
|
@@ -173,12 +299,19 @@ export const FileList: React.FC<FileListProps> = ({
|
|
|
173
299
|
const toolbarEndContents = (
|
|
174
300
|
<React.Fragment>
|
|
175
301
|
{enableUpload && (
|
|
176
|
-
<
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
302
|
+
<FileUpload
|
|
303
|
+
key={uploadKey}
|
|
304
|
+
customUpload={true}
|
|
305
|
+
auto
|
|
306
|
+
uploadHandler={handleUpload}
|
|
307
|
+
accept={filter}
|
|
308
|
+
maxFileSize={25000} // Set maximum file size as needed
|
|
309
|
+
mode="basic"
|
|
310
|
+
chooseLabel=""
|
|
311
|
+
chooseOptions={{
|
|
312
|
+
icon: 'pi pi-upload',
|
|
313
|
+
className: 'p-button-icon-only p-button-text p-button-rounded p-mr-2'
|
|
314
|
+
}}
|
|
182
315
|
/>
|
|
183
316
|
|
|
184
317
|
)}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Copyright (C) 2024 Automated Design Corp. All Rights Reserved.
|
|
3
3
|
* Created Date: 2024-01-16 14:17:02
|
|
4
4
|
* -----
|
|
5
|
-
* Last Modified: 2024-
|
|
5
|
+
* Last Modified: 2024-05-01 12:14:27
|
|
6
6
|
* Modified By: ADC
|
|
7
7
|
* -----
|
|
8
8
|
*
|
|
@@ -10,13 +10,13 @@
|
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
import {Component} from 'react';
|
|
13
|
+
import { Component } from 'react';
|
|
14
14
|
//import useFitText from 'use-fit-text';
|
|
15
15
|
import { format as numerableFormat } from 'numerable';
|
|
16
16
|
import clsx from 'clsx';
|
|
17
|
-
import { EventEmitterContext, EventEmitterContextType} from '../core/EventEmitterContext';
|
|
17
|
+
import { EventEmitterContext, EventEmitterContextType } from '../core/EventEmitterContext';
|
|
18
18
|
|
|
19
|
-
import {IPositionContext} from '../core/PositionContext';
|
|
19
|
+
import { IPositionContext } from '../core/PositionContext';
|
|
20
20
|
import type { NumerableFormatOptions } from '../core/NumerableTypes';
|
|
21
21
|
|
|
22
22
|
/**
|
|
@@ -84,23 +84,69 @@ interface State {
|
|
|
84
84
|
|
|
85
85
|
|
|
86
86
|
/**
|
|
87
|
-
* `ValueDisplay` is a React component
|
|
88
|
-
*
|
|
89
|
-
*
|
|
87
|
+
* `ValueDisplay` is a React component designed to display a value which can be a string, number, or null.
|
|
88
|
+
* It supports formatting numeric values using the `numerableFormat` function, and is capable of dynamic positioning
|
|
89
|
+
* and sizing within its parent container. The component integrates with an `EventEmitterContext` to listen for
|
|
90
|
+
* updates to its value based on a specified topic, making it ideal for real-time data display scenarios.
|
|
91
|
+
*
|
|
92
|
+
* The component can be absolutely positioned based on `x` and `y` props, and its size can be adjusted using
|
|
93
|
+
* `width` and `height` props. If `useAbsolutePositioning` is true, it will position itself based on the provided
|
|
94
|
+
* coordinates; otherwise, it will position relatively.
|
|
95
|
+
*
|
|
96
|
+
* ### Props:
|
|
97
|
+
* - `value`: The initial value to display, which can be updated via props or context events.
|
|
98
|
+
* - `x`, `y`: Coordinates for absolute positioning within the parent container.
|
|
99
|
+
* - `width`, `height`: Dimensions of the component. If height is not provided, it defaults to the width.
|
|
100
|
+
* - `format`: A string specifying the format for numeric values (see numerable.js documentation for format strings).
|
|
101
|
+
* - `formatOptions`: Additional formatting options as per numerable.js.
|
|
102
|
+
* - `className`: Custom class for CSS styling.
|
|
103
|
+
* - `useAbsolutePositioning`: Boolean to toggle absolute positioning.
|
|
104
|
+
* - `topic`: Optional string to subscribe to context updates for dynamic value changes.
|
|
105
|
+
*
|
|
106
|
+
* ### Usage Example:
|
|
107
|
+
* ```tsx
|
|
108
|
+
* import React from 'react';
|
|
109
|
+
* import ReactDOM from 'react-dom';
|
|
110
|
+
* import { ValueDisplay } from './components/ValueDisplay';
|
|
111
|
+
*
|
|
112
|
+
* const App = () => {
|
|
113
|
+
* return (
|
|
114
|
+
* <div>
|
|
115
|
+
* <ValueDisplay
|
|
116
|
+
* value={1234.56}
|
|
117
|
+
* x={100}
|
|
118
|
+
* y={200}
|
|
119
|
+
* width={150}
|
|
120
|
+
* height={50}
|
|
121
|
+
* format="0,0.00"
|
|
122
|
+
* className="numeric-display"
|
|
123
|
+
* useAbsolutePositioning={true}
|
|
124
|
+
* topic="priceUpdate"
|
|
125
|
+
* />
|
|
126
|
+
* </div>
|
|
127
|
+
* );
|
|
128
|
+
* };
|
|
129
|
+
*
|
|
130
|
+
* ReactDOM.render(<App />, document.getElementById('root'));
|
|
131
|
+
* ```
|
|
132
|
+
*
|
|
133
|
+
* In this example, `ValueDisplay` is used to show a numeric value formatted as a string with two decimal places.
|
|
134
|
+
* It is positioned absolutely at coordinates (100, 200) with a specified width and height. The component listens
|
|
135
|
+
* for updates on the "priceUpdate" topic to dynamically update its displayed value.
|
|
90
136
|
*/
|
|
91
137
|
class ValueDisplay extends Component<Props, State> {
|
|
92
|
-
|
|
138
|
+
|
|
93
139
|
/** Defines the context type to subscribe to changes using EventEmitter. */
|
|
94
140
|
static contextType = EventEmitterContext;
|
|
95
141
|
|
|
96
|
-
|
|
142
|
+
|
|
97
143
|
/** ID for the subscription to the topic, used to unsubscribe on component unmount. */
|
|
98
144
|
protected unsubscribeTopicId: number | null = null;
|
|
99
145
|
|
|
100
146
|
/**
|
|
101
147
|
* The constructor initializes the component state and binds the initial value.
|
|
102
148
|
* @param props The properties passed to the component, including initial value and other display options.
|
|
103
|
-
*/
|
|
149
|
+
*/
|
|
104
150
|
constructor(props: Props) {
|
|
105
151
|
super(props);
|
|
106
152
|
this.state = {
|
|
@@ -112,7 +158,7 @@ class ValueDisplay extends Component<Props, State> {
|
|
|
112
158
|
/**
|
|
113
159
|
* Upon mounting, the component subscribes to updates on the specified topic if it exists,
|
|
114
160
|
* updating its state with the new value when the topic publishes updates.
|
|
115
|
-
*/
|
|
161
|
+
*/
|
|
116
162
|
componentDidMount() {
|
|
117
163
|
const { topic } = this.props;
|
|
118
164
|
if (topic) {
|
|
@@ -127,19 +173,19 @@ class ValueDisplay extends Component<Props, State> {
|
|
|
127
173
|
* If the value prop changes, the component updates its state with the new value.
|
|
128
174
|
* This ensures that the component remains in sync with its props.
|
|
129
175
|
* @param prevProps The previous properties for comparison to detect changes.
|
|
130
|
-
*/
|
|
176
|
+
*/
|
|
131
177
|
componentDidUpdate(prevProps: Props) {
|
|
132
178
|
// Check if the value prop has changed
|
|
133
179
|
if (this.props.value !== prevProps.value) {
|
|
134
180
|
// Update the state with the new value
|
|
135
181
|
this.setState({ subscribedValue: this.props.value });
|
|
136
182
|
}
|
|
137
|
-
}
|
|
183
|
+
}
|
|
138
184
|
|
|
139
185
|
/**
|
|
140
186
|
* Before the component is unmounted, it unsubscribes from the topic to prevent memory leaks
|
|
141
187
|
* and unnecessary updates from occurring.
|
|
142
|
-
*/
|
|
188
|
+
*/
|
|
143
189
|
componentWillUnmount() {
|
|
144
190
|
if (this.unsubscribeTopicId) {
|
|
145
191
|
const { unsubscribe } = this.context as EventEmitterContextType;
|
|
@@ -151,13 +197,13 @@ class ValueDisplay extends Component<Props, State> {
|
|
|
151
197
|
* Renders the component with styling and formatting based on the provided properties and state.
|
|
152
198
|
* Supports absolute or relative positioning and scales the display based on the context's dimensions.
|
|
153
199
|
* @returns A styled `div` element displaying the formatted value.
|
|
154
|
-
*/
|
|
200
|
+
*/
|
|
155
201
|
render() {
|
|
156
202
|
const { x, y, width, height, format, formatOptions, className, useAbsolutePositioning } = this.props;
|
|
157
203
|
const { subscribedValue, fontSize } = this.state;
|
|
158
204
|
const { scale, xOffset, yOffset } = this.context as IPositionContext;
|
|
159
205
|
|
|
160
|
-
const style
|
|
206
|
+
const style: React.CSSProperties = {
|
|
161
207
|
position: useAbsolutePositioning ? 'absolute' : 'relative',
|
|
162
208
|
display: useAbsolutePositioning ? "" : "inline-block",
|
|
163
209
|
verticalAlign: 'middle',
|
|
@@ -170,12 +216,21 @@ class ValueDisplay extends Component<Props, State> {
|
|
|
170
216
|
whiteSpace: 'nowrap',
|
|
171
217
|
};
|
|
172
218
|
|
|
219
|
+
// Determine how to display the value
|
|
220
|
+
let displayValue;
|
|
221
|
+
if (typeof subscribedValue === 'number' || (typeof subscribedValue === 'string' && !isNaN(Number(subscribedValue)))) {
|
|
222
|
+
displayValue = numerableFormat(subscribedValue, format, formatOptions);
|
|
223
|
+
} else {
|
|
224
|
+
displayValue = subscribedValue; // Directly use the string if it's not numeric
|
|
225
|
+
}
|
|
226
|
+
|
|
173
227
|
return (
|
|
174
228
|
<div className={clsx(className)} style={style}>
|
|
175
|
-
{
|
|
229
|
+
{displayValue}
|
|
176
230
|
</div>
|
|
177
231
|
);
|
|
178
232
|
}
|
|
233
|
+
|
|
179
234
|
}
|
|
180
235
|
|
|
181
236
|
export { ValueDisplay, NumerableFormatOptions };
|
package/src/hooks/adsHooks.tsx
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
* Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
|
|
3
3
|
* Created Date: 2024-04-26 09:04:40
|
|
4
4
|
* -----
|
|
5
|
-
* Last Modified: 2024-04-
|
|
5
|
+
* Last Modified: 2024-04-30 21:32:01
|
|
6
6
|
* -----
|
|
7
7
|
*
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
import { useContext, useRef, useEffect } from 'react';
|
|
12
|
+
import { useContext, useRef, useEffect, useCallback } from 'react';
|
|
13
13
|
import { EventEmitterContext } from '../core/EventEmitterContext';
|
|
14
14
|
|
|
15
15
|
|
|
@@ -163,6 +163,80 @@ export function useAdsWriteValue(symbolName: string) {
|
|
|
163
163
|
|
|
164
164
|
|
|
165
165
|
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* useAdsWriteScaledValue is a custom React hook that enables writing scaled numerical values to a backend system.
|
|
170
|
+
* It applies a specified scale and offset to a numeric value before sending it over an ADS connection.
|
|
171
|
+
* This hook is ideal for scenarios where numeric data needs to be adjusted according to dynamically configurable
|
|
172
|
+
* scale factors before being persisted or processed by a backend system.
|
|
173
|
+
*
|
|
174
|
+
* @param symbolName The symbol name in the backend system where the value will be written.
|
|
175
|
+
* @param scale The scale factor to be applied to the value.
|
|
176
|
+
* @param offset The offset to be applied after scaling the value.
|
|
177
|
+
* @returns A function that takes a numeric value, applies the scaling and offset, and sends the modified value to the backend.
|
|
178
|
+
*
|
|
179
|
+
* @example
|
|
180
|
+
* This example demonstrates how to use the `useAdsWriteScaledValue` hook within a component that allows users
|
|
181
|
+
* to input a value in inches, which is then automatically converted to millimeters (if the scale is set for such conversion)
|
|
182
|
+
* based on a dynamic scale factor managed in the component's state.
|
|
183
|
+
*
|
|
184
|
+
* ```tsx
|
|
185
|
+
* import React, { useState } from 'react';
|
|
186
|
+
* import { useAdsWriteScaledValue } from './hooks';
|
|
187
|
+
*
|
|
188
|
+
* const MeasurementInput: React.FC = () => {
|
|
189
|
+
* const [scale, setScale] = useState<number>(1 / 25.4); // Initial scale for converting inches to millimeters.
|
|
190
|
+
* const [offset, setOffset] = useState<number>(0); // No offset by default.
|
|
191
|
+
*
|
|
192
|
+
* // The hook is used here with the scale and offset state variables.
|
|
193
|
+
* const writeMeasurement = useAdsWriteScaledValue("GIO.axisX.position", scale, offset);
|
|
194
|
+
*
|
|
195
|
+
* // This function is called when the input field value changes.
|
|
196
|
+
* const handleMeasurementChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
197
|
+
* const valueInInches = parseFloat(event.target.value);
|
|
198
|
+
* writeMeasurement(valueInInches); // Write the scaled value (converted to millimeters).
|
|
199
|
+
* };
|
|
200
|
+
*
|
|
201
|
+
* return (
|
|
202
|
+
* <div>
|
|
203
|
+
* <label>Enter measurement in inches:</label>
|
|
204
|
+
* <input type="number" onChange={handleMeasurementChange} />
|
|
205
|
+
* </div>
|
|
206
|
+
* );
|
|
207
|
+
* };
|
|
208
|
+
*
|
|
209
|
+
* export default MeasurementInput;
|
|
210
|
+
* ```
|
|
211
|
+
*
|
|
212
|
+
* In this component, `writeMeasurement` is a function returned by the `useAdsWriteScaledValue` hook that takes a value in inches,
|
|
213
|
+
* converts it to millimeters using the current `scale`, and writes the result to a backend symbol. The `scale` and `offset` can be adjusted
|
|
214
|
+
* dynamically if needed, for instance, based on user selection or other external configurations.
|
|
215
|
+
*/
|
|
216
|
+
export function useAdsWriteScaledValue(symbolName: string, scale: number, offset: number) {
|
|
217
|
+
const { invoke } = useContext(EventEmitterContext);
|
|
218
|
+
const domain = "ADS";
|
|
219
|
+
const fname = "write_value";
|
|
220
|
+
|
|
221
|
+
return useCallback(async (value: number) => {
|
|
222
|
+
|
|
223
|
+
// In autocore-react, we multiple to scale incoming values,
|
|
224
|
+
// divide to scale outgoing values.
|
|
225
|
+
// This is an OUTGOING value, so we divide.
|
|
226
|
+
|
|
227
|
+
const scaledValue = (value - offset) / scale;
|
|
228
|
+
try {
|
|
229
|
+
await invoke(domain, fname, { symbol_name: symbolName, value: scaledValue });
|
|
230
|
+
} catch (err) {
|
|
231
|
+
console.error(`Error writing scaled value to tag ${symbolName}: ${err}`);
|
|
232
|
+
}
|
|
233
|
+
}, [symbolName, scale, offset, invoke]);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
166
240
|
/**
|
|
167
241
|
* Custom hook to send a "tap" action, which sends true followed by false after a short delay,
|
|
168
242
|
* to a specified symbol in the backend. This is used to simulate a button tap or momentary switch.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
|
|
3
|
+
* Created Date: 2024-04-30 12:14:43
|
|
4
|
+
* -----
|
|
5
|
+
* Last Modified: 2024-04-30 12:15:46
|
|
6
|
+
* -----
|
|
7
|
+
*
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
export {useAdsRegisterSymbols, useAdsWriteValue, useAdsTapValue} from "./adsHooks";
|
|
12
|
+
export {useScaledValue, kMillimeters2Inches } from './useScaledValue';
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
|
|
3
|
+
* Created Date: 2024-04-30 11:41:59
|
|
4
|
+
* -----
|
|
5
|
+
* Last Modified: 2024-04-30 21:33:42
|
|
6
|
+
* -----
|
|
7
|
+
*
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
import { useCallback, useState } from 'react';
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
export const kMillimeters2Inches: number = 1 / 25.4;
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
type UseScaledValueReturn = [number, (newValue: number) => void];
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A custom React hook for converting values between different scales,
|
|
22
|
+
* with support for dynamically updating the scale and offset. This hook manages values
|
|
23
|
+
* in a base unit and allows for easy conversion to a display unit, updating
|
|
24
|
+
* reactively to changes in the conversion factors.
|
|
25
|
+
*
|
|
26
|
+
* @param initialValue - The initial value in the base unit.
|
|
27
|
+
* @param scale - The dynamic scale factor used for conversion to the display unit.
|
|
28
|
+
* @param offset - An optional offset applied after scaling (default is 0).
|
|
29
|
+
* @returns A tuple containing the display value and a setter function for updating
|
|
30
|
+
* the value in the display unit.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* Here's how to use `useScaledValue` in a component that fetches a scale factor from a backend
|
|
34
|
+
* and allows the user to input values in a converted scale, which are then handled in a base unit:
|
|
35
|
+
*
|
|
36
|
+
* ```tsx
|
|
37
|
+
* import React, { useState, useEffect } from 'react';
|
|
38
|
+
* import { useScaledValue } from './hooks/useScaledValue';
|
|
39
|
+
*
|
|
40
|
+
* const MeasurementInput: React.FC = () => {
|
|
41
|
+
* const [units, setUnits] = useState<number>(1); // Start with a default scale of 1
|
|
42
|
+
* const [xPosition, setXPosition] = useScaledValue(0, units);
|
|
43
|
+
*
|
|
44
|
+
* useEffect(() => {
|
|
45
|
+
* async function fetchScale() {
|
|
46
|
+
* try {
|
|
47
|
+
* // Simulate fetching scale factor from a backend
|
|
48
|
+
* const res = await invoke("GNV", "read_value", { group: "ux", key: "kSelectedUnits" });
|
|
49
|
+
* setUnits(res.data); // Update scale based on backend response
|
|
50
|
+
* } catch (error) {
|
|
51
|
+
* console.error('Failed to fetch units', error);
|
|
52
|
+
* }
|
|
53
|
+
* }
|
|
54
|
+
* fetchScale();
|
|
55
|
+
* }, []);
|
|
56
|
+
*
|
|
57
|
+
* return (
|
|
58
|
+
* <input
|
|
59
|
+
* type="number"
|
|
60
|
+
* value={xPosition.toFixed(2)} // Display the value formatted to 2 decimal places
|
|
61
|
+
* onChange={(e) => setXPosition(parseFloat(e.target.value))}
|
|
62
|
+
* />
|
|
63
|
+
* );
|
|
64
|
+
* };
|
|
65
|
+
*
|
|
66
|
+
* export default MeasurementInput;
|
|
67
|
+
* ```
|
|
68
|
+
*
|
|
69
|
+
* In this example, `useScaledValue` is used to manage a measurement input in a dynamic unit system.
|
|
70
|
+
* The component fetches the conversion scale from the backend upon component mounting and updates the
|
|
71
|
+
* input display accordingly. The user's input is converted back to the base unit before being processed.
|
|
72
|
+
*/
|
|
73
|
+
export function useScaledValue(initialValue: number, scale: number, offset: number = 0): UseScaledValueReturn {
|
|
74
|
+
|
|
75
|
+
const [displayValue, setDisplayValue] = useState<number>(initialValue * scale + offset);
|
|
76
|
+
|
|
77
|
+
const handleSetDisplayValue = useCallback((newValue: number) => {
|
|
78
|
+
|
|
79
|
+
// In autocore-react, we multiple to scale incoming values,
|
|
80
|
+
// divide to scale outgoing values.
|
|
81
|
+
// This is an INCOMING value, so we multiply.
|
|
82
|
+
|
|
83
|
+
const newDisplayValue = newValue * scale + offset;
|
|
84
|
+
setDisplayValue(newDisplayValue);
|
|
85
|
+
|
|
86
|
+
}, [scale, offset]);
|
|
87
|
+
|
|
88
|
+
return [displayValue, handleSetDisplayValue];
|
|
89
|
+
}
|