@adcops/autocore-react 3.0.19 → 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.
@@ -2,18 +2,65 @@
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-25 16:40:53
5
+ * Last Modified: 2024-04-30 08:33:37
6
6
  * -----
7
7
  *
8
8
  */
9
9
 
10
+ /** @file
11
+ * `ValueInput` is a React component for number input that encapsulates various features
12
+ * such as custom numeric formatting, optional currency formatting, increment and decrement
13
+ * buttons, and validation. This component uses the PrimeReact `InputNumber` control
14
+ * to provide a rich input experience, including handling both decimal and currency modes,
15
+ * with configurable precision and optional prefix/suffix text.
16
+ *
17
+ * Properties:
18
+ * - `label`: Label text displayed on the input field.
19
+ * - `value`: Current numeric value of the input field.
20
+ * - `min`: Minimum allowable value.
21
+ * - `max`: Maximum allowable value.
22
+ * - `minPrecision`: Minimum number of decimal places to display.
23
+ * - `maxPrecision`: Maximum number of decimal places allowed.
24
+ * - `mode`: Determines whether the input is treated as a plain decimal or currency. Defaults to "decimal".
25
+ * - `currency`: ISO 4217 currency code for formatting the value as currency.
26
+ * - `prefix`: String to display before the value.
27
+ * - `suffix`: String to display after the value.
28
+ * - `showButtons`: Whether to display increment and decrement buttons.
29
+ * - `step`: The amount by which the value should be incremented or decremented.
30
+ * - `locale`: Locale code for formatting the value.
31
+ * - `description`: Additional descriptive text to display below the input.
32
+ * - `disabled`: Whether the input is disabled.
33
+ * - `dispatchTopic`: Event topic to dispatch on value change.
34
+ * - `placeholder`: Placeholder text when the input is empty.
35
+ * - `onValueChanged`: Callback function that is called when the user accepts a new value.
36
+ *
37
+ * Example Usage:
38
+ * ```tsx
39
+ * <ValueInput
40
+ * label="Quantity"
41
+ * value={10}
42
+ * min={1}
43
+ * max={100}
44
+ * minPrecision={0}
45
+ * maxPrecision={2}
46
+ * mode="decimal"
47
+ * showButtons={true}
48
+ * step={1}
49
+ * locale="en-US"
50
+ * onValueChanged={(newValue) => console.log("New Value:", newValue)}
51
+ * />
52
+ * ```
53
+ *
54
+ * This example creates a `ValueInput` component for entering quantities, with values ranging from 1 to 100,
55
+ * allowing up to 2 decimal places. Increment and decrement buttons are visible, and the new value is logged
56
+ * to the console when accepted.
57
+ */
10
58
 
11
- import React, { createRef } from "react";
12
59
 
60
+ import React, { useState, useRef, useEffect, useContext } from 'react';
13
61
  import { InputNumber } from 'primereact/inputnumber';
14
- import { Button } from "primereact/button";
15
-
16
62
  import { EventEmitterContext } from "../core/EventEmitterContext";
63
+ import { Button } from 'primereact/button';
17
64
 
18
65
  /**
19
66
  * Properties of the ValueInput component.
@@ -34,12 +81,12 @@ interface ValueInputProps {
34
81
  /**
35
82
  * Minimum value for the field.
36
83
  */
37
- min: number | undefined;
84
+ min?: number | undefined;
38
85
 
39
86
  /**
40
87
  * Minimum value for the field.
41
88
  */
42
- max: number | undefined;
89
+ max?: number | undefined;
43
90
 
44
91
  /**
45
92
  * Minimum number of decimal points. The user will not
@@ -49,7 +96,7 @@ interface ValueInputProps {
49
96
  * the component will throw an error.
50
97
  * @default 0
51
98
  */
52
- minPrecision: number | undefined;
99
+ minPrecision?: number | undefined;
53
100
 
54
101
 
55
102
  /**
@@ -58,7 +105,7 @@ interface ValueInputProps {
58
105
  * the component will throw an error.
59
106
  * @default 3
60
107
  */
61
- maxPrecision: number | undefined;
108
+ maxPrecision?: number | undefined;
62
109
 
63
110
 
64
111
  /**
@@ -67,7 +114,7 @@ interface ValueInputProps {
67
114
  * currency type using the currency property.
68
115
  * @default "decimal"
69
116
  */
70
- mode: "currency" | "decimal" | undefined;
117
+ mode?: "currency" | "decimal" | undefined;
71
118
 
72
119
 
73
120
  /**
@@ -78,19 +125,19 @@ interface ValueInputProps {
78
125
  *
79
126
  * @default "USD"
80
127
  */
81
- currency: string;
128
+ currency?: string;
82
129
 
83
130
  /**
84
131
  * An optional prefix before the value of the field.
85
132
  * Unlike the TextInput control, this prefix is internal to the field.
86
133
  */
87
- prefix: string | undefined;
134
+ prefix?: string | undefined;
88
135
 
89
136
  /**
90
137
  * An optional suffix after the value of the field.
91
138
  * Unlike the TextInput control, this prefix is internal to the field.
92
139
  */
93
- suffix: string | undefined;
140
+ suffix?: string | undefined;
94
141
 
95
142
  /**
96
143
  * Set true to display buttons to increment/decrement the value.
@@ -98,12 +145,12 @@ interface ValueInputProps {
98
145
  *
99
146
  * @default false
100
147
  */
101
- showButtons: boolean;
148
+ showButtons?: boolean;
102
149
 
103
150
  /**
104
151
  * The amount clicking an increment/decrement buttion will change the value.
105
152
  */
106
- step: number | undefined;
153
+ step?: number | undefined;
107
154
 
108
155
 
109
156
  /**
@@ -112,25 +159,25 @@ interface ValueInputProps {
112
159
  *
113
160
  * @default "en-US"
114
161
  */
115
- locale: string | undefined;
162
+ locale?: string | undefined;
116
163
 
117
164
  /**
118
165
  * A small, advisory text below the field.
119
166
  */
120
- description: React.ReactNode | undefined;
167
+ description?: React.ReactNode | undefined;
121
168
 
122
169
  /**
123
170
  * If true, all functions of the field will be disabled.
124
171
  */
125
- disabled: boolean | undefined;
172
+ disabled?: boolean | undefined;
126
173
 
127
174
  /** Topic on which the value will be dispatched through the user interfave on successful data entry. */
128
- dispatchTopic: string | undefined;
175
+ dispatchTopic?: string | undefined;
129
176
 
130
177
  /**
131
178
  * Placeholder string to display if the value is empty.
132
179
  */
133
- placeholder: string | undefined;
180
+ placeholder?: string | undefined;
134
181
 
135
182
  /**
136
183
  * The user has accepted a new value.
@@ -139,229 +186,182 @@ interface ValueInputProps {
139
186
  onValueChanged?(newValue: number): void;
140
187
  }
141
188
 
142
- /**
143
- * State variables of the ValueInput component.
144
- */
145
- interface ValueInputState {
146
-
147
- entryValue: number | null;
148
- currentValue: number | null;
149
- editing: boolean;
150
- }
151
-
152
-
153
189
  /**
154
190
  * A convenient field with all the usual features of inputing numbers.
155
191
  * Wraps the common features of use of a InputNumber, p-inputgroup, some icon buttons,
156
192
  * accepting and rejecting values and keyboard management.
157
193
  */
158
- export class ValueInput extends React.Component<ValueInputProps, ValueInputState> {
159
-
160
- // Here's an example of using the Application-wide EventEmitter con
161
- // Define the contextType for the class to access the context
162
- static contextType = EventEmitterContext;
163
- // After specifying contextType, you can declare the context's type for the TypeScript compiler.
164
- // Basically, we're telling TypeScript the type of the context; this line doesn't
165
- // actually do any linking linking to the EventEmitterContext.
166
- declare context: React.ContextType<typeof EventEmitterContext>;
167
-
168
-
169
-
194
+ export const ValueInput: React.FC<ValueInputProps> = ({
195
+ label = '',
196
+ value = null,
197
+ min = undefined,
198
+ max = undefined,
199
+ minPrecision = 0,
200
+ maxPrecision = 3,
201
+ mode = "decimal",
202
+ currency = "USD",
203
+ prefix = undefined,
204
+ suffix = undefined,
205
+ showButtons = false,
206
+ step = 1,
207
+ locale = "en-US",
208
+ description = undefined,
209
+ disabled = false,
210
+ dispatchTopic = undefined,
211
+ placeholder = undefined,
212
+ onValueChanged = undefined
213
+ }) => {
214
+ const [entryValue, setEntryValue] = useState<number | null>(value);
215
+ const [currentValue, setCurrentValue] = useState<number | null>(value);
216
+ const [bufferedValue, setBufferedValue] = useState<number | null>(value);
217
+ const [editing, setEditing] = useState<boolean>(false);
218
+ const [invalidValue, setInvalidValue] = useState<boolean>(false);
219
+ const inputRef = useRef<InputNumber>(null);
220
+ const eventEmitter = useContext(EventEmitterContext);
221
+
222
+ useEffect(() => {
223
+
224
+ if (bufferedValue !== null) {
225
+ setCurrentValue(bufferedValue);
226
+ setBufferedValue(null);
227
+ setInvalidValue(false);
228
+ }
229
+ else if (value !== currentValue) {
230
+ setCurrentValue(value);
231
+ setEntryValue(value);
232
+ setEditing(false);
233
+ setInvalidValue(false);
234
+ }
235
+
170
236
 
171
- /**
172
- * Default properties for the component.
173
- */
174
- static defaultProps = {
175
- label: '',
176
- value: undefined,
177
- keyFilter: undefined,
178
- writeTopic: undefined,
179
- onValueChanged: undefined,
180
- description: undefined,
181
- prefix: undefined,
182
- suffix: undefined,
183
- disabled: false,
184
- dispatchTopic: undefined,
185
- placeholder: undefined,
186
- validator: undefined,
187
- min: undefined,
188
- max: undefined,
189
- minPrecision: 0,
190
- maxPrecision: 3,
191
- mode: "decimal",
192
- showButtons: false,
193
- step: 1,
194
- locale: "en-US",
195
- currency: "USD"
196
- };
197
- inputRef: React.RefObject<HTMLInputElement>;
237
+ }, [value, currentValue]);
198
238
 
199
239
  /**
240
+ * Buffers the original value, if editing just starting,
241
+ * and updates the entry value.
200
242
  *
201
- * @param {FooterViewProps} props
243
+ * @param val New value being entered.
202
244
  */
203
- constructor(props: ValueInputProps) {
204
- super(props);
205
- this.state = {
206
- entryValue: props.value,
207
- currentValue: props.value,
208
- editing: false
209
- };
210
-
211
- this.inputRef = createRef();
212
- }
245
+ const handleBufferValue = (val: number | null) => {
246
+ if (!editing) {
247
+ setBufferedValue(currentValue);
248
+ setEditing(true);
249
+ }
250
+ setEntryValue(val);
251
+ };
213
252
 
214
253
  /**
215
- * The component has been loaded into the DOM.
254
+ * Returns true if the new value falls within specified parameters.
255
+ * @param val The new value.
256
+ * @returns
216
257
  */
217
- componentDidMount() {
218
- }
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
-
231
-
232
- private onBufferValue(val: number | null) {
233
- if (val === null)
234
- return;
235
-
236
- if (!this.state.editing) {
237
- this.setState({
238
- entryValue: val, //this.state.currentValue,
239
- editing: true
240
- }, () => {
241
-
242
- setTimeout(() => {
243
- if (this.inputRef.current) {
244
- this.inputRef.current.focus();
245
- }
246
-
247
- }, 0);
248
-
258
+ const validateValue = (val : number) : boolean => {
259
+
260
+ if (max !== undefined) {
261
+ if (val > max) {
262
+ return false;
249
263
  }
250
- );
251
264
  }
252
- else {
253
- this.setState({
254
- entryValue: val
255
- });
265
+ if (min !== undefined) {
266
+ if (val < min) {
267
+ return false;
268
+ }
256
269
  }
270
+
271
+ return true;
257
272
  }
258
273
 
259
274
  /**
260
275
  * The user has elected to accept the input value. Validate and store, if valid.
261
276
  */
262
- private onAcceptValue() {
263
- if (this.state.entryValue !== null) {
264
- this.setState({ editing: false, currentValue: this.state.entryValue });
265
-
266
- if (this.props.onValueChanged)
267
- this.props.onValueChanged(this.state.entryValue);
268
-
269
- if (this.props.dispatchTopic !== undefined) {
270
- this.context.dispatch({ topic: this.props.dispatchTopic, payload: this.state.entryValue });
277
+ const handleAcceptValue = () => {
278
+ if (editing && entryValue !== null ) {
279
+
280
+ if (validateValue(entryValue)) {
281
+ setCurrentValue(entryValue);
282
+ setEditing(false);
283
+ onValueChanged?.(entryValue);
284
+ setInvalidValue(false);
285
+
286
+ if (dispatchTopic) {
287
+ eventEmitter.dispatch({ topic: dispatchTopic, payload: entryValue });
288
+ }
289
+ }
290
+ else {
291
+ setInvalidValue(true);
271
292
  }
272
293
 
273
294
  }
274
- }
295
+ };
275
296
 
276
297
  /**
277
- * The user wishes to reset/cancel the previous value.
298
+ * The user wishes to cancel/reset to the previous value.
278
299
  */
279
- private onResetValue() {
280
-
281
- if (this.state.editing) {
282
-
283
- this.setState({
284
- currentValue: this.state.currentValue,
285
- entryValue: this.state.currentValue,
286
- editing: false
287
- });
288
- }
289
- }
290
-
300
+ const handleResetValue = () => {
301
+ if (editing) {
302
+ setEntryValue(null);
303
+ setCurrentValue(null);
304
+ setEditing(false);
305
+ setInvalidValue(false);
306
+ }
307
+ };
291
308
 
292
- render() {
293
-
294
- return (
295
- <div>
296
- <div className="p-inputgroup flex-1" >
297
- <span className="p-inputgroup-addon">
298
- {this.props.label}
299
- </span>
300
- <InputNumber
301
- inputRef={this.inputRef}
302
- key={this.state.editing ? "editing" : "not-editing"}
303
- min={this.props.min}
304
- max={this.props.max}
305
- minFractionDigits={this.props.minPrecision}
306
- maxFractionDigits={this.props.maxPrecision}
307
- mode={this.props.mode}
308
- prefix={this.props.prefix}
309
- suffix={this.props.suffix}
310
- showButtons={this.props.showButtons}
311
- step={this.props.step}
312
- placeholder={this.props.placeholder}
313
- value={this.state.currentValue}
314
- onChange={(e) => { this.onBufferValue(e.value) }}
315
-
316
- buttonLayout="horizontal"
317
- decrementButtonClassName="p-button-danger"
318
- incrementButtonClassName="p-button-success"
319
- incrementButtonIcon="pi pi-plus"
320
- decrementButtonIcon="pi pi-minus"
321
-
322
- locale="en-US"
323
- currency={this.props.currency}
324
-
325
- onKeyDown={(e) => {
326
- if (e.key === 'Enter') {
327
- this.onAcceptValue();
328
- }
329
- else if (e.key === 'Escape') {
330
- this.onResetValue();
331
- }
332
- }}
333
- disabled={this.props.disabled}
334
- autoFocus={false}
335
- />
336
- <Button
337
- icon="pi pi-check"
338
- disabled={this.props.disabled || !this.state.editing}
339
- className="p-button-success"
340
- onClick={() => this.onAcceptValue()}
341
- visible={this.state.editing}
342
- size="small"
343
- autoFocus={false}
344
- />
345
-
346
- <Button
347
- icon="pi pi-times"
348
- disabled={this.props.disabled || !this.state.editing}
349
- className="p-button-danger"
350
- onClickCapture={() => this.onResetValue()}
351
- visible={this.state.editing}
352
- size="small"
353
- autoFocus={false}
354
- />
355
- </div>
356
-
357
- {this.props.description !== undefined &&
358
- <small>{this.props.description}</small>
359
- }
309
+ return (
310
+ <div>
311
+ <div className="p-inputgroup flex-1">
312
+ <span className="p-inputgroup-addon">{label}</span>
313
+ <InputNumber
314
+ ref={inputRef}
315
+ invalid={invalidValue}
316
+ min={min}
317
+ max={max}
318
+ minFractionDigits={minPrecision}
319
+ maxFractionDigits={maxPrecision}
320
+ mode={mode}
321
+ prefix={prefix}
322
+ suffix={suffix}
323
+ showButtons={showButtons}
324
+ step={step}
325
+ placeholder={placeholder}
326
+ value={currentValue}
327
+ onChange={(e) => handleBufferValue(e.value)}
328
+ locale={locale}
329
+ currency={currency}
330
+ onKeyDown={(e) => {
331
+ if (e.key === 'Enter') {
332
+ handleAcceptValue();
333
+ } else if (e.key === 'Escape') {
334
+ handleResetValue();
335
+ }
336
+ }}
337
+ disabled={disabled}
338
+ />
339
+
340
+ <Button
341
+ icon="pi pi-check"
342
+ disabled={disabled || !editing}
343
+ className="p-button-success"
344
+ onClick={() => handleAcceptValue()}
345
+ visible={editing}
346
+ size="small"
347
+ autoFocus={false}
348
+ />
349
+
350
+ <Button
351
+ icon="pi pi-times"
352
+ disabled={disabled || !editing}
353
+ className="p-button-danger"
354
+ onClickCapture={() => handleResetValue()}
355
+ visible={editing}
356
+ size="small"
357
+ autoFocus={false}
358
+ />
360
359
 
361
360
 
362
361
  </div>
362
+ {description && <small>{description}</small>}
363
+ </div>
364
+ );
365
+ };
363
366
 
364
- );
365
- }
366
-
367
- }
367
+ export default ValueInput;
@@ -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-28 20:07:12
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';