@modernman00/shared-js-lib 1.2.13 → 1.2.23

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/FormHelper.js CHANGED
@@ -1,14 +1,14 @@
1
- 'use strict'
1
+ 'use strict';
2
2
  export default class FormHelper {
3
3
  constructor(data) {
4
- if (!Array.isArray(data)) throwError('data must be an array of form elements');
4
+ if (!Array.isArray(data)) throwError('data must be an array of form elements');
5
5
  this.data = data;
6
6
  this.error = [];
7
7
  this.result = 0;
8
8
  }
9
9
 
10
10
  id(x) {
11
- return document.getElementById(x)
11
+ return document.getElementById(x);
12
12
  }
13
13
 
14
14
  /**
@@ -26,67 +26,139 @@ export default class FormHelper {
26
26
  * @param {string} [type='general'] - the type of validation to perform. Currently only 'email' is supported
27
27
  * @returns {boolean} - true if the field is valid, false otherwise
28
28
  */
29
- validateField(value, type = 'general') {
29
+ validateLoginField(inputId, type = 'general') {
30
+ const inputEl = this.id(inputId);
31
+ const value = inputEl.value.trim();
32
+ let msg = '';
33
+ let isValid = true;
34
+
30
35
  if (type === 'email') {
31
36
  const emailRegex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-Z0-9]{2,4}$/;
32
- return emailRegex.test(value);
37
+ if (!emailRegex.test(value)) {
38
+ msg = '<li>Please enter a valid email</li>';
39
+ isValid = false;
40
+ }
41
+ }
42
+
43
+ else if (type === 'password') {
44
+ const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;
45
+ if (!passwordRegex.test(value)) {
46
+ msg = '<li>Please enter a valid password (min 8 chars, upper & lowercase, number, special char)</li>';
47
+ isValid = false;
48
+ }
49
+ }
50
+
51
+ else if (type === 'general') {
52
+ const generalRegex = /[\w\d\s.,'"!?@#&()\-]/;
53
+ if (!generalRegex.test(value)) {
54
+ msg = '<li>Invalid entry — special characters may not be allowed</li>';
55
+ isValid = false;
56
+ }
57
+ }
58
+
59
+ // Set error if invalid
60
+ const errorEl = this.id(`${type}_error`);
61
+ if (!isValid) {
62
+ if (errorEl) {
63
+ errorEl.innerHTML = msg;
64
+ errorEl.style.color = 'red';
65
+ }
66
+ this.error.push(msg);
67
+ } else {
68
+ if (errorEl) errorEl.innerHTML = ''; // Clear error on success
33
69
  }
34
- return value.trim().length > 0;
70
+
71
+ return isValid;
35
72
  }
36
73
 
37
74
 
75
+ matchRegex(value, type) {
76
+ const regexPatterns = {
77
+ email: /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-Z0-9]{2,4}$/,
78
+ password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/,
79
+ general: /[\w\d\s.,'"!?@#&()\-]/,
80
+ };
81
+
82
+ return regexPatterns[type]?.test(value);
83
+ }
84
+
38
85
  /**
39
- * Loop through all the elements in the form and validate each one.
40
- * If element is empty, add error message to the error array and set result to false
41
- * If element is not empty, check if it validates according to its type (email or general)
42
- * If it does not validate, add error message to the error array and set result to false
43
- * @returns {void}
86
+ *
87
+ * @param {*} optionalFields ["spouseName", "spouseMobile", "fatherEmail"];
88
+ * @param {*} typeMap Create a validation map if certain fields need special types (email, password, etc). const types = {
89
+ email_id: "email",
90
+ password_id: "password",
91
+ custom_text_id: "general"
92
+ };
93
+ * formHelper.massValidate(optional, types);
44
94
  */
45
- massValidate() {
46
- const invalidElements = this.data.flatMap(et => et.filter(post => {
47
- const postName = post.name.replace('_', ' ');
48
- let errMsg = this.id(`${post.name}_error`);
49
-
50
- // rid it off the submit and token
51
- if (['submit', 'button', 'showPassword_id', 'g-recaptcha-response', 'cancel', 'token', 'checkbox_id'].includes(post.name) ||
52
- ['button'].includes(post.id) || ['button'].includes(post.type)) return false;
53
-
54
- // check if there is no value
55
- if (['spouseName', 'spouseMobile', 'spouseEmail', 'fatherMobile', 'fatherEmail', 'motherMobile', 'maidenName', 'motherEmail'].includes(post.name)) {
56
- // post.value is not prpvided if it is not provided
57
- post.value = post.value === "" ? "Not Provided" : post.value
95
+
96
+
97
+
98
+ massValidate(optionalFields = [], typeMap = {}) {
99
+ this.clearError(); // Reset errors
100
+ this.result = 0;
101
+
102
+ for (let input of this.data) {
103
+ const { name, value, id, type, placeholder } = input;
104
+ const errorEl = this.id(`${name}_error`);
105
+
106
+
107
+ // Skip non-input elements
108
+ if (
109
+ ['submit', 'button', 'g-recaptcha-response', 'cancel'].includes(name) ||
110
+ ['button', 'showPassword_id', 'token', 'g-recaptcha-response'].includes(id) ||
111
+ type === 'button' ||
112
+ name === 'checkbox_id'
113
+ ) continue;
114
+
115
+
116
+
117
+ let label = name.replace(/_/g, ' '); // For readable error text
118
+ let val = value.trim();
119
+
120
+ // Handle optional fields
121
+ if (optionalFields.includes(name) && val === '') {
122
+ input.value = 'Not Provided';
123
+ continue;
58
124
  }
59
125
 
60
- if (post.value === '' || post.value === 'select') {
61
- errMsg.innerHTML = `${post.placeholder ?? "*"} cannot be left empty`;
62
- errMsg.style.color = 'red';
63
- this.error.push(`${postName.toUpperCase()} cannot be left empty`);
64
- this.result = false;
65
- return true;
126
+ // Required field check
127
+ if (val === '' || val === 'select') {
128
+ if (errorEl) errorEl.innerHTML = `<li style="color:red;">${label} cannot be left empty.</li>`;
129
+ this.error.push(`${label.toUpperCase()} cannot be left empty.`);
130
+ continue;
66
131
  }
67
132
 
68
- if (post.name === 'email' && !this.validateField(post.value, 'email')) {
69
- errMsg.innerHTML = '* Please enter a valid email';
70
- errMsg.style.color = 'red';
71
- this.error.push('<li style="color: red;">Please enter a valid email</li>');
72
- this.result = false;
73
- return true;
133
+ // Determine field type for regex
134
+ let validateType = typeMap[name] || (
135
+ name.toLowerCase().includes('email') ? 'email' :
136
+ name.toLowerCase().includes('password') ? 'password' : 'general'
137
+ );
138
+
139
+ if (!this.matchRegex(val, validateType)) {
140
+ const msg = `There is a problem with your entry for ${label.toUpperCase()}`;
141
+ if (errorEl) errorEl.innerHTML = `<li style="color:red;">${msg}</li>`;
142
+ this.error.push(msg);
143
+ continue;
74
144
  }
75
145
 
76
- return false;
77
- }));
146
+ if (errorEl) errorEl.innerHTML = ''; // Clear if all good
147
+ }
78
148
 
79
- if (invalidElements.length > 0) this.result = false;
149
+ this.result = this.error.length === 0 ? 1 : 0;
80
150
  }
81
151
 
152
+
153
+
82
154
  emailVal() {
83
155
  const emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
84
- let msg = `<li style=color:'red';> Please enter a valid email</li>`
85
- const email = this.id('email_id').value
156
+ let msg = '<li style=color:\'red\';> Please enter a valid email</li>';
157
+ const email = this.id('email_id').value;
86
158
  if (email.match(emailExp) === null) {
87
- this.id('email_error').innerHTML = msg
88
- this.id('email_error').style.color = "red"
89
- this.error.push(msg)
159
+ this.id('email_error').innerHTML = msg;
160
+ this.id('email_error').style.color = 'red';
161
+ this.error.push(msg);
90
162
  }
91
163
  }
92
164
 
@@ -128,7 +200,7 @@ export default class FormHelper {
128
200
  clearHtml() {
129
201
  this.data.flat().forEach(post => {
130
202
  if (!['submit', 'checkbox'].includes(post.name) && post.type !== 'submit') {
131
- post.value = "";
203
+ post.value = '';
132
204
  }
133
205
  });
134
206
  }
@@ -140,16 +212,17 @@ export default class FormHelper {
140
212
 
141
213
  realTimeCheckLen(input, maxi) {
142
214
  input.forEach((id, i) => {
143
- const theData = this.id(`${id}_id`);
215
+
216
+ const theData = this.id(`${id}`);
144
217
  if (!theData) {
145
- console.error(`Element with ID '${id}_id' not found`);
218
+ console.error(`Element with ID '${id}' not found`);
146
219
  return;
147
220
  }
148
221
  const max = maxi[i];
149
222
  theData.maxLength = parseInt(max) + 1;
150
223
  theData.addEventListener('input', () => {
151
224
  const error = this.id(`${id}_error`);
152
- error.innerHTML = (theData.value.length > max) ? `You have reached the maximum limit` : "";
225
+ error.innerHTML = (theData.value.length > max) ? 'You have reached the maximum limit' : '';
153
226
  this.id(`${id}_help`).style.display = theData.value.length > max ? '' : 'none';
154
227
  });
155
228
  });
@@ -167,12 +240,12 @@ export default class FormHelper {
167
240
  const secondInput = this.id(second + '_id');
168
241
  const error = this.id(`${second}_error`);
169
242
 
170
- const checkMatch = () => error.innerHTML = (firstInput.value !== secondInput.value) ? 'Your passwords do not match' : "";
243
+ const checkMatch = () => error.innerHTML = (firstInput.value !== secondInput.value) ? 'Your passwords do not match' : '';
171
244
 
172
245
  firstInput.addEventListener('input', checkMatch);
173
246
  secondInput.addEventListener('input', checkMatch);
174
247
  }
175
-
248
+
176
249
 
177
250
  /**
178
251
  * Injects the values in the html array to the elements with the IDs in the idArray
@@ -190,11 +263,11 @@ export default class FormHelper {
190
263
  */
191
264
  duplicate(giveInput, takeInput) {
192
265
  let giver, taker;
193
- giver = this.id(giveInput)
194
- taker = this.id(takeInput)
266
+ giver = this.id(giveInput);
267
+ taker = this.id(takeInput);
195
268
  giver.addEventListener('keyup', () => {
196
269
  taker.value = giver.value;
197
- })
270
+ });
198
271
  }
199
272
 
200
273
 
@@ -208,23 +281,23 @@ export default class FormHelper {
208
281
  * @param {string} outputId - the id of the element to update with the response from the server
209
282
  */
210
283
  realTimeServer(input, url, outputId) {
211
- const theInput = this.id(input)
212
- const output = this.id(outputId)
284
+ const theInput = this.id(input);
285
+ const output = this.id(outputId);
213
286
  theInput.addEventListener('keyup', async () => {
214
- const inputVal = theInput.value
287
+ const inputVal = theInput.value;
215
288
 
216
- if (inputVal === "") {
217
- output.innerHTML = "";
289
+ if (inputVal === '') {
290
+ output.innerHTML = '';
218
291
  return;
219
292
  }
220
293
 
221
294
  try {
222
- const response = await axios.get(`${url}=${inputVal}`)
223
- output.innerHTML = response.data
295
+ const response = await axios.get(`${url}=${inputVal}`);
296
+ output.innerHTML = response.data;
224
297
  } catch (error) {
225
- console.error(error)
298
+ console.error(error);
226
299
  }
227
- })
300
+ });
228
301
  }
229
302
 
230
303
  /**
@@ -236,31 +309,15 @@ export default class FormHelper {
236
309
  isChecked(yesId, noId, hiddenInput) {
237
310
  const checked = () => {
238
311
  if (this.id(yesId).checked) {
239
- alert('check')
312
+ alert('check');
240
313
  this.id(hiddenInput).innerHTML = 'checked';
241
314
  } else if (this.id(noId).checked) {
242
315
  this.id(hiddenInput).innerHTML = 'checked';
243
316
  }
244
- }
245
-
246
- this.id(yesId).addEventListener('click', checked)
247
- this.id(noId).addEventListener('click', checked)
248
-
249
- }
250
-
251
- previousAddress() {
252
- const timeAddy = this.id('time_at_address_id')
253
- const prevAddy = this.id('previous_address_class')
254
- const showPrev = () => {
255
- if (timeAddy.value != '3 years+') {
256
- prevAddy.style.display = 'block'
257
- this.id('previous_address_help').innerHTML = "Please enter your full address: House No, Street Name, Town/City and Post Code"
258
- } else {
259
- prevAddy.style.display = 'none'
260
- }
317
+ };
261
318
 
262
- }
263
- timeAddy.addEventListener('change', showPrev)
319
+ this.id(yesId).addEventListener('click', checked);
320
+ this.id(noId).addEventListener('click', checked);
264
321
 
265
322
  }
266
323
 
package/Http.js CHANGED
@@ -1,150 +1,244 @@
1
1
  import { id, log } from './UtilityHtml.js';
2
- import { clearLoader } from './Loader.js';
3
- import axios from 'axios'
4
- import axiosRetry from 'axios-retry';
5
-
6
- axiosRetry(axios, { retries: 3 });
7
-
2
+ import axios from './axiosWrapper.js';
3
+ import { redirectAfterDelay, parseErrorResponse } from './general.js';
8
4
 
5
+ /**
6
+ *
7
+ * Sends form data via POST request.
8
+ * @param {string} url - The URL to post the data to.
9
+ * @param {string} formId - The ID or class of the form.
10
+ * @param {string|null} redirect - The page to redirect to after successful submission.
11
+ * @param {string|null} css - The CSS framework to use for notification styling (e.g., 'W3css', 'bulma').
12
+ NOTICE:::Make sure you set the notification id as the formId_notification
13
+ */
9
14
  export const postFormData = async (url, formId, redirect = null, css = null) => {
10
- const notificationForm = `${formId}_notification`;
15
+
16
+ let notificationForm = `${formId}_notification`;
11
17
  const notificationId = id(notificationForm);
12
18
 
19
+
13
20
  if (!notificationId) {
14
21
  throw new Error('Notification element not found');
15
22
  }
16
-
17
23
  // Cleanup previous notification styles
18
24
  notificationId.style.display = 'none';
19
- notificationId.className = notificationId.className.replace(/is-danger|is-success|w3-red|w3-green|bg-danger|bg-success/g, '');
20
25
 
26
+ ['is-danger', 'is-success', 'w3-red', 'w3-green', 'bg-danger', 'bg-success'].forEach(cls => notificationId.classList.remove(cls));
27
+
28
+ // add value to the hidden csrf input field
29
+ // const csrfToken = getCookieValue('XSRF-TOKEN');
30
+ // if (csrfToken) {
31
+ // const csrfInput = id('token');
32
+ // if (csrfInput) {
33
+ // csrfInput.value = csrfToken; // Set the CSRF token in the hidden input field
34
+ // }
35
+
36
+ // extract the form entries
21
37
  const form = id(formId);
38
+
22
39
  if (!form) {
23
40
  throw new Error('Form element not found');
24
41
  }
25
42
 
26
- const formEntries = new FormData(form);
43
+ let formEntries = new FormData(form);
44
+
27
45
  formEntries.delete('submit');
28
46
  formEntries.delete('checkbox_id');
29
47
 
30
48
  const options = {
31
- baseURL: '/',
32
- xsrfCookieName: 'XSRF-TOKEN',
33
- xsrfHeaderName: 'X-XSRF-TOKEN',
34
- withCredentials: true,
49
+ baseURL: '/', // Adjust to your API base URL
50
+ withCredentials: true, // Ensure cookies (e.g., XSRF token) are sent
35
51
  };
36
52
 
53
+ // AXIOS POST FUNCTIONALITY
37
54
  try {
38
55
  const response = await axios.post(url, formEntries, options);
39
- if (!(response.status >= 200 && response.status < 300)) {
40
- throw new Error(response.data?.message || 'Request failed');
41
- }
42
-
43
56
  const successClass = getNotificationClassByCSS(css || 'bulma', 'green');
44
- const { message } = response.data || {};
45
- const { id: idSetFromHttp, famCode: famCodeSetFromHttp, outcome: dbHttpResult } = typeof message === 'object' ? message : { outcome: message };
46
57
 
47
- if (!idSetFromHttp || !dbHttpResult || !famCodeSetFromHttp) {
48
- throw new Error('Response data is missing required fields');
58
+ // check if response.data.message is an array
59
+ const { message } = response.data || {};
60
+ if( !message) {
61
+ throw new Error('Response data does not contain a message');
49
62
  }
50
-
51
- sessionStorage.setItem('idSetFromHttp', sessionStorage.getItem('idSetFromHttp') || idSetFromHttp);
52
- sessionStorage.setItem('famCodeSetFromHttp', sessionStorage.getItem('famCodeSetFromHttp') || famCodeSetFromHttp);
53
-
54
- processFormDataAction(successClass, dbHttpResult, notificationId);
63
+ processFormDataAction(successClass, message, notificationId);
55
64
 
56
65
  if (redirect) {
57
- setTimeout(() => window.location.assign(redirect), 2000);
66
+ redirectAfterDelay(redirect, 2000);
58
67
  }
68
+
59
69
  } catch (error) {
60
70
  const errorClass = getNotificationClassByCSS(css || 'bulma', 'red');
61
- const errorMessage = error.response?.data?.error || error.request || 'An unknown error occurred';
62
- processFormDataAction(errorClass, errorMessage, notificationId);
71
+ const ErrorMsg = parseErrorResponse(error);
72
+ processFormDataAction(errorClass, ErrorMsg, notificationId);
63
73
  }
64
74
  };
65
75
 
66
-
67
76
  /**
68
- * Displays a notification message and handles the loading indicator.
69
- * @param {string} cssClass - The CSS class to add to the notification element.
70
- * @param {string} message - The message to display in the notification element.
71
- * @param {HTMLElement} formNotificationId - The notification element to display the message in.
72
- * @returns {void}
77
+ * Process form data action.
78
+ * @param {string} cssClass - The CSS class for the notification.
79
+ * @param {string} message - The notification message.
73
80
  */
74
81
  const processFormDataAction = (cssClass, message, formNotificationId) => {
75
- if (!formNotificationId) {
76
- return log('Notification element not found');
82
+ if (formNotificationId) {
83
+ formNotificationId.style.display = 'block';
84
+ formNotificationId.classList.add(cssClass);
85
+ const errorElement = id('error');
86
+ if (errorElement) {
87
+ errorElement.scrollIntoView({ behavior: 'smooth' });
88
+ errorElement.innerHTML = message;
89
+ }
90
+ const loader = id('setLoader');
91
+ if (loader) loader.classList.remove('loader');
92
+ } else {
93
+ log('Notification element not found');
77
94
  }
95
+ };
78
96
 
79
- formNotificationId.style.display = 'block';
80
- formNotificationId.classList.add(cssClass);
81
-
82
- const errorElement = id('error');
83
- if (errorElement) {
84
- errorElement.innerHTML = message;
85
- errorElement.scrollIntoView({ behavior: 'smooth' });
97
+ /**
98
+ * Get the notification class based on the CSS framework.
99
+ * @param {string|null} css - The CSS framework to use for notification styling.
100
+ * @param {string} status - The status of the notification ('green' or 'red').
101
+ * @returns {string} - The corresponding CSS class.
102
+ */
103
+ const getNotificationClassByCSS = (css, status) => {
104
+ switch (css) {
105
+ case 'W3css':
106
+ return status === 'green' ? 'w3-green' : 'w3-red';
107
+ case 'bulma':
108
+ return status === 'green' ? 'is-success' : 'is-danger';
109
+ case 'bootstrap':
110
+ return status === 'green' ? 'bg-success' : 'bg-danger';
111
+ default:
112
+ return status === 'green' ? 'bg-success' : 'bg-danger';
86
113
  }
87
-
88
- clearLoader();
89
114
  };
90
115
 
91
- const getNotificationClassByCSS = (css, color) => (css === 'bulma' ? `is-${color}` : color === 'green' ? `${css}-${color}` : `${css}-danger`);
92
-
93
116
 
94
117
  /**
95
- * Fetches data from a specified API endpoint using a GET request.
96
118
  *
97
- * @param {string} URL - The API endpoint to fetch data from.
98
- * @param {string|null} [token=null] - Optional authorization token for the request.
99
- * @returns {Promise<Object>} - A promise that resolves with the response data or rejects with an error.
119
+ * @param { the url you want to get} URL
120
+ * @returns
121
+ // now we can use that data from the outside!
122
+ axiosTest()
123
+ .then(data => {
124
+ response.json({ message: 'Request received!', data })
125
+ })
126
+ .catch(err => console.log(err))
100
127
  */
101
128
 
102
129
  export const getApiData = async (URL, token = null) => {
103
- const headers = {
104
- 'X-Requested-With': 'XMLHttpRequest',
105
- 'Content-Type': 'application/json',
106
- 'Accept': 'application/json',
107
- };
108
- if (token) {
109
- headers['Authorization'] = `Bearer ${token}`;
110
- }
111
-
112
130
  try {
113
- const response = await axios.get(URL, { headers });
114
- return response.data;
131
+
132
+ const config = {
133
+ headers: {
134
+ 'X-Requested-With': 'XMLHttpRequest',
135
+ 'Content-Type': 'application/json',
136
+ 'Accept': 'application/json',
137
+ 'Authorization': 'Bearer ' + token
138
+ },
139
+ };
140
+
141
+ const fetch = await axios.get(URL, config);
142
+ return fetch.data;
143
+
144
+
115
145
  } catch (error) {
116
- return Promise.reject(error);
146
+
147
+ return error;
148
+
117
149
  }
118
- }
119
150
 
120
151
 
152
+ };
153
+
121
154
  export const getMultipleApiData = async (url1, url2, token = null) => {
122
- const config = {
123
- headers: {
124
- 'X-Requested-With': 'XMLHttpRequest',
125
- 'Content-Type': 'application/json',
126
- 'Accept': 'application/json',
127
- Authorization: `Bearer ${token}`,
128
- },
129
- };
155
+ try {
156
+
157
+ const config = {
158
+ headers: {
159
+ 'X-Requested-With': 'XMLHttpRequest',
160
+ 'Content-Type': 'application/json',
161
+ 'Accept': 'application/json',
162
+ 'Authorization': 'Bearer ' + token
163
+ },
164
+ };
165
+
166
+ const fetch = await axios.all([
167
+ axios.get(url1, config),
168
+ axios.get(url2, config)
169
+ ]);
170
+ return fetch;
171
+
172
+ } catch (error) {
173
+
174
+ return error;
175
+
176
+ }
177
+
130
178
 
131
- return await axios.all([axios.get(url1, config), axios.get(url2, config)]).then(axios.spread((res1, res2) => [res1.data, res2.data]));
132
179
  };
133
180
 
181
+
182
+ // build a function to post multiple api form data
183
+
134
184
  export const postMultipleApiData = async (url1, url2, formData, token = null) => {
135
- const config = {
136
- headers: {
137
- 'X-Requested-With': 'XMLHttpRequest',
138
- 'Content-Type': 'application/json',
139
- 'Accept': 'application/json',
140
- 'Authorization': 'Bearer ' + token
141
- },
142
- };
185
+ try {
143
186
 
144
- const [res1, res2] = await Promise.all([
145
- axios.post(url1, formData, config),
146
- axios.post(url2, formData, config),
147
- ]);
187
+ const config = {
188
+ headers: {
189
+ 'X-Requested-With': 'XMLHttpRequest',
190
+ 'Content-Type': 'application/json',
191
+ 'Accept': 'application/json',
192
+ 'Authorization': 'Bearer ' + token
193
+ },
194
+ };
195
+ const fetch = await axios.all([
196
+ axios.post(url1, formData, config),
197
+ axios.post(url2, formData, config)
198
+ ]);
199
+
200
+ return fetch;
201
+
202
+ } catch (error) {
203
+ return error;
204
+ }
205
+ };
206
+ /**
207
+ *
208
+ * @param { name} cname
209
+ * @param {* value} cvalue
210
+ * @param {* no of days 365} exdays
211
+ */
212
+ export const setCookie = (cname, cvalue, exdays) => {
213
+ var d = new Date();
214
+ d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
215
+ var expires = 'expires=' + d.toUTCString();
216
+ document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
217
+ };
148
218
 
149
- return [res1.data, res2.data];
219
+ export const getCookie = (cname) => {
220
+ var name = cname + '=';
221
+ var ca = document.cookie.split(';');
222
+ for (var i = 0; i < ca.length; i++) {
223
+ var c = ca[i];
224
+ while (c.charAt(0) == ' ') {
225
+ c = c.substring(1);
226
+ }
227
+ if (c.indexOf(name) == 0) {
228
+ return c.substring(name.length, c.length);
229
+ }
230
+ }
231
+ return '';
150
232
  };
233
+
234
+ export const checkCookie = () => {
235
+ var user = getCookie('username');
236
+ if (user != '') {
237
+ alert('Welcome again ' + user);
238
+ } else {
239
+ user = prompt('Please enter your name:', '');
240
+ if (user != '' && user != null) {
241
+ setCookie('username', user, 365);
242
+ }
243
+ }
244
+ };
package/Loader.js CHANGED
@@ -1,4 +1,4 @@
1
- import { id } from './global.js';
1
+ import { id } from './UtilityHtml.js';
2
2
 
3
3
  export const loaderIconBootstrap = () => {
4
4