forked from episphere/quest
-
Notifications
You must be signed in to change notification settings - Fork 1
/
questionProcessor.js
1497 lines (1264 loc) · 62.8 KB
/
questionProcessor.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 { moduleParams } from './questionnaire.js';
import { parseGrid } from './buildGrid.js';
import { translate } from './common.js';
import { evaluateCondition } from "./evaluateConditions.js";
import { getStateManager } from './stateManager.js';
const questionSeparatorRegex = /\[([A-Z_][A-Z0-9_#]*[?!]?)(?:\|([^,|\]]+)\|?)?(,.*?)?\](.*?)(?=$|\[[A-Z_]|<form)/gs;
const gridReplaceRegex = /\|grid(\!|\?)*\|([^|]+)\|([^|]+)\|([^|]+)\|([^|]+)\|/g;
const idWithLoopSuffixRegex = /^([a-zA-Z0-9_]+?)(_?\d+_\d+)?$/;
const valueOrDefaultRegex = /valueOrDefault\(["']([a-zA-Z0-9_]+?)(_?\d+_\d+)?["'](.*)\)/g;
const elementIdRegex = /id=([^\s]+)/;
const embeddedHTMLQuestionIDRegex = /id="([^"]+)"/;
const displayIfRegex = /displayif\s*=\s*.*/;
const endMatchRegex = /end\s*=\s*(.*)?/;
export class QuestionProcessor {
constructor(markdown, precalculated_values, i18n) {
this.i18n = i18n; // Language settings
this.buttonTextObj = { // Back/Reset/Next/Submit buttons
back: i18n.backButton,
reset: i18n.resetAnswerButton,
next: i18n.nextButton,
submit: i18n.submitSurveyButton
};
this.precalculated_values = precalculated_values; // Pre-calculated form values (e.g. user name and current date)
this.lastBatchProcessedQuestionIndex = 0; // Track the last batch preprocessed question.
this.loopDataArr = []; // Array of loop data. Responsive to user input.
this.gridQuestionsArr = []; // Array of grid question IDs, used for processing someSelected and noneSelected conditionals.
this.questions = this.splitIntoQuestions(markdown); // Split and prepare questions
this.processedQuestions = new Map(); // Cache of processed form elements
this.currentQuestionIndex = 0; // Track the current question
this.isProcessingComplete = false; // Mark when all questions are processed
}
setQuestName(markdown) {
const questModuleNameRegExp = new RegExp(/{"name":"(\w*)"}/);
markdown.replace(questModuleNameRegExp, (_, moduleID) => {
moduleParams.questName = moduleID;
return "";
});
}
removeMarkdownComments(markdown) {
return markdown.replace(/\/\/.*|\/\*[\s\S]*?\*\//g, '');
}
splitIntoQuestions(markdown) {
const questionsArr = [];
let match;
// Set the questionnaire name
this.setQuestName(markdown);
// Remove comments from the markdown
markdown = this.removeMarkdownComments(markdown);
// TODO: remove (this is a temporary fix for the yob issue)
//replace all instances of RCRTUP_YOB_V1R0 with yob
markdown = markdown.replace(/RCRTUP_YOB_V1R0/g, 'yob');
// Search for items in delayedParameterArray and add 'Loading...' placeholder text so it's parsed correctly
if (Object.keys(moduleParams.asyncQuestionsMap).length > 0) {
Object.keys(moduleParams.asyncQuestionsMap).forEach((key) => {
markdown = markdown.replace(key, `${key} ${moduleParams.i18n.loading}`);
});
};
// Replace grids with placeholders and store grid content for later processing
let gridPlaceholders = [];
const gridButtonDiv = this.getButtonDiv(true)
markdown = markdown.replace(gridReplaceRegex, (...args) => {
const gridContent = parseGrid(...args, gridButtonDiv);
const placeholder = `<<GRID_PLACEHOLDER_${gridPlaceholders.length}>>`;
gridPlaceholders.push(gridContent);
return placeholder;
});
// Future improvement: Consider unrolling after user has input the response that determines number of loops.
// This would lighten the initial load considerably. Would need to handle insertions to the array.
// Would also need to handle removing generated loop eles on back button click and/or change of the trigger response.
// Current loop process unrolls all possible responses to n=loopMax (25).
markdown = unrollLoops(markdown, this.i18n.language);
// Now we have the contents unpacked and the grid placeholders embedded:
// Split it into an array of question objects, handling the grids along the way
// Note: Everything must be parsed in markdown order since some questions have jump targets and others don't.
while ((match = questionSeparatorRegex.exec(markdown)) !== null) {
const questionContent = match[4].trim();
const questionAndGridSegments = questionContent.split(/(<<GRID_PLACEHOLDER_\d+>>)/g).filter(part => part.trim() !== '');
// If length === 1, no grid placeholders were found in the question content
if (questionAndGridSegments.length === 1) {
questionsArr.push({
fullMatch: match[0],
questionID: match[1],
questOpts: match[2] || '',
questArgs: match[3] || '',
questText: questionContent,
formElement: null
});
// Else, handle the question content plus the grid placeholders, which are at the end of the parsed array
} else {
questionAndGridSegments.forEach((arrayItem) => {
const gridPlaceholderMatch = arrayItem.match(/<<GRID_PLACEHOLDER_(\d+)>>/);
if (gridPlaceholderMatch) {
// Get the previously stored grid content
const gridIndex = parseInt(gridPlaceholderMatch[1], 10);
const gridContent = gridPlaceholders[gridIndex].trim();
const match = gridContent.match(embeddedHTMLQuestionIDRegex);
const questionID = match ? match[1] : '';
this.gridQuestionsArr.push(questionID);
// Add the grid to the questions array. The formElement is already processed.
// Also add the grid ID to the gridQuestions array for processing someSelected and noneSelected conditionals.
questionsArr.push({
fullMatch: match[0],
questionID: questionID,
questOpts: null,
questArgs: null,
questText: null,
formElement: gridContent
});
} else {
// Handle regular question content (the grid placeholder has been removed)
questionsArr.push({
fullMatch: match[0],
questionID: match[1],
questOpts: match[2] || '',
questArgs: match[3] || '',
questText: arrayItem.trim(),
formElement: null
});
}
});
}
}
return questionsArr;
}
/**
* Transform the HTML string from the markdown converter into an HTML element.
* Execute legacy DOM manipulation to convert the string into an element.
* @param {string} htmlString - The HTML string to convert.
* @param {boolean} isFirstQuestion - boolean to determine if this is the first question. If true, remove the 'back' button.
* @param {boolean} isLastQuestion - boolean to determine if this is the last question. If true, remove the 'next' button.
* @param {number} index - The index of the question in the this.questions array.
* @returns {HTMLElement} - The HTML question element (a form with response options).
*/
convertHTMLStringToEle(htmlString, isFirstQuestion, isLastQuestion, index) {
const template = document.createElement('template');
template.innerHTML = htmlString.trim();
const newQuestionEle = template.content.firstChild;
// Add the loop data to the loopDataArr to support the exitLoop function.
if (newQuestionEle.hasAttribute("loopmax") && newQuestionEle.hasAttribute("firstquestion") && newQuestionEle.getAttribute("firstquestion") == '1') {
const appState = getStateManager();
const loopMaxID = newQuestionEle.getAttribute("loopmax");
const loopMaxResponse = parseInt(appState.findResponseValue(loopMaxID), 10);
const questionIDMatch = newQuestionEle.id.match(idWithLoopSuffixRegex);
const loopFirstQuestionID = questionIDMatch?.[1] || '';
this.loopDataArr.push({
locationIndex: index, // Position in the questions array
loopMax: 25, // Default max response iterations: 25
loopMaxQuestionID: loopMaxID, // The questionID that determines the number of iterations
loopMaxResponse: loopMaxResponse, // The user's response to the loopMax question
loopFirstQuestionID: loopFirstQuestionID, // The first questionID marker (first question in in the loop)
});
}
// The rest of this function is legacy DOM manipulation. Caution on refactoring.
// handle data-hidden elements
[...newQuestionEle.querySelectorAll("[data-hidden]")].forEach((x) => {
x.style.display = "none";
});
// validate confirm. If the confirm was used instead of data-confirm, fix it now
[...newQuestionEle.querySelectorAll("[confirm]")].forEach((element) => {
element.dataset.confirm = element.getAttribute("confirm")
element.removeAttribute("confirm")
});
[...newQuestionEle.querySelectorAll("[data-confirm]")].forEach((element) => {
console.warn('TODO: REMOVE? NOT FOUND in DOM (this previously used document access): confirm element found:', element.dataset.confirm);
if (!newQuestionEle.querySelector(`#${element.dataset.confirm}`)) {
delete element.dataset.confirm
}
const otherElement = newQuestionEle.querySelector(`#${element.dataset.confirm}`);
console.warn('TODO: REMOVE? NOT FOUND in DOM (this previously used document access): confirm element found (otherElement):', otherElement);
otherElement.dataset.confirmationFor = element.id;
});
// enable all popovers...
[...newQuestionEle.querySelectorAll('[data-bs-toggle="popover"]')].forEach(popoverTriggerEl => {
new bootstrap.Popover(popoverTriggerEl);
});
// remove the first 'previous' button and the final 'next' button.
if (isFirstQuestion) {
newQuestionEle.querySelector(".previous").remove();
}
if (isLastQuestion) {
newQuestionEle.querySelector(".next").remove();
}
return newQuestionEle;
}
/**
* Manage the currentQuestionIndex value, which acts as a pointer for question navigation.
* @param {string} updateType
* @param {number|null} value - optional,
*/
setCurrentQuestionIndex(updateType, value) {
if (typeof updateType !== 'string') {
moduleParams.errorLogger('Error (setCurrentQuestionIndex). updateType must be a string')
}
switch(updateType) {
case 'increment':
this.currentQuestionIndex++;
break;
case 'decrement':
this.currentQuestionIndex--;
break;
case 'update':
if (typeof value !== 'number') {
moduleParams.errorLogger('Error (setCurrentQuestionIndex). value must be a number for update operations.')
}
this.currentQuestionIndex = value;
break;
default:
moduleParams.errorLogger('Error (setCurrentQuestionIndex): unhandled updateType', updateType, value);
}
}
/**
* Find a question by questionID from the this.questions array.
* @param {string || undefined} questionID - The questionID to find.
* @returns {object} - { question: The HTML element of the found question, index: the index of the found question }
*/
findQuestion(questionID) {
if (!questionID) {
moduleParams.errorLogger('Error, findQuestion (no questionID provided):', questionID);
}
let index;
if (questionID.startsWith('_CONTINUE')) {
return this.findStartOfNextLoopIteration(questionID);
} else if (questionID === 'END') {
index = this.questions.length - 1;
} else {
index = this.questions.findIndex(question => question.questionID.startsWith(questionID));
}
if (index !== -1) {
const foundQuestion = this.processQuestion(index);
if (!foundQuestion) {
moduleParams.errorLogger('Error: (findQuestion): question not found at index', index)
}
return { question: foundQuestion, index: index };
}
moduleParams.errorLogger(`Error, findQuestion (question not found): ${moduleParams.questName}, question: ${questionID}`);
return { question: null, index: -1 };
}
/**
* Load the initial question when a user starts or returns to a survey.
* Find the question, set the currentQuestionIndex, and manage the active question class.
* @param {string} questionID - The questionID to load.
* @returns {HTMLElement} - The HTML element of the loaded question.
*/
loadInitialQuestionOnStartup(questionID) {
if (this.questions.length === 0) {
moduleParams.errorLogger('Error during initialization (loadInitialQuestion): no questions found', this.questions);
return null;
}
const { question, index } = this.findQuestion(questionID);
if (!question) {
moduleParams.errorLogger('Error during initialization (loadInitialQuestion): question not found', questionID);
return null;
}
this.setCurrentQuestionIndex('update', index);
return this.manageActiveQuestionClass(question, null);
}
/**
* Get the next sequential questionID from the this.questions array.
* Used whenever a response doesn't have an associated jump target.
* Check the currentQuestionIndex, increment it, and return the next questionID.
* @returns {string} - The ID of the next question to load.
*/
getNextSequentialQuestionID() {
if (this.currentQuestionIndex + 1 < this.questions.length) {
this.setCurrentQuestionIndex('increment')
const nextQuestion = this.processQuestion(this.currentQuestionIndex);
return nextQuestion.id;
}
moduleParams.errorLogger(`Error, getNextSequentialQuestion (no next question to load): ${moduleParams.questName}, index: ${this.currentQuestionIndex}`);
return null;
}
/**
* Load the previous question. Note: this is not necessarily the previous array index due to jumps and loops.
* Find the previous question, set the currentQuestionIndex, and manage the active question class.
* @param {string} previousQuestionID - The questionID to load.
* @returns {HTMLElement} - The HTML element of the loaded question.
*/
loadPreviousQuestion(previousQuestionID) {
if (this.currentQuestionIndex <= 0) {
moduleParams.errorLogger(`Error, loadPreviousQuestion (Unhandled case: no previous question to load): ${moduleParams.questName}, question: ${previousQuestionID}`);
return null;
}
const questionToUnload = this.getCurrentQuestion();
const { question, index } = this.findQuestion(previousQuestionID);
this.setCurrentQuestionIndex('update', index);
this.manageActiveQuestionClass(question, questionToUnload);
return question;
}
/**
* Load the next question in the survey. Note: this is not necessarily the next array index due to jumps and loops.
* Find the next question, set the currentQuestionIndex, and manage the active question class.
* @param {string} questionID - The questionID to load.
* @returns {HTMLElement} - The HTML element of the loaded question.
*/
loadNextQuestion(questionID) {
if (this.currentQuestionIndex + 1 > this.questions.length) {
moduleParams.errorLogger(`Error, loadNextQuestion (unhandled case: at end of survey): ${moduleParams.questName}, question: ${questionID}, index: ${this.currentQuestionIndex}, length: ${this.questions.length}`);
return null;
}
const questionToUnload = this.getCurrentQuestion();
const { question, index } = this.findQuestion(questionID);
this.setCurrentQuestionIndex('update', index);
this.manageActiveQuestionClass(question, questionToUnload);
return question;
}
/**
* Get the current question from the this.questions array.
* Useful for managing the active question class on 'next' and 'back' button clicks, and for processing the current question.
* @returns {HTMLElement} - The HTML element of the current question.
*/
getCurrentQuestion() {
if (this.currentQuestionIndex > this.questions.length || this.currentQuestionIndex < 0) {
moduleParams.errorLogger(`Error, getCurrentQuestion (index out of range): ${moduleParams.questName}, index: ${this.currentQuestionIndex}`);
return null;
}
return this.processQuestion(this.currentQuestionIndex);
}
getAllProcessedQuestions() {
return this.processedQuestions;
}
/**
* Process a single question's markdown, add it to the cache, and return the HTML element.
* First, search the cache for the question. If found, it has already been processed. Return early.
* Note about the questions array:
* - Grid questions are pre-parsed as HTML strings, directly to the .formElement property in the quesitons array.
* - All other questions are processed as a regex match with ID, opts, args, and text properties (raw text).
* - So, grid questions only have one step here, while all other questions have two steps.
* @param {number} index - The index of the question to process from the this.questions array.
* @returns {HTMLElement} - The HTML element of the processed question.
*/
processQuestion(index) {
if (index < 0) return null;
if (this.processedQuestions.has(index)) {
return this.processedQuestions.get(index);
}
const questionObj = this.questions[index];
const isFirstQuestion = index === 0;
const isLastQuestion = index === this.questions.length - 1;
let questionElement;
if (questionObj.formElement) {
questionElement = this.convertHTMLStringToEle(questionObj.formElement, isFirstQuestion, isLastQuestion, index);
} else {
const processedHTMLString = this.convertToHTMLString(questionObj);
questionElement = this.convertHTMLStringToEle(processedHTMLString, isFirstQuestion, isLastQuestion, index);
}
this.processedQuestions.set(index, questionElement);
return questionElement;
}
/**
* Process all questions in the survey. This is a batch process that can be used to pre-process all questions.
* It runs in two instances:
* (1) on survey startup (or return to survey), it preprocesses batches of the survey, and
* (2) when the user returns to the survey mid-loop, it preprocesses all questions up to the current question to obtain the loop data for navigation.
* Questions take ~1-2ms to process depending on complexity and device, so small batches don't impact performance significantly.
* @param {number} startIndex - The index of the first question to process.
* @param {number} stopIndex - The index of the last question to process.
* @returns {void} - The processed questions are added to the cache.
*/
processAllQuestions(startIndex = 0, stopIndex = this.questions.length) {
if (this.isProcessingComplete) return;
const startingPoint = Math.max(this.lastBatchProcessedQuestionIndex, startIndex, 0);
const stoppingPoint = Math.min(stopIndex, this.questions.length);
for (let i = startingPoint; i < stoppingPoint; i++) {
this.processQuestion(i);
}
if (stoppingPoint === this.questions.length) {
this.isProcessingComplete = true;
}
this.lastBatchProcessedQuestionIndex = stoppingPoint;
}
/**
* Manage the question with the .active class attached. This is used for question visibility (legacy).
* @param {HTMLElement} questionToLoad - The question to load.
* @param {HTMLElement} questionToUnload - The question to unload.
* @returns {HTMLElement} - The question to load with the .active class appended.
*/
manageActiveQuestionClass(questionToLoad, questionToUnload) {
if (!questionToLoad) {
moduleParams.errorLogger('Error, manageActiveQuestionClass (no question to load):', questionToLoad, questionToUnload);
return null;
}
if (questionToUnload) {
questionToUnload.classList.remove('active');
}
questionToLoad.classList.add('active');
return questionToLoad;
}
/**
* Handle 'someSelected' and 'noneSelected' conditionals for grid questions.
* Search the grid questions for the elementID (the specific radio or checkbox input element).
* Return the value of the input element for comparison to the user's input.
* @param {string} elementID - The ID of the radio or checkbox input element to find.
* @returns {string} - The value of the input element, or null if not found.
*/
findGridRadioCheckboxEle(elementID) {
for (const questionID of this.gridQuestionsArr) {
const { question } = this.findQuestion(questionID);
if (question) {
const radioOrCheckbox = question.querySelector(`#${elementID}`);
if (radioOrCheckbox) {
return radioOrCheckbox?.value || null;
}
}
}
moduleParams.errorLogger(`Error, findGridInputElement (element not found): ${moduleParams.questName}, elementID: ${elementID}`);
return null;
}
/**
* Find the closest loop data prior to the current question index.
* If not found, user may be returning to the survey mid-loop. Process all questions up to the current index,
* which will populate the loopDataArr with the correct loop data. Then try again.
* @returns {object} - The loop data object for the current loop. { locationIndex, loopMax, loopMaxQuestionID, loopMaxResponse, loopFirstQuestionID }
*/
getLoopData() {
const findNearestLoopIndex = () => {
let nearestLocationIndex = -1;
for (const loopData of this.loopDataArr) {
if (loopData.locationIndex <= this.currentQuestionIndex) {
if (loopData.locationIndex > nearestLocationIndex) {
nearestLocationIndex = loopData.locationIndex;
}
}
}
return nearestLocationIndex;
}
let loopStartLocationIndex = findNearestLoopIndex();
if (loopStartLocationIndex === -1) {
this.processAllQuestions(0, this.currentQuestionIndex);
loopStartLocationIndex = findNearestLoopIndex();
}
// Find the loop data object where locationIndex matches the loopStartLocationIndex
const loopData = this.loopDataArr.find(data => data.locationIndex === loopStartLocationIndex);
// Return the matching object or fallback
return loopData || this.loopDataArr[this.loopDataArr.length - 1] || null;
}
/**
* If the loopMaxResponse changes, update the loopDataArr with the new value.
* This is a rare case where a user changes their response to a loopMax question.
* Find the loopData object that matches the loopMaxQuestionID and update the loopMaxResponse.
* This a is relatively inexpesive (but necessary) check because loopDataArr is small (length === number of loops in the survey).
* Process:
* - Check whether the questionID is a loopMax question.
* - In the typical case: a response is NOT associate with a loopMax value. Return early.
* - If the loopMax questionID is a match, update the loopData object with the new response.
* @param {string} questionID - The questionID to check. Only questionIDs that determine the number of loop iterations result in further processing.
* @param {string} response - The user's response to the loopMax question.
* @returns {void} - The loopDataArr is up-to-date with new response values for future loop execution.
*/
checkLoopMaxData(questionID, response) {
// Some questions are prompt-only (no responses). Return early.
if (!questionID || !response) return;
// If no match found, return early, continue normal survey operation. This is the typical case.
const questionIDMatch = this.loopDataArr.find(loopData => loopData.loopMaxQuestionID === questionID);
if (!questionIDMatch) return;
// If the loopMax questionID is found, update the loopData object with the new response.
const loopDataIndex = this.loopDataArr.findIndex(loopData => loopData.loopMaxQuestionID === questionID);
if (loopDataIndex === -1) {
moduleParams.errorLogger(`Error, checkLoopMaxData (loopData not found): ${moduleParams.questName}, loopMaxQuestionID: ${questionID}`);
return;
}
// update the loopData object with the new response
const updatedLoopMaxResponse = parseInt(response, 10);
if (isNaN(updatedLoopMaxResponse)) {
moduleParams.errorLogger(`Error, checkLoopMaxData (invalid response): ${moduleParams.questName}, response: ${response}`);
return;
}
this.loopDataArr[loopDataIndex].loopMaxResponse = updatedLoopMaxResponse;
}
/**
* Find the loop's jump target based on survey conditionals, which is either:
* (1) The beginning of the next loop iteration, or
* (2) The end of the loop sequence.
* @param {string} questionID - The questionID to find the next iteration of the loop.
* @returns {object} - { question: The found jump target in HTML element format, prepared for DOM insertion, index: the quesiton's index }
*/
findStartOfNextLoopIteration(questionID) {
const loopIndexRegex = /_(\d+)_(\d+)$/;
const loopIndexMatch = questionID.match(loopIndexRegex);
if (!loopIndexMatch && loopIndexMatch[1] && loopIndexMatch[2]) {
moduleParams.errorLogger(`Error, findQuestion (loop index not found): ${moduleParams.questName}, question: ${questionID}`);
return null;
}
const loopIterationIndex = loopIndexMatch[1];
const nextLoopIterationIndex = parseInt(loopIterationIndex, 10) + 1;
const loopData = this.getLoopData();
if (!loopData) {
moduleParams.errorLogger(`Error, findQuestion (loop data not found): ${moduleParams.questName}, question: ${questionID}`);
return null;
}
// If the next index is greater than the loopMaxResponse (or loopMax as a fallback), exit the loop.
if (nextLoopIterationIndex > loopData.loopMaxResponse || nextLoopIterationIndex > loopData.loopMax) {
return this.findEndOfLoop();
// Else, find the first question for the next loop iteration.
} else {
const nextIterationFirstQuestionID = `${loopData.loopFirstQuestionID}_${nextLoopIterationIndex}_${nextLoopIterationIndex}`;
return this.findQuestion(nextIterationFirstQuestionID);
}
}
/**
* Find the end of the loop sequence. This is a placeholder questionID 'END_OF_LOOP' that marks the end of the loop as a jump target.
* @returns {object} - { question: The found jump target in HTML element format, prepared for DOM insertion, index: the quesiton's index }
*/
findEndOfLoop() {
const endOfLoopIndex = this.questions.findIndex((question, index) => {
return question.questionID === 'END_OF_LOOP' && index > this.currentQuestionIndex;
});
if (endOfLoopIndex === -1) {
moduleParams.errorLogger(`Error, findEndOfLoop (no end of loop found): ${moduleParams.questName}, index: ${this.currentQuestionIndex}`);
return { question: null, index: -1 }
}
// End of loop found. This element is a placeholder, so increment to access the first question after the loop.
return { question: this.processQuestion(endOfLoopIndex + 1), index: endOfLoopIndex + 1 };
}
/**
* For some input elements, the input ID and the form ID are different.
* This is a legacy case, where we need to continue supporting existing surveys.
* Process: Search questions for the elementID. If found, return the parent formID.
* This supports 'forid' replacement and displayif conditionals.
* @param {string} elementID - The ID of the input element to find.
* @returns {string} - The ID of the input element's form, required for evaluating some conditionals, or null if not found.
*/
findRelatedFormID(elementID) {
for (const questionInList of this.questions) {
const questionID = questionInList.questionID;
const { question } = this.findQuestion(questionID);
if (question) {
const foundElement = question.querySelector(`#${elementID}`);
if (foundElement) {
return question.id;
}
}
}
moduleParams.errorLogger(`Error, findRelatedFormID (formID not found): ${moduleParams.questName}, elementID: ${elementID}`);
return null;
}
replaceDateTags(content) {
const replacements = [
[/#currentMonthStr/g, this.i18n.months[this.precalculated_values.current_month_str]],
[/#currentMonth/g, this.precalculated_values.current_month],
[/#currentYear/g, this.precalculated_values.current_year],
[/#today(\s*[+-]\s*\d+)?/g, this.replaceTodayTag.bind(this)],
];
replacements.forEach(([regex, replacement]) => {
content = content.replace(regex, replacement);
});
return content;
}
convertToHTMLString(question, i18n = this.i18n, precalculated_values = this.precalculated_values) {
let { questionID, questOpts, questArgs, questText } = question;
questText = this.replaceDateTags(questText);
questText = questText
.replaceAll("\u001f", "\n")
.replace(/(?:\r\n|\r|\n)/g, "<br>")
.replace(/\[_#\]/g, "");
let counter = 1;
questText = questText.replace(/\[\]/g, function () {
let t = "[" + counter.toString() + "]";
counter = counter + 1;
return t;
});
//handle options for question
questOpts = questOpts || '';
if (questOpts) {
questOpts = questOpts.replaceAll(/(min|max)-count\s*=\s*(\d+)/g,'data-$1-count=$2')
}
// handle displayif on the question. If questArgs is undefined set it to blank.
questArgs = questArgs || '';
let endMatch;
if (questArgs) {
const displayifMatch = questArgs.match(displayIfRegex);
endMatch = questArgs.match(endMatchRegex);
// if so, remove the comma and go. if not, set questArgs to blank...
if (displayifMatch) {
questArgs = displayifMatch[0];
questArgs = `displayif=${encodeURIComponent(displayifMatch[0].slice(displayifMatch[0].indexOf('=') + 1))}`
} else if (endMatch) {
questArgs = endMatch[0];
} else {
questArgs = "";
}
}
let target = "";
let hardBool = questionID.endsWith("!");
let softBool = questionID.endsWith("?");
if (hardBool || softBool) {
questionID = questionID.slice(0, -1);
if (hardBool) {
target = "data-bs-target='#hardModal'";
} else {
target = "data-bs-target='#softModal'";
}
}
// Worker doesn't have window context/access, so needed to be pre-calculated instead of accessing math._value.
// replace user profile variables...
questText = questText.replace(/\{\$u:(\w+)}/g, (all, varid) => {
return `<span name='${varid}'>${precalculated_values[varid] || ''}</span>`;
});
// replace {$id} with span tag
questText = questText.replace(/\{\$(\w+(?:\.\w+)?):?([a-zA-Z0-9 ,.!?"-]*)\}/g, fID);
function fID(fullmatch, forId, optional) {
if (optional == null || optional === "") {
optional = "";
} else {
optional = `optional='${encodeURIComponent(optional)}'`;
}
return `<span forId='${forId}' ${optional}>${forId}</span>`;
}
// replace {#id} with span tag
questText=questText.replace(/\{\#([^}#]+)\}/g,fHash)
function fHash(fullmatch,expr){
return `<span data-encoded-expression=${encodeURIComponent(expr)}>${expr}</span>`
}
//adding displayif with nested questions. nested display if uses !| to |!
questText = questText.replace(/!\|(displayif=.+?)\|(.*?)\|!/g, fDisplayIf);
function fDisplayIf(containsGroup, condition, text) {
text = text.replace(/\|(?:__\|){2,}(?:([^|<]+[^|]+)\|)?/g, fNum);
text = text.replace(/\|popup\|([^|]+)\|(?:([^|]+)\|)?([^|]+)\|/g, fPopover);
text = text.replace(/\|@\|(?:([^|<]+[^|]+)\|)?/g, fEmail);
text = text.replace(/\|date\|(?:([^|<]+[^|]+)\|)?/g, fDate);
text = text.replace(/\|tel\|(?:([^|<]+[^|]+)\|)?/g, fPhone);
text = text.replace(/\|SSN\|(?:([^|<]+[^|]+)\|)?/g, fSSN);
text = text.replace(/\|state\|(?:([^|<]+[^|]+)\|)?/g, fState);
text = text.replace(/\[(\d*)(\*)?(?::(\w+))?(?:\|(\w+))?(?:,(displayif=.+?\))?)?\]\s*(.*?)\s*(?=(?:\[\d)|\n|<br>|$)/g, fCheck);
text = text.replace(/\[text\s?box(?:\s*:\s*(\w+))?\]/g, fTextBox);
text = text.replace(/\|(?:__\|)(?:([^\s<][^|<]+[^\s<])\|)?\s*(.*?)/g, fText);
text = text.replace(/\|___\|((\w+)\|)?/g, fTextArea);
text = text.replace(/\|time\|(?:([^|<]+[^|]+)\|)?/g, fTime);
text = text.replace(/#YNP/g, translate('yesNoPrefer'));
text = questText.replace(/#YN/g, translate('yesNo'));
return `<span class='displayif' ${condition}>${text}</span>`;
}
//replace |popup|buttonText|Title|text| with a popover
questText = questText.replace(
/\|popup\|([^|]+)\|(?:([^|]+)\|)?([^|]+)\|/g, fPopover);
function fPopover(fullmatch, buttonText, title, popText) {
title = title ? title : "";
popText = popText.replace(/"/g, """)
return `<a tabindex="0" class="popover-dismiss btn" role="button" title="${title}" data-toggle="popover" data-bs-toggle="popover" data-trigger="focus" data-bs-trigger="focus" data-content="${popText}" data-bs-content="${popText}">${buttonText}</a>`;
}
// replace |hidden|value|
questText = questText.replace(/\|hidden\|\s*id\s*=\s*([^\|]+)\|?/g, fHide);
function fHide(fullmatch, id) {
return `<input type="text" data-hidden=true id=${id}>`
}
// replace |@| with an email input
questText = questText.replace(/\|@\|(?:([^\|\<]+[^\|]+)\|)?/g, fEmail);
function fEmail(fullmatch, opts) {
const { options } = guaranteeIdSet(opts, "email");
return `<input type='email' ${options} placeholder="[email protected]"></input>`;
}
// replace |date| with a date input
questText = questText.replace(/\|date\|(?:([^\|\<]+[^\|]+)\|)?/g, fDate);
questText = questText.replace(/\|month\|(?:([^\|]+)\|)?/g, fMonth);
function fDate(fullmatch, opts) {
let type = fullmatch.match(/[^|]+/);
let { options, elementId } = guaranteeIdSet(opts, type);
let optionObj = paramSplit(options);
// can't have the value uri encoded...
if (Object.prototype.hasOwnProperty.call(optionObj, "value")) {
optionObj.value = decodeURIComponent(optionObj.value);
}
options = reduceObj(optionObj);
if (Object.prototype.hasOwnProperty.call(optionObj, "min")) {
options = options + ` data-min-date-uneval=${optionObj.min}`
}
if (Object.prototype.hasOwnProperty.call(optionObj, "max")) {
options = options + ` data-max-date-uneval=${optionObj.max}`
}
const descText = type === 'month' ? "Type month and four-digit year" : type === 'date' ? "Select a date" : "Enter the month and year in format: four digit year - two digit month. YYYY-MM";
// Adding placeholders and aria-describedby attributes in one line
options += ` placeholder='Select ${type}' aria-describedby='${elementId}-desc' aria-label='Select ${type}'`;
return `<input type='${type}' ${options}><span id='${elementId}-desc' class='visually-hidden'>${descText}</span>`;
}
function fMonth(fullmatch, opts) {
const type = fullmatch.match(/[^|]+/);
const { options, elementId } = guaranteeIdSet(opts, type);
const questionIDPrefix = questionID.match(idWithLoopSuffixRegex)[1];
const updatedOptions = options.replace(valueOrDefaultRegex, (_, prefix, suffix, rest) => {
return `valueOrDefault("${questionIDPrefix}${suffix}"${rest})`;
});
const optionObj = paramSplit(updatedOptions);
if (Object.prototype.hasOwnProperty.call(optionObj, "value")) {
optionObj.value = decodeURIComponent(optionObj.value);
}
const unevaluatedDates = [];
if (Object.prototype.hasOwnProperty.call(optionObj, "min")) {
unevaluatedDates.push(`data-min-date-uneval=${optionObj.min}`);
}
if (Object.prototype.hasOwnProperty.call(optionObj, "max")) {
unevaluatedDates.push(`data-max-date-uneval=${optionObj.max}`);
}
const descText = "Enter the month and year in format: four digit year - two digit month. YYYY-MM";
const finalOptions = `${updatedOptions} ${unevaluatedDates.join(' ')} placeholder='Select month' aria-describedby='${elementId}-desc' aria-label='Select month'`;
return `<input type='${type}' ${finalOptions}><span id='${elementId}-desc' class='visually-hidden'>${descText}</span>`;
}
// replace |tel| with phone input
questText = questText.replace(/\|tel\|(?:([^\|\<]+[^\|]+)\|)?/g, fPhone);
function fPhone(fullmatch, opts) {
const { options } = guaranteeIdSet(opts, "tel");
return `<input type='tel' ${options} pattern="[0-9]{3}-?[0-9]{3}-?[0-9]{4}" maxlength="12" placeholder='###-###-####'></input>`;
}
// replace |SSN| with SSN input
questText = questText.replace(/\|SSN\|(?:([^\|\<]+[^\|]+)\|)?/g, fSSN);
function fSSN(fullmatch, opts) {
const { options } = guaranteeIdSet(opts, "SSN");
return `<input type='text' ${options} id="SSN" class="SSN" inputmode="numeric" maxlength="11" pattern="[0-9]{3}-?[0-9]{2}-?[0-9]{4}" placeholder="_ _ _-_ _-_ _ _ _"></input>`;
}
// replace |SSNsm| with SSN input
questText = questText.replace(/\|SSNsm\|(?:([^\|\<]+[^\|]+)\|)?/g, fSSNsm);
function fSSNsm(fullmatch, opts) {
const { options } = guaranteeIdSet(opts, "SSNsm");
return `<input type='text' ${options} class="SSNsm" inputmode="numeric" maxlength="4" pattern='[0-9]{4}'placeholder="_ _ _ _"></input>`;
}
// replace |zip| with text input
questText = questText.replace(/\|zip\|(?:([^\|\<]+[^\|]+)\|)?/g, fzip);
function fzip(fullmatch, opts) {
const { options, elementId } = guaranteeIdSet(opts, "zip");
return `<input type='text' ${options} id=${elementId} class="zipcode" pattern="^[0-9]{5}(?:-[0-9]{4})?$" placeholder="_ _ _ _ _"></input>`;
}
// replace |state| with state dropdown
questText = questText.replace(/\|state\|(?:([^\|\<]+[^\|]+)\|)?/g, fState);
function fState(fullmatch, opts) {
const { options } = guaranteeIdSet(opts, "state");
return `<select ${options}>
<option value='' disabled selected>${i18n.chooseState}: </option>
<option value='AL'>Alabama</option>
<option value='AK'>Alaska</option>
<option value='AZ'>Arizona</option>
<option value='AR'>Arkansas</option>
<option value='CA'>California</option>
<option value='CO'>Colorado</option>
<option value='CT'>Connecticut</option>
<option value='DE'>Delaware</option>
<option value='DC'>District Of Columbia</option>
<option value='FL'>Florida</option>
<option value='GA'>Georgia</option>
<option value='HI'>Hawaii</option>
<option value='ID'>Idaho</option>
<option value='IL'>Illinois</option>
<option value='IN'>Indiana</option>
<option value='IA'>Iowa</option>
<option value='KS'>Kansas</option>
<option value='KY'>Kentucky</option>
<option value='LA'>Louisiana</option>
<option value='ME'>Maine</option>
<option value='MD'>Maryland</option>
<option value='MA'>Massachusetts</option>
<option value='MI'>Michigan</option>
<option value='MN'>Minnesota</option>
<option value='MS'>Mississippi</option>
<option value='MO'>Missouri</option>
<option value='MT'>Montana</option>
<option value='NE'>Nebraska</option>
<option value='NV'>Nevada</option>
<option value='NH'>New Hampshire</option>
<option value='NJ'>New Jersey</option>
<option value='NM'>New Mexico</option>
<option value='NY'>New York</option>
<option value='NC'>North Carolina</option>
<option value='ND'>North Dakota</option>
<option value='OH'>Ohio</option>
<option value='OK'>Oklahoma</option>
<option value='OR'>Oregon</option>
<option value='PA'>Pennsylvania</option>
<option value='RI'>Rhode Island</option>
<option value='SC'>South Carolina</option>
<option value='SD'>South Dakota</option>
<option value='TN'>Tennessee</option>
<option value='TX'>Texas</option>
<option value='UT'>Utah</option>
<option value='VT'>Vermont</option>
<option value='VA'>Virginia</option>
<option value='WA'>Washington</option>
<option value='WV'>West Virginia</option>
<option value='WI'>Wisconsin</option>
<option value='WY'>Wyoming</option>
</select>`;
}
function guaranteeIdSet(options = "", inputType = "inp") {
if (options) {
options = options.trim();
}
let elementId = options.match(elementIdRegex);
if (!elementId) {
elementId = `${questionID}_${inputType}`;
options = `${options} id=${elementId}`;
} else {
elementId = elementId[1];
}
return { options: options, elementId: elementId };
}
// replace |image|URL|height,width| with a html img tag...
questText = questText.replace(
/\|image\|(.*?)\|(?:([0-9]+),([0-9]+)\|)?/g,
"<img src=https://$1 height=$2 width=$3 loading='lazy'>"
);
//regex to test if there are input as a part of radio or checkboxes
//let radioCheckboxAndInput = false;
if (questText.match(/(\[|\()(\d*)(?:\:(\w+))?(?:\|(\w+))?(?:,(displayif=.+?\))?)?(\)|\])\s*(.*?\|_.*?\|)/g)) {
//radioCheckboxAndInput = true;
questOpts = questOpts + " radioCheckboxAndInput";
}
questText = questText.replace(/<br>/g, "<br>\n");
// replace (XX) with a radio button...
// buttons can have a displayif that contains recursive
// parentheses. Regex in JS currently does not support
// recursive pattern matching. So, I look for the start
// of the radio button, a left parenthesis, with a digit
// along with other optional arguments. the handleButton
// function returns the entire string that gets matched,
// similar to string.replace
function handleButton(match) {
let value = match[1];
let radioElementName = match[2] ? match[2] : questionID;
let labelID = match[3] ? match[3] : `${radioElementName}_${value}_label`;
// finds real end
let cnt = 0;
let end = 0;
for (let i = match.index; i < match.input.length; i++) {
if (match.input[i] == "(") cnt++;
if (match.input[i] == ")") cnt--;
if (match.input[i] == "\n") break;
end = i + 1;
if (cnt == 0) break;
}
// need to have the displayif=... in the variable display_if otherwise if
// you have displayif={displayif} displayif will be false if empty.
let radioButtonMetaData = match.input.substring(match.index, end);
let display_if = match[4] ? radioButtonMetaData.substring(radioButtonMetaData.indexOf(match[4]), radioButtonMetaData.length - 1).trim() : "";
display_if = (display_if) ? `displayif=${encodeURIComponent(display_if)}` : ""
let label_end = match.input.substring(end).search(/\n|(?:<br>|$)/) + end;
let label = match.input.substring(end, label_end);
let replacement = `<div class='response' ${display_if}><input type='radio' name='${radioElementName}' value='${value}' id='${radioElementName}_${value}'></input><label id='${labelID}' for='${radioElementName}_${value}'>${label}</label></div>`;
return match.input.substring(0, match.index) + replacement + match.input.substring(label_end);
}
/*