@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,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-29 11:01:41
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 { MessageSeverity } from 'primereact/api';
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? : string
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 { invoke, dispatch } = useContext(EventEmitterContext);
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" : 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: 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
- console.error("Failed downloading file: " + error);
129
- dispatch({
130
- topic: "autocore-react/alert/error",
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: 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
- console.error("Failed deleting file: " + error);
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
- <Button
177
- icon="pi pi-upload"
178
- className="p-button-rounded p-mr-2"
179
- aria-label="Upload"
180
- size="small"
181
- rounded text
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-04-28 16:06:59
4
4
  * -----
5
- * Last Modified: 2024-04-28 20:05:41
5
+ * Last Modified: 2024-05-01 07:30:49
6
6
  * -----
7
7
  *
8
8
  */
@@ -2,7 +2,7 @@
2
2
  * Copyright (C) 2024 Automated Design Corp. All Rights Reserved.
3
3
  * Created Date: 2024-01-16 14:17:02
4
4
  * -----
5
- * Last Modified: 2024-03-08 07:48:42
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 that subscribes to a value from an `EventEmitterContext` and renders it.
88
- * This component adjusts its display based on the provided properties, including positioning and styling adjustments
89
- * based on its context. It is designed to work within a system that provides dynamic updates to values via an event emitter.
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 : React.CSSProperties = {
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
- {numerableFormat(subscribedValue, format, formatOptions)}
229
+ {displayValue}
176
230
  </div>
177
231
  );
178
232
  }
233
+
179
234
  }
180
235
 
181
236
  export { ValueDisplay, NumerableFormatOptions };