dce-reactkit 3.0.0-beta.4 → 3.0.0-beta.42

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.
Files changed (60) hide show
  1. package/.eslintrc.js +95 -0
  2. package/README.md +1 -546
  3. package/dist/cjs/index.js +944 -85
  4. package/dist/cjs/index.js.map +1 -1
  5. package/dist/cjs/types/components/AppWrapper.d.ts +25 -2
  6. package/dist/cjs/types/components/ButtonInputGroup.d.ts +12 -0
  7. package/dist/cjs/types/components/CheckboxButton.d.ts +20 -0
  8. package/dist/cjs/types/components/RadioButton.d.ts +20 -0
  9. package/dist/cjs/types/components/SimpleDateChooser.d.ts +22 -0
  10. package/dist/cjs/types/components/TabBox.d.ts +1 -0
  11. package/dist/cjs/types/helpers/genRouteHandler.d.ts +30 -0
  12. package/dist/cjs/types/helpers/getOrdinal.d.ts +8 -0
  13. package/dist/cjs/types/helpers/getTimeInfoInET.d.ts +17 -0
  14. package/dist/cjs/types/helpers/handleError.d.ts +18 -0
  15. package/dist/cjs/types/helpers/handleSuccess.d.ts +8 -0
  16. package/dist/cjs/types/helpers/visitServerEndpoint.d.ts +23 -0
  17. package/dist/cjs/types/index.d.ts +13 -1
  18. package/dist/cjs/types/server/initServer.d.ts +21 -0
  19. package/dist/cjs/types/types/ParamType.d.ts +17 -0
  20. package/dist/cjs/types/types/ReactKitErrorCode.d.ts +3 -1
  21. package/dist/esm/index.js +933 -86
  22. package/dist/esm/index.js.map +1 -1
  23. package/dist/esm/types/components/AppWrapper.d.ts +25 -2
  24. package/dist/esm/types/components/ButtonInputGroup.d.ts +12 -0
  25. package/dist/esm/types/components/CheckboxButton.d.ts +20 -0
  26. package/dist/esm/types/components/RadioButton.d.ts +20 -0
  27. package/dist/esm/types/components/SimpleDateChooser.d.ts +22 -0
  28. package/dist/esm/types/components/TabBox.d.ts +1 -0
  29. package/dist/esm/types/helpers/genRouteHandler.d.ts +30 -0
  30. package/dist/esm/types/helpers/getOrdinal.d.ts +8 -0
  31. package/dist/esm/types/helpers/getTimeInfoInET.d.ts +17 -0
  32. package/dist/esm/types/helpers/handleError.d.ts +18 -0
  33. package/dist/esm/types/helpers/handleSuccess.d.ts +8 -0
  34. package/dist/esm/types/helpers/visitServerEndpoint.d.ts +23 -0
  35. package/dist/esm/types/index.d.ts +13 -1
  36. package/dist/esm/types/server/initServer.d.ts +21 -0
  37. package/dist/esm/types/types/ParamType.d.ts +17 -0
  38. package/dist/esm/types/types/ReactKitErrorCode.d.ts +3 -1
  39. package/dist/index.d.ts +229 -10
  40. package/package.json +13 -1
  41. package/rollup.config.js +0 -1
  42. package/src/components/AppWrapper.tsx +73 -15
  43. package/src/components/ButtonInputGroup.tsx +89 -0
  44. package/src/components/CheckboxButton.tsx +100 -0
  45. package/src/components/ErrorBox.tsx +4 -4
  46. package/src/components/LoadingSpinner.tsx +3 -3
  47. package/src/components/Modal.tsx +185 -71
  48. package/src/components/RadioButton.tsx +102 -0
  49. package/src/components/SimpleDateChooser.tsx +222 -0
  50. package/src/components/TabBox.tsx +65 -58
  51. package/src/helpers/genRouteHandler.ts +326 -0
  52. package/src/helpers/getOrdinal.tsx +13 -0
  53. package/src/helpers/getTimeInfoInET.tsx +56 -0
  54. package/src/helpers/handleError.ts +65 -0
  55. package/src/helpers/handleSuccess.ts +18 -0
  56. package/src/helpers/visitServerEndpoint.tsx +110 -0
  57. package/src/index.ts +27 -0
  58. package/src/server/initServer.ts +53 -0
  59. package/src/types/ParamType.ts +18 -0
  60. package/src/types/ReactKitErrorCode.tsx +3 -1
@@ -0,0 +1,13 @@
1
+ const ORDINALS = ['th', 'st', 'nd', 'rd'];
2
+
3
+ /**
4
+ * Get a number's ordinal
5
+ * @author Gabe Abrams
6
+ * @param num the number being analyzed
7
+ * @returns ordinal
8
+ */
9
+ const getOrdinal = (num: number): string => {
10
+ return (ORDINALS[(num - 20) % 10] ?? ORDINALS[num] ?? ORDINALS[0]);
11
+ };
12
+
13
+ export default getOrdinal;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Get current time info in US Boston Eastern Time, independent of machine
3
+ * timezone
4
+ * @author Gabe Abrams
5
+ * @param {Date} [date=now] the date to get info on
6
+ * @returns object with timestamp (ms since epoch) and numbers
7
+ * corresponding to ET time values for year, month, day, hour, minute
8
+ */
9
+ const getTimeInfoInET = (date?: Date): {
10
+ timestamp: number,
11
+ year: number,
12
+ month: number,
13
+ day: number,
14
+ hour: number,
15
+ minute: number,
16
+ } => {
17
+ // Create a time string
18
+ const d = (date || new Date());
19
+ const str = d.toLocaleString(
20
+ 'en-US', // Using US encoding (it's the only one installed on containers)
21
+ { timeZone: 'America/New_York' } // Force EST timezone
22
+ );
23
+
24
+ // Parse the string for the date/time info
25
+ const [dateStr, timeStr] = str.split(', '); // Format: MM/DD/YYYY, HH:MM:SS AM
26
+ const [monthStr, dayStr, yearStr] = dateStr.split('/'); // Format: MM/DD/YYYY
27
+ const [hourStr, minStr, ending] = timeStr.split(':'); // Format: HH:MM:SS AM
28
+
29
+ // Create all time numbers
30
+ const timestamp = d.getTime();
31
+ const year = Number.parseInt(yearStr, 10);
32
+ const month = Number.parseInt(monthStr, 10);
33
+ const day = Number.parseInt(dayStr, 10);
34
+ const minute = Number.parseInt(minStr, 10);
35
+ let hour = Number.parseInt(hourStr, 10);
36
+ // Convert from am/pm to 24hr
37
+ const isAM = ending.toLowerCase().includes('am');
38
+ const isPM = !isAM;
39
+ if (isPM && hour !== 12) {
40
+ hour += 12;
41
+ } else if (isAM && hour === 12) {
42
+ hour = 0;
43
+ }
44
+
45
+ // Return
46
+ return {
47
+ timestamp,
48
+ year,
49
+ month,
50
+ day,
51
+ hour,
52
+ minute,
53
+ };
54
+ };
55
+
56
+ export default getTimeInfoInET;
@@ -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,110 @@
1
+ // Import custom error
2
+ import ErrorWithCode from '../errors/ErrorWithCode';
3
+ import ReactKitErrorCode from '../types/ReactKitErrorCode';
4
+
5
+ // Import helpers from app wrapper
6
+ import { cacclSendRequest } from '../components/AppWrapper';
7
+
8
+ /*------------------------------------------------------------------------*/
9
+ /* Listener */
10
+ /*------------------------------------------------------------------------*/
11
+
12
+ // Handler for session expiry
13
+ let sessionExpiryHandler: () => void;
14
+
15
+ // Keep track of whether or not session expiry has already been handled
16
+ let sessionAlreadyExpired = false;
17
+
18
+ /**
19
+ * Set the session expiry handler
20
+ * @author Gabe Abrams
21
+ * @param handler new handler to use when session expires
22
+ */
23
+ export const setSessionExpiryHandler = (handler: () => void) => {
24
+ sessionExpiryHandler = handler;
25
+ };
26
+
27
+ /*------------------------------------------------------------------------*/
28
+ /* Main */
29
+ /*------------------------------------------------------------------------*/
30
+
31
+ /**
32
+ * Visit an endpoint on the server [for client only]
33
+ * @author Gabe Abrams
34
+ * @param opts object containing all arguments
35
+ * @param opts.path - the path of the server endpoint
36
+ * @param [opts.method=GET] - the method of the endpoint
37
+ * @param [opts.params] - query/body parameters to include
38
+ * @returns response from server
39
+ */
40
+ const visitServerEndpoint = async (
41
+ opts: {
42
+ path: string,
43
+ method?: ('GET' | 'POST' | 'DELETE' | 'PUT'),
44
+ params?: { [key in string]: any },
45
+ },
46
+ ): Promise<any> => {
47
+ // Send the request
48
+ const response = await cacclSendRequest({
49
+ path: opts.path,
50
+ method: opts.method ?? 'GET',
51
+ params: opts.params,
52
+ });
53
+
54
+ // Check for failure
55
+ if (!response || !response.body) {
56
+ throw new ErrorWithCode(
57
+ 'We didn\'t get a response from the server. Please check your internet connection.',
58
+ ReactKitErrorCode.NoResponse,
59
+ );
60
+ }
61
+ if (!response.body.success) {
62
+ // Session expired
63
+ if (response.body.code === ReactKitErrorCode.SessionExpired) {
64
+ // Skip notice if session was already expired
65
+ if (sessionAlreadyExpired) {
66
+ // Never return (browser is already reloading)
67
+ await new Promise<{ [key in string]: any }>(() => {
68
+ // Promise that never returns
69
+ });
70
+ }
71
+ sessionAlreadyExpired = true;
72
+
73
+ // Show session expiration message
74
+ if (sessionExpiryHandler) {
75
+ // Use handler
76
+ sessionExpiryHandler();
77
+ } else {
78
+ // Fallback to alert
79
+
80
+ // eslint-disable-next-line no-alert
81
+ alert('Your session has expired. Please start over.');
82
+ }
83
+
84
+ // Never return (don't continue execution)
85
+ await new Promise<{ [key in string]: any }>(() => {
86
+ // Promise that never returns
87
+ });
88
+ }
89
+
90
+ // Other errors
91
+ throw new ErrorWithCode(
92
+ (
93
+ response.body.message
94
+ || 'An unknown error occurred. Please contact an admin.'
95
+ ),
96
+ (
97
+ response.body.code
98
+ || ReactKitErrorCode.NoCode
99
+ ),
100
+ );
101
+ }
102
+
103
+ // Success! Extract the body
104
+ const { body } = response.body;
105
+
106
+ // Return
107
+ return body;
108
+ };
109
+
110
+ export default visitServerEndpoint;
package/src/index.ts CHANGED
@@ -4,6 +4,10 @@ import LoadingSpinner from './components/LoadingSpinner';
4
4
  import ErrorBox from './components/ErrorBox';
5
5
  import Modal from './components/Modal';
6
6
  import TabBox from './components/TabBox';
7
+ import RadioButton from './components/RadioButton';
8
+ import CheckboxButton from './components/CheckboxButton';
9
+ import ButtonInputGroup from './components/ButtonInputGroup';
10
+ import SimpleDateChooser from './components/SimpleDateChooser';
7
11
 
8
12
  // Import errors
9
13
  import ErrorWithCode from './errors/ErrorWithCode';
@@ -19,6 +23,13 @@ import padZerosLeft from './helpers/padZerosLeft';
19
23
  import roundToNumDecimals from './helpers/roundToNumDecimals';
20
24
  import sum from './helpers/sum';
21
25
  import waitMs from './helpers/waitMs';
26
+ import visitServerEndpoint from './helpers/visitServerEndpoint';
27
+ import genRouteHandler from './helpers/genRouteHandler';
28
+ import handleError from './helpers/handleError';
29
+ import handleSuccess from './helpers/handleSuccess';
30
+ import initServer from './server/initServer';
31
+ import getOrdinal from './helpers/getOrdinal';
32
+ import getTimeInfoInET from './helpers/getTimeInfoInET';
22
33
 
23
34
  // Import types
24
35
  import ModalButtonType from './types/ModalButtonType';
@@ -26,6 +37,7 @@ import ModalSize from './types/ModalSize';
26
37
  import ModalType from './types/ModalType';
27
38
  import ReactKitErrorCode from './types/ReactKitErrorCode';
28
39
  import Variant from './types/Variant';
40
+ import ParamType from './types/ParamType';
29
41
 
30
42
  // Export each item
31
43
  export {
@@ -35,6 +47,10 @@ export {
35
47
  ErrorBox,
36
48
  Modal,
37
49
  TabBox,
50
+ RadioButton,
51
+ CheckboxButton,
52
+ ButtonInputGroup,
53
+ SimpleDateChooser,
38
54
  // Global functions
39
55
  alert,
40
56
  confirm,
@@ -52,10 +68,21 @@ export {
52
68
  roundToNumDecimals,
53
69
  sum,
54
70
  waitMs,
71
+ getOrdinal,
72
+ getTimeInfoInET,
73
+ // Client helpers
74
+ visitServerEndpoint,
75
+ // Server helpers
76
+ initServer,
77
+ genRouteHandler,
78
+ handleError,
79
+ handleSuccess,
55
80
  // Types
56
81
  ModalButtonType,
57
82
  ModalSize,
58
83
  ModalType,
59
84
  ReactKitErrorCode,
60
85
  Variant,
86
+ // Server types
87
+ ParamType,
61
88
  };
@@ -0,0 +1,53 @@
1
+ // Import custom error
2
+ import ErrorWithCode from '../errors/ErrorWithCode';
3
+ import ReactKitErrorCode from '../types/ReactKitErrorCode';
4
+
5
+ // Types
6
+ type GetLaunchInfoFunction = (req: any) => {
7
+ launched: boolean,
8
+ launchInfo?: any,
9
+ };
10
+
11
+ // Stored copy of caccl functions
12
+ let _cacclGetLaunchInfo: GetLaunchInfoFunction;
13
+
14
+ /*------------------------------------------------------------------------*/
15
+ /* Helpers */
16
+ /*------------------------------------------------------------------------*/
17
+
18
+ /**
19
+ * Get launch info via CACCL
20
+ * @author Gabe Abrams
21
+ * @param req express request object
22
+ * @returns object { launched, launchInfo }
23
+ */
24
+ export const cacclGetLaunchInfo: GetLaunchInfoFunction = (req: any) => {
25
+ if (!_cacclGetLaunchInfo) {
26
+ throw new ErrorWithCode(
27
+ 'Could not get launch info because server was not initialized with dce-reactkit\'s initServer function',
28
+ ReactKitErrorCode.NoCACCLGetLaunchInfoFunction,
29
+ );
30
+ }
31
+
32
+ return _cacclGetLaunchInfo(req);
33
+ };
34
+
35
+ /*------------------------------------------------------------------------*/
36
+ /* Main */
37
+ /*------------------------------------------------------------------------*/
38
+
39
+ /**
40
+ * Prepare dce-reactkit to run on the server
41
+ * @author Gabe Abrams
42
+ * @param opts object containing all arguments
43
+ * @param opts.getLaunchInfo CACCL LTI's get launch info function
44
+ */
45
+ const initServer = (
46
+ opts: {
47
+ getLaunchInfo: GetLaunchInfoFunction,
48
+ },
49
+ ) => {
50
+ _cacclGetLaunchInfo = opts.getLaunchInfo;
51
+ };
52
+
53
+ export default initServer;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Server-side API param types
3
+ * @author Gabe Abrams
4
+ */
5
+ enum ParamType {
6
+ Boolean = 'boolean', // Boolean
7
+ BooleanOptional = 'boolean-optional', // Optional boolean
8
+ Float = 'float', // Float Number
9
+ FloatOptional = 'float-optional', // Optional Float Number
10
+ Int = 'int', // Integer Number
11
+ IntOptional = 'int-optional', // Optional Integer Number
12
+ JSON = 'json', // JSONified object
13
+ JSONOptional = 'json-optional', // Optional JSONified object
14
+ String = 'string', // String
15
+ StringOptional = 'string-optional', // Optional string
16
+ }
17
+
18
+ export default ParamType;
@@ -1,4 +1,4 @@
1
- // Highest error code = DRK2
1
+ // Highest error code = DRK8
2
2
 
3
3
  /**
4
4
  * List of error codes built into the react kit
@@ -11,6 +11,8 @@ enum ReactKitErrorCode {
11
11
  MissingParameter = 'DRK4',
12
12
  InvalidParameter = 'DRK5',
13
13
  WrongCourse = 'DRK6',
14
+ NoCACCLSendRequestFunction = 'DRK7',
15
+ NoCACCLGetLaunchInfoFunction = 'DRK8',
14
16
  }
15
17
 
16
18
  export default ReactKitErrorCode;