dce-reactkit 2.0.4 → 2.0.7

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.
@@ -0,0 +1,447 @@
1
+ /**
2
+ * A generic popup modal
3
+ * @author Gabe Abrams
4
+ */
5
+
6
+ // Import React
7
+ import React, { useState, useEffect } from 'react';
8
+
9
+ // Import other components
10
+ import BootstrapModal from 'react-bootstrap/Modal';
11
+ import waitMs from '../helpers/waitMs';
12
+
13
+ // Import types
14
+ import Variant from '../types/Variant';
15
+
16
+ /*------------------------------------------------------------------------*/
17
+ /* Style */
18
+ /*------------------------------------------------------------------------*/
19
+
20
+ const style = `
21
+ /* More opaque backdrop */
22
+ .Modal-backdrop {
23
+ background-color: black !important;
24
+ opacity: 0.8 !important;
25
+ z-index: 10000000 !important;
26
+ }
27
+
28
+ /* Customize the modal header and body */
29
+ .modal-header {
30
+ /* Dark theme */
31
+ background-color: #222 !important;
32
+ color: white !important;
33
+
34
+ /* Border */
35
+ border: 1px solid #545454 !important;
36
+ }
37
+ .modal-body {
38
+ /* Dark theme */
39
+ background-color: #222 !important;
40
+ color: white !important;
41
+
42
+ /* Border */
43
+ border-top: 0 !important;
44
+ border-left: 1px solid #545454 !important;
45
+ border-bottom: 1px solid #545454 !important;
46
+ border-right: 1px solid #545454 !important;
47
+ border-bottom-left-radius: 3px;
48
+ border-bottom-right-radius: 3px;
49
+ }
50
+
51
+ /* Create our own animation */
52
+ .modal-content {
53
+ animation-name: Modal-drop-in;
54
+ animation-duration: 0.4s;
55
+ animation-iteration-count: 1;
56
+ animation-fill-mode: forwards;
57
+ animation-timing-function: ease-out;
58
+ }
59
+ @keyframes Modal-drop-in {
60
+ 0% {
61
+ transform: scale(0.8);
62
+ opacity: 0.5;
63
+ }
64
+ 100% {
65
+ transform: scale(1);
66
+ opacity: 1;
67
+ }
68
+ }
69
+ `;
70
+
71
+ /*------------------------------------------------------------------------*/
72
+ /* Constants */
73
+ /*------------------------------------------------------------------------*/
74
+
75
+ // Constants
76
+ const MS_TO_ANIMATE = 400; // Time to animate in/out (defined by bootstrap)
77
+ const MS_ANIMATE_IN_DELAY = 10;
78
+ // Time to wait before animating in (must be >0 or animation won't trigger)
79
+
80
+ // Modal types
81
+ enum ModalType {
82
+ Okay = 'okay', // [Okay]
83
+ OkayCancel = 'okay-cancel', // [Okay] [Cancel]
84
+ YesNo = 'yes-no', // [Yes] [No]
85
+ YesNoCancel = 'yes-no-cancel', // [Yes] [No] [Cancel]
86
+ AbandonGoBack = 'abandon-goBack', // [Abandon Changes] [Go Back]
87
+ ImSureCancel = 'imSure-cancel', // [I am sure] [Cancel]
88
+ DeleteCancel = 'delete-cancel', // [Yes, Delete] [Cancel]
89
+ ConfirmCancel = 'confirm-cancel', // [Confirm] [Cancel]
90
+ NoButtons = '-', // No buttons
91
+ }
92
+
93
+ // Modal sizes
94
+ enum ModalSize {
95
+ Small = 'sm',
96
+ Medium = 'md',
97
+ Large = 'lg',
98
+ ExtraLarge = 'xl',
99
+ }
100
+
101
+ // Button types
102
+ enum ButtonType {
103
+ Okay = 'okay',
104
+ Cancel = 'cancel',
105
+ Yes = 'yes',
106
+ No = 'no',
107
+ Abandon = 'abandon',
108
+ GoBack = 'goBack',
109
+ Continue = 'continue',
110
+ ImSure = 'imSure',
111
+ Delete = 'delete',
112
+ Confirm = 'confirm',
113
+ }
114
+
115
+ // Modal type to list of buttons
116
+ const modalTypeToButtonTypes: {
117
+ [k: string]: ButtonType[]
118
+ } = {
119
+ [ModalType.Okay]: [
120
+ ButtonType.Okay,
121
+ ],
122
+ [ModalType.OkayCancel]: [
123
+ ButtonType.Okay,
124
+ ButtonType.Cancel,
125
+ ],
126
+ [ModalType.YesNo]: [
127
+ ButtonType.Yes,
128
+ ButtonType.No,
129
+ ],
130
+ [ModalType.YesNoCancel]: [
131
+ ButtonType.Yes,
132
+ ButtonType.No,
133
+ ButtonType.Cancel,
134
+ ],
135
+ [ModalType.AbandonGoBack]: [
136
+ ButtonType.Abandon,
137
+ ButtonType.GoBack,
138
+ ],
139
+ [ModalType.ImSureCancel]: [
140
+ ButtonType.ImSure,
141
+ ButtonType.Cancel,
142
+ ],
143
+ [ModalType.DeleteCancel]: [
144
+ ButtonType.Delete,
145
+ ButtonType.Cancel,
146
+ ],
147
+ [ModalType.ConfirmCancel]: [
148
+ ButtonType.Confirm,
149
+ ButtonType.Cancel,
150
+ ],
151
+ };
152
+
153
+ // Button type styling and labels
154
+ const buttonTypeToLabelAndVariant = {
155
+ [ButtonType.Okay]: {
156
+ label: 'Okay',
157
+ variant: Variant.Dark,
158
+ },
159
+ [ButtonType.Cancel]: {
160
+ label: 'Cancel',
161
+ variant: Variant.Secondary,
162
+ },
163
+ [ButtonType.Yes]: {
164
+ label: 'Yes',
165
+ variant: Variant.Dark,
166
+ },
167
+ [ButtonType.No]: {
168
+ label: 'No',
169
+ variant: Variant.Secondary,
170
+ },
171
+ [ButtonType.Abandon]: {
172
+ label: 'Abandon Changes',
173
+ variant: Variant.Warning,
174
+ },
175
+ [ButtonType.GoBack]: {
176
+ label: 'Go Back',
177
+ variant: Variant.Secondary,
178
+ },
179
+ [ButtonType.Continue]: {
180
+ label: 'Continue',
181
+ variant: Variant.Dark,
182
+ },
183
+ [ButtonType.ImSure]: {
184
+ label: 'I am sure',
185
+ variant: Variant.Warning,
186
+ },
187
+ [ButtonType.Delete]: {
188
+ label: 'Yes, Delete',
189
+ variant: Variant.Danger,
190
+ },
191
+ [ButtonType.Confirm]: {
192
+ label: 'Confirm',
193
+ variant: Variant.Dark,
194
+ },
195
+ };
196
+
197
+ /*------------------------------------------------------------------------*/
198
+ /* Types */
199
+ /*------------------------------------------------------------------------*/
200
+
201
+ type Props = {
202
+ // Type of the modal
203
+ type?: ModalType,
204
+ // Size of the modal
205
+ size?: ModalSize,
206
+ // Title of the modal (if excluded, no header)
207
+ title?: React.ReactNode,
208
+ // The body of the modal
209
+ children?: React.ReactNode,
210
+ // Handler to call when modal is closed (if excluded, not closable)
211
+ onClose?: (type: ButtonType) => void,
212
+ // Custom label for "okay" button
213
+ okayLabel?: string,
214
+ // Custom variant for "okay" button
215
+ okayVariant?: Variant,
216
+ // Custom label for "cancel" button
217
+ cancelLabel?: string,
218
+ // Custom variant for "cancel" button
219
+ cancelVariant?: Variant,
220
+ // Custom label for "yes" button
221
+ yesLabel?: string,
222
+ // Custom variant for "yes" button
223
+ yesVariant?: Variant,
224
+ // Custom label for "no" button
225
+ noLabel?: string,
226
+ // Custom variant for "no" button
227
+ noVariant?: Variant,
228
+ // Custom label for "abandon" button
229
+ abandonLabel?: string,
230
+ // Custom variant for "abandon" button
231
+ abandonVariant?: Variant,
232
+ // Custom label for "goBack" button
233
+ goBackLabel?: string,
234
+ // Custom variant for "goBack" button
235
+ goBackVariant?: Variant,
236
+ // Custom label for "continue" button
237
+ continueLabel?: string,
238
+ // Custom variant for "continue" button
239
+ continueVariant?: Variant,
240
+ // Custom label for "imSure" button
241
+ imSureLabel?: string,
242
+ // Custom variant for "imSure" button
243
+ imSureVariant?: Variant,
244
+ // Custom label for "delete" button
245
+ deleteLabel?: string,
246
+ // Custom variant for "delete" button
247
+ deleteVariant?: Variant,
248
+ // Custom label for "confirm" button
249
+ confirmLabel?: string,
250
+ // Custom variant for "confirm" button
251
+ confirmVariant?: Variant,
252
+ };
253
+
254
+ /*------------------------------------------------------------------------*/
255
+ /* Component */
256
+ /*------------------------------------------------------------------------*/
257
+
258
+ const Modal: (
259
+ React.FC<Props>
260
+ & {
261
+ ModalType: typeof ModalType,
262
+ ModalSize: typeof ModalSize,
263
+ ButtonType: typeof ButtonType,
264
+ Variant: typeof Variant,
265
+ }
266
+ ) = (props) => {
267
+ /*------------------------------------------------------------------------*/
268
+ /* Setup */
269
+ /*------------------------------------------------------------------------*/
270
+
271
+ /* -------------- Props ------------- */
272
+
273
+ const {
274
+ type = ModalType.NoButtons,
275
+ size = ModalSize.Large,
276
+ title,
277
+ children,
278
+ onClose,
279
+ } = props;
280
+
281
+ /* -------------- State ------------- */
282
+
283
+ // If true, the modal is shown
284
+ const [visible, setVisible] = useState(false);
285
+
286
+ // True if currently animating in
287
+ const [animatingIn, setAnimatingIn] = useState(false);
288
+
289
+ /*------------------------------------------------------------------------*/
290
+ /* Lifecycle Functions */
291
+ /*------------------------------------------------------------------------*/
292
+
293
+ /**
294
+ * Mount
295
+ * @author Gabe Abrams
296
+ */
297
+ useEffect(
298
+ () => {
299
+ (async () => {
300
+ // Start the component animating in
301
+ await waitMs(MS_ANIMATE_IN_DELAY);
302
+ setAnimatingIn(true);
303
+
304
+ // Wait and then set visible to true
305
+ await waitMs(MS_TO_ANIMATE);
306
+ setVisible(true);
307
+ })();
308
+ },
309
+ [],
310
+ );
311
+
312
+ /*------------------------------------------------------------------------*/
313
+ /* Component Functions */
314
+ /*------------------------------------------------------------------------*/
315
+
316
+ /**
317
+ * Handles the closing of the modal
318
+ * @author Gabe Abrams
319
+ * @param buttonType the button that was clicked when closing the
320
+ * modal
321
+ */
322
+ const handleClose = async (buttonType: ButtonType) => {
323
+ // Don't close if no handler
324
+ if (!onClose) {
325
+ return;
326
+ }
327
+
328
+ // Don't close if animating in
329
+ if (animatingIn) {
330
+ return;
331
+ }
332
+
333
+ // Don't close if already closed
334
+ if (!visible) {
335
+ return;
336
+ }
337
+
338
+ // Update the state
339
+ setVisible(false);
340
+
341
+ // Call the handler after the modal has animated out
342
+ await waitMs(MS_TO_ANIMATE);
343
+ onClose(buttonType);
344
+ };
345
+
346
+ /*------------------------------------------------------------------------*/
347
+ /* Render */
348
+ /*------------------------------------------------------------------------*/
349
+
350
+ /*----------------------------------------*/
351
+ /* Footer */
352
+ /*----------------------------------------*/
353
+
354
+ // Get list of buttons for this modal type
355
+ const buttonTypes: ButtonType[] = modalTypeToButtonTypes[type] ?? [];
356
+
357
+ // Create buttons
358
+ const buttons = buttonTypes.map((buttonType: ButtonType, i) => {
359
+ // Get default style
360
+ let {
361
+ label,
362
+ variant,
363
+ } = buttonTypeToLabelAndVariant[buttonType];
364
+
365
+ // Override with customizations
366
+ if (props[`${buttonType}Label`]) {
367
+ label = props[`${buttonType}Label`];
368
+ }
369
+ if (props[`${buttonType}Variant`]) {
370
+ variant = props[`${buttonType}Variant`];
371
+ }
372
+
373
+ // Check if this button is last
374
+ const last = (i === buttonTypes.length - 1);
375
+
376
+ // Create the button
377
+ return (
378
+ <button
379
+ type="button"
380
+ className={`Modal-${buttonType}-button btn btn-${variant} ${last ? '' : 'mr-1'}`}
381
+ onClick={() => {
382
+ handleClose(buttonType);
383
+ }}
384
+ >
385
+ {label}
386
+ </button>
387
+ );
388
+ });
389
+
390
+ // Put all buttons in a footer
391
+ const footer = (
392
+ (buttons && buttons.length)
393
+ ? (
394
+ <div>
395
+ {buttons}
396
+ </div>
397
+ )
398
+ : undefined
399
+ );
400
+
401
+ // Render the modal
402
+ return (
403
+ <BootstrapModal
404
+ show={visible}
405
+ size={size !== ModalSize.Medium ? size : undefined}
406
+ onHide={() => {
407
+ handleClose(ButtonType.Cancel);
408
+ }}
409
+ style={{ zIndex: 5000000000 }}
410
+ backdropClassName="Modal-backdrop"
411
+ centered
412
+ >
413
+ <style>{style}</style>
414
+ {title && (
415
+ <BootstrapModal.Header
416
+ closeButton={!!onClose}
417
+ >
418
+ <BootstrapModal.Title>
419
+ {title}
420
+ </BootstrapModal.Title>
421
+ </BootstrapModal.Header>
422
+ )}
423
+ {children && (
424
+ <BootstrapModal.Body>
425
+ {children}
426
+ </BootstrapModal.Body>
427
+ )}
428
+ {footer && (
429
+ <BootstrapModal.Footer>
430
+ {footer}
431
+ </BootstrapModal.Footer>
432
+ )}
433
+ </BootstrapModal>
434
+ );
435
+ };
436
+
437
+ /*------------------------------------------------------------------------*/
438
+ /* Wrap Up */
439
+ /*------------------------------------------------------------------------*/
440
+
441
+ // Add enums
442
+ Modal.ModalType = ModalType;
443
+ Modal.ModalSize = ModalSize;
444
+ Modal.ButtonType = ButtonType;
445
+ Modal.Variant = Variant;
446
+
447
+ export default Modal;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * An error with a code
3
+ * @author Gabe Abrams
4
+ */
5
+ class ErrorWithCode extends Error {
6
+ code: string;
7
+
8
+ constructor(message: string, code: string) {
9
+ super(message);
10
+ this.name = 'ErrorWithCode';
11
+ this.code = code;
12
+ }
13
+ }
14
+
15
+ export default ErrorWithCode;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Shorten text so it fits into a certain number of chars
3
+ * @author Gabe Abrams
4
+ * @param text the text to abbreviate
5
+ * @param maxChars the maximum number of chars to include
6
+ * @returns abbreviated text with length no greater than maxChars
7
+ * (including ellipses if applicable)
8
+ */
9
+ const abbreviate = (text: string, maxChars: number): string => {
10
+ // Check if already short enough
11
+ if (text.trim().length < maxChars) {
12
+ return text.trim();
13
+ }
14
+
15
+ // Abbreviate
16
+ const shortenedText = (
17
+ text
18
+ .trim()
19
+ .substring(0, maxChars - 3)
20
+ .trim()
21
+ );
22
+ return `${shortenedText}...`;
23
+ };
@@ -0,0 +1,22 @@
1
+ import sum from './sum';
2
+
3
+ /**
4
+ * Get the average of a set of numbers
5
+ * @author Gabe Abrams
6
+ * @param nums the numbers to average
7
+ * @returns average value or 0 if no numbers
8
+ */
9
+ const avg = (nums: number[]) => {
10
+ // Handle empty array case
11
+ if (nums.length === 0) {
12
+ return 0;
13
+ }
14
+
15
+ // Get the total value
16
+ const total = sum(nums);
17
+
18
+ // Get average
19
+ return (total / nums.length);
20
+ };
21
+
22
+ export default avg;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Round a number (ceiling) to a certain number of decimals
3
+ * @author Gabe Abrams
4
+ * @param num the number to round
5
+ * @param numDecimals the number of decimals to round to
6
+ * @returns rounded number
7
+ */
8
+ const ceilToNumDecimals = (num: number, numDecimals: number): number => {
9
+ const rounder = 10 ** numDecimals;
10
+ return (Math.ceil(num * rounder) / rounder);
11
+ };
12
+
13
+ export default ceilToNumDecimals;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Round a number (floor) to a certain number of decimals
3
+ * @author Gabe Abrams
4
+ * @param num the number to round
5
+ * @param numDecimals the number of decimals to round to
6
+ * @returns rounded number
7
+ */
8
+ const floorToNumDecimals = (num: number, numDecimals: number): number => {
9
+ const rounder = 10 ** numDecimals;
10
+ return (Math.floor(num * rounder) / rounder);
11
+ };
12
+
13
+ export default floorToNumDecimals;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Force a number to stay within specific bounds
3
+ * @author Gabe Abrams
4
+ * @param num the number to move into the bounds
5
+ * @param min the minimum number in the bound
6
+ * @param max the maximum number in the bound
7
+ * @returns bounded number
8
+ */
9
+ const forceNumIntoBounds = (num: number, min: number, max: number): number => {
10
+ return Math.max(
11
+ min,
12
+ Math.min(
13
+ max,
14
+ num,
15
+ ),
16
+ );
17
+ };
18
+
19
+ export default forceNumIntoBounds;
@@ -0,0 +1,65 @@
1
+ // Import shared types
2
+ import ReactKitErrorCode from '../types/ReactKitErrorCode';
3
+
4
+ /**
5
+ * Handle an error and respond to the client
6
+ * @author Gabe Abrams
7
+ * @param res express response
8
+ * @param error error info
9
+ * @param opts.err the error to send to the client
10
+ * or the error message
11
+ * @param [opts.code] an error code (only used if err.code is not
12
+ * included)
13
+ * @param [opts.status=500] the https status code to use
14
+ * defined)
15
+ */
16
+ const handleError = (
17
+ res: any,
18
+ error: (
19
+ | {
20
+ message: any,
21
+ code?: string,
22
+ status?: number,
23
+ }
24
+ | Error
25
+ | string
26
+ | any
27
+ ),
28
+ ): undefined => {
29
+ // Get the error message
30
+ let message;
31
+ if (error && (error as any).message) {
32
+ message = (error.message || 'An unknown error occurred.');
33
+ } else if (typeof error === 'string') {
34
+ message = (
35
+ error.trim().length > 0
36
+ ? error
37
+ : 'An unknown error occurred.'
38
+ );
39
+ } else {
40
+ message = 'An unknown error occurred.';
41
+ }
42
+
43
+ // Get the error code
44
+ const code = (error.code || ReactKitErrorCode.NoCode);
45
+
46
+ // Get the status code
47
+ const status = (error.status || 500);
48
+
49
+ // Respond to user
50
+ res
51
+ // Set the http status code
52
+ .status(status)
53
+ // Send a JSON response
54
+ .json({
55
+ // Error message
56
+ message,
57
+ // Error code
58
+ code,
59
+ // Success = false flag so client can detect server-side errors
60
+ success: false,
61
+ });
62
+ return undefined;
63
+ };
64
+
65
+ export default handleError;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Send successful API response
3
+ * @author Gabe Abrams
4
+ * @param res express response
5
+ * @param body the body of the response to send to the client
6
+ */
7
+ const handleSuccess = (res: any, body: any): undefined => {
8
+ // Send a http 200 json response
9
+ res.json({
10
+ // Include the body as a parameter
11
+ body,
12
+ // Success = true flag so client can detect successful responses
13
+ success: true,
14
+ });
15
+ return undefined;
16
+ };
17
+
18
+ export default handleSuccess;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Pad a number's decimal with zeros on the right
3
+ * (e.g. 5.2 becomes 5.20 with 2 digit padding)
4
+ * @author Gabe Abrams
5
+ * @param num the number to pad
6
+ * @param numDigits the minimum number of digits after the decimal
7
+ * @returns padded number
8
+ */
9
+ const padDecimalZeros = (num: number, numDigits: number): string => {
10
+ // Skip if nothing to do
11
+ if (numDigits < 1) {
12
+ return;
13
+ }
14
+
15
+ // Convert to string
16
+ let out = String(num);
17
+
18
+ // Add a decimal point if there isn't one
19
+ if (!out.includes('.')) {
20
+ out += '.';
21
+ }
22
+
23
+ // Add zeros
24
+ while (out.split('.')[1].length < numDigits) {
25
+ out = `${out}0`;
26
+ }
27
+
28
+ // Return
29
+ return out;
30
+ };
31
+
32
+ export default padDecimalZeros;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Pad a number with zeros on the left (e.g. 5 becomes 05 with 2 digit padding)
3
+ * @author Gabe Abrams
4
+ * @param num the number to pad
5
+ * @param numDigits the minimum number of digits before the decimal
6
+ * @returns padded number
7
+ */
8
+ const padZerosLeft = (num: number, numDigits: number): string => {
9
+ // Convert to string
10
+ let out = String(num);
11
+
12
+ // Add zeros
13
+ while (out.split('.')[0].length < numDigits) {
14
+ out = `0${out}`;
15
+ }
16
+
17
+ // Return
18
+ return out;
19
+ };
20
+
21
+ export default padZerosLeft;