-
Notifications
You must be signed in to change notification settings - Fork 11
/
questionnaire.js
1584 lines (1377 loc) · 54.3 KB
/
questionnaire.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Tree } from "./tree.js";
import { knownFunctions } from "./knownFunctions.js";
import { removeQuestion } from "./localforageDAO.js";
import { validateInput, validationError } from "./validate.js"
import { translate } from "./common.js";
export const moduleParams = {};
import * as mathjs from 'https://cdn.skypack.dev/[email protected]';
export const math=mathjs.create(mathjs.all)
window.math = math
// create a class YearMonth custom datatype for use in mathjs to handle
// the month class...
export function YearMonth(str) {
if (str?.isYearMonth) {
this.month = str.month
this.year = str.year
} else {
let x = str.match(/^(\d+)\-(\d+)$/)
this.month = parseInt(x[2]).toLocaleString(navigator.language, { minimumIntegerDigits: 2 })
this.year = x[1]
}
}
YearMonth.prototype.isYearMonth = true
YearMonth.prototype.toString = function () {
return `${this.year}-${this.month}`
}
// create an add function. Note: YearMonth + integer = String
YearMonth.prototype.add = function (n) {
let m = parseInt(this.month) + n
let yr = parseInt(this.year) + ((m > 12) ? 1 : 0);
// if month == 0, set it to 12
let mon = (m % 12) || 12
return new YearMonth(`${yr}-${mon}`).toString()
}
// Note: YearMonth - n = String
YearMonth.prototype.subtract = function (n) {
let m = parseInt(this.month) - n
let yr = parseInt(this.year) - ((m > 0) ? 0 : 1);
let mon = ((m + 12) % 12) || 12
return new YearMonth(`${yr}-${mon}`).toString()
}
// Note: YearMonth - YearMonth = integer
YearMonth.prototype.subMonth = function(ym){
return (12*(parseInt(this.year)-parseInt(ym.year)) + parseInt(this.month)-parseInt(ym.month));
}
// This works in all cases except x=new String(),
// which you should never do anyway...
let isString = (value) => typeof value == 'string'
// Note: these function make explicit
// use of the fact that the DOM stores information.
// be careful the DOM and the localforage become
// mis-aligned.
export const myFunctions = {
exists: function (x) {
if (!x) return false;
if (x.toString().includes('.')) {
return !math.isUndefined( getKeyedValue(x) )
}
let element = document.getElementById(x);
// handle the array case (checkboxes)...
if (Array.isArray(element?.value)) return !!element.value.length
// note !! converts "truthy" values
return (!!element && !!element.value) || moduleParams.previousResults.hasOwnProperty(x)
},
doesNotExist: function (x) {
return !math.exists(x)
},
noneExist: function (...ids) {
// if you give me no ids, none of them exist therefore true...
// loop through all the ids of any exists then return false...
return ids.every(id => math.doesNotExist(id))
},
someExist: function (...ids) {
return ids.some(id => math.exists(id))
},
allExist: function (...ids) {
return ids.every(id => math.exists(id))
},
_value: function (x) {
if (!math.exists(x)) return null
if (x.toString().includes('.')) {
return getKeyedValue(x)
}
let element = document.getElementById(x);
let returnValue = (element) ? element.value : moduleParams.previousResults[x]
return returnValue
},
valueEquals: function (id, value) {
// if id is not passed in return FALSE
if (math.doesNotExist(id)) return false;
let element_value = math._value(id);
// catch if we have a combobox...
if (element_value[id]) {
element_value = element_value[id]
}
// if the element does not exist return FALSE
return (element_value == value)
},
equals: function(id, value){
return math.valueEquals(id,value)
},
valueIsOneOf: function (id, ...values) {
if (myFunctions.doesNotExist(id)) return false;
// compare as strings so "1" == "1"
values = values.map(v => v.toString())
let test_values = math._value(id);
// catch if we have a combobox...
if (test_values[id]) {
test_values = test_values[id]
}
if (Array.isArray(test_values)) {
return (test_values.some(v => values.includes(v.toString())))
}
return values.includes(test_values.toString())
},
/**
* checks whether the value for id is
* between the values of lowerLimit and upperLimit inclusively
* lowerLimit <= value(id) <= upperlimit
*
* if you pass in an array of ids, it uses the first id that exists. The
* array is passed into valueOrDefault.
*
* @param {Number} lowerLimit The lowest acceptable value
* @param {Number} upperLimit the highest acceptable value
* @param {Array} ids An array of values, passed into valueOrDefault.
* @return {boolean} is lowerLimit <= value(id) <= upperLimit
*/
valueIsBetween: function (lowerLimit, upperLimit, ...ids) {
if (lowerLimit === undefined || upperLimit === undefined || ids === undefined) return false;
let value = undefined;
value = (ids.length > 1) ? myFunctions.valueOrDefault(ids.shift(), ids) : myFunctions._value(ids.shift())
// for this function to work, value, lowerLimit, and
// upperLimit MUST be numeric....
if (!isNaN(value) && !isNaN(lowerLimit) && !isNaN(value)) {
return (parseFloat(lowerLimit) <= value && value <= parseFloat(upperLimit))
}
return false
},
/**
* Given a comma separated value of Conditions and values, returns a string of all the values that exist.
* separated by a comma or the optional separator
*
* i.e. existingValues(exists("ID1"),displaytext,exists("ID2"),displaytext)
*
* @param {args} the args should be condition1, VAL1, condition2, VAL2, (optional)sep=,
*
*/
existingValues: function (args) {
if (!args) return ""
let argArray = math.parse(args).args
let sep = ", "
if (argArray[argArray.length - 1].name == "sep") {
sep = argArray.pop().evaluate()
}
// we better have (id/value PAIRS)
argArray = argArray.reduce((prev, current, index, array) => {
// skip the ids...
if (index % 2 == 0) return prev
// see if the id exists, if so keep the value
if (array[index - 1].evaluate()) prev.push(math.valueOrDefault(current.evaluate(), current.evaluate()))
return prev
}, [])
return argArray.join(sep)
},
// if the value of id is a string
// return the string length, otherwise
// return -1
valueLength: function(id){
// if id is not passed in return FALSE
if (math.doesNotExist(id)) return false;
let element_value = math._value(id);
if (isString(element_value)){
return element_value.length
}
return -1;
},
dateCompare: function (month1, year1, month2, year2) {
if (
[month1, month2].some((m) => { let m1 = parseInt(m); m1 < 0 || m1 > 11 })
) {
throw 'DateCompareError:months need to be from 0 (Jan) to 11 (Dec)'
}
if (
[year1, year2].some((yr) => isNaN(yr))
) {
throw 'DateCompareError:years need to be numeric'
}
let date1 = (new Date(year1, month1)).getTime()
let date2 = (new Date(year2, month2)).getTime()
return (date1 < date2) ? -1 : (date1 == date2) ? 0 : 1
},
isSelected: function (id) {
// if the id doesnt exist, the ?.checked returns undefined.
// !!undefined == false.
return (!!document.getElementById(id)?.checked)
},
someSelected: function (...ids) {
return (ids.some(id => math.isSelected(id)))
},
noneSelected: function(...ids){
return (!ids.some(id => math.isSelected(id)))
},
// defaultValue accepts an Id and a value or a Id/Value
// If only 1 default value is given, first it looks it up
// if it does not exist assume it is a value...
// If 2 default values are given, look up the first, if it
// does not exist, return the second as a value...
valueOrDefault: function (x, ...defaultValue) {
let v = math._value(x)
let indx = 0;
while (v == null && defaultValue.length > indx) {
v = math._value(defaultValue[indx])
if (v == null) indx++
}
if (v == null) v = defaultValue[defaultValue.length - 1]
return (v)
},
selectionCount: function(x,countReset=false){
let [questionId,name] = x.split(':')
name = name ?? questionId
if (!math.exists(questionId)) return 0
let v = math._value(questionId)
// BUG FIX: if the data-reset ("none of the above") is selected
let questionElement = document.getElementById(questionId)
if ( Array.isArray(v) || Array.isArray(v[name]) ) {
v = Array.isArray(v)?v:v[name]
if (countReset){
return v.length;
}
// there is a chance that nothing is selected (v.length==0) in that case you will the
// selector will find nothing. Use the "?" because you cannot find the dataset on a null object.
return questionElement.querySelector(`input[type="checkbox"][name="${name}"]:checked`)?.dataset["reset"]?0:v.length
}
// if we want object to return the number of keys
// Object.keys(v).length
// otherwise:
return 0;
},
// For a question in a loop, does the value of the response
// for ANY ITERATION equal a value from a given set.
loopQuestionValueIsOneOf: function (id, ...values) {
// Loops append _n_n to the id, where n is an
// integer starting from 1...
for (let i = 1; ; i = i + 1) {
let tmp_qid = `${id}_${i}_${i}`
// the Id does not exist, we've gone through
// all potential question and have not found
// a value in the set of "acceptable" values...
if (math.doesNotExist(tmp_qid)) return false;
if (math.valueIsOneOf(tmp_qid, ...values)) return true
}
},
gridQuestionsValueIsOneOf: function (gridId, ...values) {
if (math.doesNotExist(gridId)) return false
let gridElement = document.getElementById(gridId)
if (! "grid" in gridElement.dataset) return false
values = values.map(v => v.toString())
let gridValues = math._value(gridId)
for (const gridQuestionId in gridValues) {
// even if there is only one value, force it into
// an array. flatten it to make sure that it's a 1-d array
let test_values = [gridValues[gridQuestionId]].flat()
if (test_values.some(v => values.includes(v.toString()))) {
return true;
}
}
return false;
},
yearMonth: function (str) {
let isYM = /^(\d+)\-(\d+)$/.test(str)
if (isYM) {
return new YearMonth(str)
}
let value = math._value(str)
isYM = /^(\d+)\-(\d+)$/.test(value)
if (isYM) {
return new YearMonth(value)
}
return false;
},
YearMonth: YearMonth,
}
function getKeyedValue(x) {
let array = x.toString().split('.')
// convert null or undefined to undefined...
let obj = math._value(`${array.splice(0, 1)}`) ?? undefined
return array.reduce((prev, curr) => {
if ( math.isUndefined(prev) ) return prev
return prev[curr] ?? undefined
}, obj)
}
// Tell mathjs about the YearMonth class
math.typed.addType({
name: 'YearMonth',
test: function (x) {
return x && x.isYearMonth
}
})
// Tell math.js how to add a YearMonth with a number
const add = math.typed('add', {
'YearMonth, number': function (dte, m) {
return dte.add(m)
},
'number, YearMonth': function (m, dte) {
return dte.add(m)
}
})
const subtract = math.typed('subtract', {
'YearMonth, number': function (dte, m) {
return dte.subtract(m)
},
'YearMonth, YearMonth': function (dte2, dte1) {
return dte2.subMonth(dte1)
}
})
myFunctions.add = add;
myFunctions.subtract = subtract
window.myFunctions = myFunctions;
math.import({
myFunctions
})
// The questionQueue is an Tree which contains
// the question ids in the order they should be displayed.
export const questionQueue = new Tree();
export function isFirstQuestion() {
return questionQueue.isEmpty() || questionQueue.isFirst();
}
/**
* Determine the storage format for the response data.
* Grid questions are stored as objects. Ensure each key is stored with the response.
* Single response (radio) input questions are stored as primitives.
* Multi-selection (checkbox) input questions are stored as arrays.
* @param {HTMLElement} form - the form element being evaluated.
* @returns {boolean} - true if the key must be stored with the response (Object), false otherwise (primitive).
*/
function isObjectStore(form) {
if (form.dataset?.grid === 'true') return true;
const responseInputs = Array.from(form.querySelectorAll("input, textarea, select")).reduce((acc, current) => {
if (current.type == "submit" || current.type == "hidden") return acc;
if (["radio", "checkbox"].includes(current.type)) {
acc[current.name] = true;
} else {
acc[current.id] = true;
}
return acc;
}, {});
return Object.keys(responseInputs).length !== 1;
}
function setFormValue(form, value, id) {
if (value === "" || Array.isArray(value) && value.length === 0) {
value = undefined;
}
if (!id || id.trim() === "") return;
if (!isObjectStore(form)) {
form.value = value;
} else {
if (!form.value) {
form.value = {};
}
form.value[id] = value;
if (value == undefined) {
delete form.value[id]
}
}
}
// here are function that handle the
// user selection and attach the
// selected value to the form (question)
export function textBoxInput(event) {
let inputElement = event.target;
textboxinput(inputElement);
}
export function parseSSN(event) {
if (event.type == "keyup") {
let element = event.target;
let val = element.value.replace(/\D/g, "");
let newVal = "";
if (val.length >= 3 && val.length < 5 && event.code != "Backspace") {
//reformat and return SSN
newVal += val.replace(/(\d{3})/, "$1-");
element.value = newVal;
}
if (val.length >= 5 && event.code != "Backspace") {
//reformat and return SSN
newVal += val.replace(/(\d{3})(\d{2})/, "$1-$2-");
element.value = newVal;
}
return null;
}
}
export function parsePhoneNumber(event) {
if (event.type == "keyup") {
let element = event.target;
let phone = element.value.replace(/\D/g, "");
let newVal = "";
if (phone.length >= 3 && phone.length < 6 && event.code != "Backspace") {
//reformat and return phone number
newVal += phone.replace(/(\d{3})/, "$1-");
element.value = newVal;
}
if (phone.length >= 6 && event.code != "Backspace") {
//reformat and return phone number
newVal += phone.replace(/(\d{3})(\d{3})/, "$1-$2-");
element.value = newVal;
}
return null;
}
}
export function callExchangeValues(nextElement) {
exchangeValue(nextElement, "min", "data-min");
exchangeValue(nextElement, "max", "data-max")
exchangeValue(nextElement, "minval", "data-min");
exchangeValue(nextElement, "maxval", "data-max")
exchangeValue(nextElement, "data-min", "data-min")
exchangeValue(nextElement, "data-max", "data-max");
}
function exchangeValue(element, attrName, newAttrName) {
let attr = element.getAttribute(attrName)?.trim();
// !!! DONT EVALUATE 2020-01 to 2019
// !!! DONT EVALUATE 2023-07-19-to 1997
// may have to do this for dates too. <- yeah, had to!
// Firefox and Safari for MacOS think <input type="month"> has type="text"...
// so month selection calendar is not shown.
if ( (element.getAttribute("type") == "month" && /^\d{4}-\d{1,2}$/.test(attr)) ||
(element.getAttribute("type") == "date" && /^\d{4}-\d{1,2}-\d{1,2}$/.test(attr)) ){
// if leading zero for single digit month was stripped by the browser, add it back.
if (element.getAttribute("type") == "month" && /^\d{4}-\d$/.test(attr)) {
attr = attr.replace(/-(\d)$/, '-0$1')
}
element.setAttribute(newAttrName, attr)
return element;
}
if (attr) {
let isnum = /^[\d\.]+$/.test(attr);
if (!isnum) {
let tmpVal = evaluateCondition(attr);
// note: tmpVal==tmpVal means that tmpVal is Not Nan
if (tmpVal == undefined || tmpVal == null || tmpVal != tmpVal) {
const previousResultsErrorMessage = moduleParams.previousResults && typeof moduleParams.previousResults === 'object' && Object.keys(moduleParams.previousResults)?.length === 0 && attr.includes('isDefined')
? `\nUsing the Markup Renderer?\nEnsure your variables are added to Settings -> Previous Results in JSON format.\nEx: {"AGE": "45"}`
: '';
console.error(`Module Coding Error: Evaluating ${element.id}:${attrName} expression ${attr} => ${tmpVal} ${previousResultsErrorMessage}`)
validationError(element, `Module Coding Error: ${element.id}:${attrName} ${previousResultsErrorMessage}`)
return
}
console.log('------------exchanged Vals-----------------')
console.log(`${element}, ${attrName}, ${newAttrName}, ${tmpVal}`)
element.setAttribute(newAttrName, tmpVal);
} else {
element.setAttribute(newAttrName, attr);
}
}
return element;
}
// TODO: Look here for Safari text input delay issue.
export function textboxinput(inputElement, validate = true) {
let evalBool = "";
const modalElement = document.getElementById('softModalResponse');
if (!modalElement.classList.contains('show')) {
const modal = new bootstrap.Modal(modalElement);
if (inputElement.getAttribute("modalif") && inputElement.value != "") {
evalBool = math.evaluate(
decodeURIComponent(inputElement.getAttribute("modalif").replace(/value/, inputElement.value))
);
}
if (inputElement.getAttribute("softedit") == "true" && evalBool == true) {
if (inputElement.getAttribute("modalvalue")) {
document.getElementById("modalResponseBody").innerText = decodeURIComponent(inputElement.getAttribute("modalvalue"));
modal.show();
}
}
}
if (inputElement.className == "SSN") {
// handles SSN auto-format
parseSSN(inputElement);
}
if (['text', 'number', 'email', 'tel', 'date', 'month', 'time'].includes(inputElement.type)) {
if (validate) {
validateInput(inputElement)
}
}
// BUG 423: radio button not changing value
let radioWithText = inputElement.closest(".response")?.querySelector("input[type='radio']")
if (radioWithText && inputElement.value?.trim() !== ''){
radioWithText.click()
radioAndCheckboxUpdate(radioWithText)
}
clearSelection(inputElement);
let value = handleXOR(inputElement);
let id = inputElement.id
value = value ? value : inputElement.value;
setFormValue(inputElement.form, value, id);
}
// onInput/Change handler for radio/checkboxex
export function rbAndCbClick(event) {
let inputElement = event.target;
// when we programatically click, the input element is null.
// however we call radioAndCheckboxUpdate directly..
if (inputElement) {
validateInput(inputElement)
radioAndCheckboxUpdate(inputElement);
radioAndCheckboxClearTextInput(inputElement);
}
}
//for when radio/checkboxes have input fields, only enable input fields when they are selected
export function radioAndCheckboxClearTextInput(inputElement) {
// this fails when the element name is not the same as the question id...
//let parent = document.getElementById(inputElement.name);
let parent = inputElement.form
// get all responses that have an input text box (can be number, date ..., not radio/checkbox)
let responses = [...parent.querySelectorAll(".response")]
.filter(resp => resp.querySelectorAll("input:not([type=radio]):not([type=checkbox])").length)
.filter(resp => resp.querySelectorAll("input[type=radio],input[type=checkbox]").length)
// if the checkbox is selected, make sure the input box is enable
// if the checkbox is not selected, make disable it and clear the value...
// Note: things that can go wrong.. if a response has more than one text box.
responses.forEach(resp => {
let text_box = resp.querySelector("input:not([type=radio]):not([type=checkbox])")
let checkbox = resp.querySelector("input[type=radio],input[type=checkbox]")
//text_box.disabled = !checkbox.checked
if (!checkbox.checked) {
text_box.value = ""
delete inputElement.form.value[text_box.id]
}
})
}
export function radioAndCheckboxUpdate(inputElement) {
if (!inputElement) return;
clearSelection(inputElement);
let selectedValue = {};
if (inputElement.type == "checkbox") {
// get all checkboxes with the same name attribute...
selectedValue = Array.from(
inputElement.form.querySelectorAll(
`input[type = "checkbox"][name = ${inputElement.name}]`
)
)
.filter((x) => x.checked)
.map((x) => x.value);
} else {
// we have a radio button.. just get the selected value...
selectedValue = inputElement.value;
}
setFormValue(inputElement.form, selectedValue, inputElement.name);
}
function clearSelection(inputElement) {
if (!inputElement.form || !inputElement.name) return;
let sameName = [
...inputElement.form.querySelectorAll(`input[name = ${inputElement.name}],input[name = ${inputElement.name}] + label > input`)
].filter((x) => x.type != "hidden");
/*
if this is a "none of the above", go through all elements with the same name
and mark them as "false" or clear the text values
*/
if (inputElement.dataset.reset) {
sameName.forEach((element) => {
switch (element.type) {
case "checkbox":
element.checked = element == inputElement ? element.checked : false;
break;
case "radio":
break;
default:
element.value = element == inputElement ? inputElement.value : "";
setFormValue(element.form, element.value, element.id);
if (element.nextElementSibling && element.nextElementSibling.children.length !== 0) element.nextElementSibling.children[0].innerText = "";
element.form.classList.remove("invalid");
if (inputElement.form.value) {
delete inputElement.form.value[element.id];
}
break;
}
});
} else {
// otherwise if this as another element with the same name and is marked as "none of the above" clear that.
// don't clear everything though because you are allowed to have multiple choices.
sameName.forEach((element) => {
if (element.dataset.reset) {
//uncheck reset value
element.checked = false
//removing speciically the reset value from the array of checkboxes checked
//removing from forms.value
const key1 = element.name;
const elementValue = element.value;
const vals = element.form?.value ?? {};
if (vals.hasOwnProperty(key1) && Array.isArray(vals[key1])) {
let index = vals[key1].indexOf(elementValue)
if (index != -1) {
vals[key1].splice(index, 1)
}
if (vals[key1].length == 0) {
delete vals[key1]
}
}
}
});
}
}
export function handleXOR(inputElement) {
if (!inputElement.hasAttribute("xor")) {
return inputElement.value;
}
// if the user tabbed through the xor, Dont clear anything
if (!["checkbox", "radio"].includes(inputElement.type) && inputElement.value.length == 0) {
return null;
}
let valueObj = {};
valueObj[inputElement.id] = inputElement.value;
let sibs = [...inputElement.parentElement.querySelectorAll("input")];
sibs = sibs.filter(
(x) =>
x.hasAttribute("xor") &&
x.getAttribute("xor") == inputElement.getAttribute("xor") &&
x.id != inputElement.id
);
sibs.forEach((x) => {
if (inputElement.form.value) {
delete inputElement.form.value[x.id]
}
if (["checkbox", "radio"].includes(x.type)) {
x.checked = x.dataset.reset ? false : x.checked;
} else {
x.value = "";
if (x.nextElementSibling.children.length !== 0 && x.nextElementSibling.children[0].tagName == "SPAN") {
if (x.nextElementSibling.children[0].innerText.length != 0) {
x.nextElementSibling.children[0].innerText = "";
x.classList.remove("invalid");
x.form.classList.remove('invalid');
x.nextElementSibling.remove();
}
}
valueObj[x.id] = x.value;
}
});
return valueObj[inputElement.id];
}
export function nextClick(norp, retrieve, store, rootElement) {
// Because next button does not have ID, modal will pass-in ID of question
// norp needs to be next button element
if (typeof norp == "string") {
norp = document.getElementById(norp).querySelector(".next");
}
// check that each required element is set...
norp.form.querySelectorAll("[data-required]").forEach((elm) => {
validateInput(elm)
});
showModal(norp, retrieve, store, rootElement);
}
function setNumberOfQuestionsInModal(num, norp, retrieve, store, soft) {
const prompt = translate("basePrompt", [num > 1 ? "are" : "is", num, num > 1 ? "s" : ""]);
const modalID = soft ? 'softModal' : 'hardModal';
const modal = new bootstrap.Modal(document.getElementById(modalID));
const softModalText = translate("softPrompt");
const hardModalText = translate("hardPrompt", [num > 1 ? "s" : ""]);
document.getElementById(soft ? "modalBodyText" : "hardModalBodyText").innerText = `${prompt} ${soft ? softModalText : hardModalText}`;
if (soft) {
const continueButton = document.getElementById("modalContinueButton");
continueButton.removeEventListener("click", continueButton.clickHandler);
//await the store operation on 'continue without answering' click for correct screen reader focus
continueButton.clickHandler = async () => {
await nextPage(norp, retrieve, store);
};
continueButton.addEventListener("click", continueButton.clickHandler);
}
modal.show();
// Set focus to the modal title
document.getElementById("softModalTitle").focus();
let modalElement = modal._element;
modalElement.querySelector('.close').addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
modal.hide();
}
});
}
// show modal function
function showModal(norp, retrieve, store, rootElement) {
if (norp.form.getAttribute("softedit") == "true" || norp.form.getAttribute("hardedit") == "true") {
// Fieldset is the parent of the inputs for all but grid questions. Grid questions are in a table.
const fieldset = norp.form.querySelector('fieldset') || norp.form.querySelector('tbody');
let numBlankResponses = [...fieldset.children]
.filter(x =>
x.tagName !== 'DIV' && x.tagName !== 'BR' &&
x.type && x.type !== 'hidden' &&
x.value !== undefined &&
(x.style ? x.style.display !== "none" : true) &&
!x.hasAttribute("xor")
).reduce((t, x) =>
x.value.length == 0 ? t + 1 : t, 0
);
let hasNoResponses = getSelectedResponses(fieldset).filter((x) => x.type !== "hidden").length === 0;
if (fieldset.hasAttribute("radioCheckboxAndInput")) {
if (!radioCbHasAllAnswers(fieldset)) {
hasNoResponses = true;
}
}
if (norp.form.dataset.grid) {
if (!gridHasAllAnswers(fieldset)) {
hasNoResponses = true;
}
numBlankResponses = numberOfUnansweredGridQuestions(fieldset);
}
if (numBlankResponses == 0 && hasNoResponses == true) {
numBlankResponses = 1;
} else if ((numBlankResponses == 0) == true && hasNoResponses == false) {
numBlankResponses = 0;
} else if ((numBlankResponses == 0) == false && hasNoResponses == true) {
numBlankResponses = numBlankResponses;
} else {
numBlankResponses = 0;
}
if (numBlankResponses > 0) {
setNumberOfQuestionsInModal(numBlankResponses, norp, retrieve, store, norp.form.getAttribute("softedit") == "true");
return null;
}
}
nextPage(norp, retrieve, store, rootElement);
}
let tempObj = {};
async function updateTree() {
if (moduleParams?.renderObj?.updateTree) {
moduleParams.renderObj.updateTree(moduleParams.questName, questionQueue)
}
updateTreeInLocalForage()
}
async function updateTreeInLocalForage() {
// We dont have questName yet, don't bother saving the tree yet...
if (!('questName' in moduleParams)) {
return
}
let questName = moduleParams.questName;
await localforage.setItem(questName + ".treeJSON", questionQueue.toVanillaObject());
}
function getNextQuestionId(currentFormElement) {
// get the next question from the questionQueue
// if it exists... otherwise get the next look at the
// markdown and get the question follows.
let nextQuestionNode = questionQueue.next();
if (nextQuestionNode.done) {
// We are at the end of the question queue...
// get the next element from the markdown...
let tmp = currentFormElement.nextElementSibling;
// we are at a question that should be displayed add it to the queue and
// make it the current node.
questionQueue.add(tmp.id);
nextQuestionNode = questionQueue.next();
}
return nextQuestionNode.value;
}
function showLoadingIndicator() {
const loadingIndicator = document.createElement('div');
loadingIndicator.id = 'loadingIndicator';
loadingIndicator.innerHTML = '<div class="spinner"></div>';
document.body.appendChild(loadingIndicator);
}
function hideLoadingIndicator() {
const loadingIndicator = document.getElementById('loadingIndicator');
if (loadingIndicator) {
document.body.removeChild(loadingIndicator);
}
}
// norp == next or previous button (which ever is clicked...)
async function nextPage(norp, retrieve, store, rootElement) {
// The root is defined as null, so if the question is not the same as the
// current value in the questionQueue. Add it. Only the root should be effected.
// NOTE: if the root has no children, add the current question to the queue
// and call next().
let questionElement = norp.form;
questionElement.querySelectorAll("[data-hidden]").forEach((x) => {
x.value = "true"
setFormValue(questionElement, x.value, x.id)
});
if (checkValid(questionElement) == false) {
return null;
}
if (questionQueue.isEmpty()) {
questionQueue.add(questionElement.id);
questionQueue.next();
}
let questName = moduleParams.questName;
tempObj[questionElement.id] = questionElement.value;
// check if we need to add questions to the question queue
checkForSkips(questionElement);
let nextQuestionId = getNextQuestionId(questionElement);
// get the actual HTML element.
let nextElement = document.getElementById(nextQuestionId.value);
nextElement = exitLoop(nextElement);
// before we add the next question to the queue...
// check for the displayif status...
while (nextElement?.hasAttribute("displayif")) {
// not sure what to do if the next element is is not a question ...
if (nextElement.classList.contains("question")) {
let display = evaluateCondition(nextElement.getAttribute("displayif"));
if (display) break;
if (nextElement.id.substring(0, 9) != "_CONTINUE") questionQueue.pop();
let nextQuestionId = nextElement.dataset.nodisplay_skip;
if (nextElement.dataset.nodisplay_skip) {
questionQueue.add(nextElement.dataset.nodisplay_skip);
}
nextQuestionId = getNextQuestionId(nextElement);
nextElement = document.getElementById(nextQuestionId.value);
nextElement = exitLoop(nextElement);
} else {
console.log(
" ============= next element is not a question... not sure what went wrong..."
);
console.trace();
}
}
//Check if questionElement exists first so its not pushing undefineds
//TODO if store is not defined, call lfstore -> redefine store to be store or lfstore
if (store) {
try {
// show a loading indicator for variables in delayedParameterArray (they take extra time to process)
if (moduleParams.delayedParameterArray.includes(nextElement.id)) showLoadingIndicator();
let formData = {};
formData[`${questName}.${questionElement.id}`] = questionElement.value;
console.log(formData)
await store(formData)
} catch (e) {
console.error("Store failed", e);
} finally {
hideLoadingIndicator();
}
} else {
let tmp = await localforage
.getItem(questName)
.then((allResponses) => {
// if their is not an object in LF create one that we will add later...
if (!allResponses) {
allResponses = {};
}
// set the value for the questionId...
allResponses[questionElement.id] = questionElement.value;
if (questionElement.value === undefined) {
delete allResponses[questionElement.id]
}
return allResponses;
})
.then((allResponses) => {
// allResposes really should be defined at this point. If it wasn't
// previously in LF, the previous block should have created it...
localforage.setItem(questName, allResponses, () => {
console.log(
"... Response stored in LF: " + questName,
JSON.stringify(allResponses)
);
});
});
}
//hide the current question
questionElement.classList.remove("active");
displayQuestion(nextElement);
window.scrollTo(0, 0);
}
export async function submitQuestionnaire(store, questName) {
console.log("submit questionnaire clicked!");
if (store) {
let formData = {};
formData[`${questName}.COMPLETED`] = true;
formData[`${questName}.COMPLETED_TS`] = new Date();
try {
store(formData);
} catch (e) {
console.log("Store failed", e);
}
}
}
function exitLoop(nextElement) {
if (!nextElement) {
console.error("nextElement is null or undefined");
return null;
}
if (nextElement.hasAttribute("firstquestion")) {
let loopMaxElement = document.getElementById(nextElement.getAttribute("loopmax"));
if (!loopMaxElement) {
console.error(`LoopMaxElement is null or undefined for ${nextElement.id}`);
return nextElement;
}