-
Notifications
You must be signed in to change notification settings - Fork 16
/
GIFT.pegjs
370 lines (311 loc) · 11.4 KB
/
GIFT.pegjs
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
// All these helper functions are available inside of actions
{
var questionId = null;
var questionTags = null;
var defaultFormat = "moodle"; // default format - the GIFT specs say [moodle] is default, but not sure what that means for other applications
var format = defaultFormat;
const escapedCharacters = {
"\\\\" : "&&092;",
"\\:" : "&&058;",
"\\#" : "&&035;",
"\\=" : "&&061;",
"\\{" : "&&123;",
"\\}" : "&&125;",
"\\~" : "&&126;",
"\\n" : "&&010"
};
function escapedCharacterDecode(text) {
// Replace escaped characters with their original values, except for the newline character which should return a real (not escaped newline)
return text.replace(/&&092;/g, '\\')
.replace(/&&058;/g, ':')
.replace(/&&035;/g, '#')
.replace(/&&061;/g, '=')
.replace(/&&123;/g, '{')
.replace(/&&125;/g, '}')
.replace(/&&126;/g, '~')
.replace(/&&010/g, '\n');
}
function processAnswers(question, answers) {
question.globalFeedback = answers.globalFeedback;
switch(question.type) {
case "TF":
question.isTrue = answers.isTrue;
question.incorrectFeedback = answers.feedback[1];
question.correctFeedback = answers.feedback[2];
break;
case "MC":
case "Numerical":
case "Short":
question.choices = answers.choices;
break;
case "Matching":
question.matchPairs = answers.matchPairs;
break;
}
// check for MC that's actually a short answer (all correct answers)
if (question.type == "MC" && areAllCorrect(question.choices)) {
question.type = "Short";
}
question.id = questionId;
question.tags = questionTags;
return question;
}
function areAllCorrect(choices) {
var allAreCorrect = true;
for (var i = 0; i < choices.length; i++) {
allAreCorrect &= choices[i].isCorrect;
}
return allAreCorrect;
}
function removeNewLinesDuplicateSpaces(text) {
text = text.replace(/[\n\r]/g,' '); // replace newlines with spaces
return text.replace(/\s\s+/g,' ');
}
function setLastQuestionTextFormat(fmt) {
format = fmt;
}
function getLastQuestionTextFormat() {
return format;
}
function resetLastQuestionTextFormat() {
format = defaultFormat;
}
function formattedText(format, txt) {
let inferredFormat = (format !== null ? format : getLastQuestionTextFormat());
let joinedText = txt.join('')
.replace(/\r\n/g, '\n') // replace Windows newlines with Unix newlines
.trim();
return {
format:(inferredFormat),
text:(
((inferredFormat == "html") || (inferredFormat == "markdown")) ?
// keep whitespace and newlines for html and markdown
escapedCharacterDecode(joinedText) :
escapedCharacterDecode(removeNewLinesDuplicateSpaces(joinedText))
)}
}
}
GIFTQuestions
= questions:(Category / Description / Question)+ _ __ { return questions; }
Category "Category"
= ResetIdsTags __ '$' 'CATEGORY:' _ cat:CategoryText QuestionSeparator {return {type:"Category", title:cat}}
Description "Description"
= ResetIdsTags __
TagComment*
title:QuestionTitle? _
text:QuestionStem
QuestionSeparator
{ var question = {id: questionId, tags: questionTags, type:"Description", title:title, stem:text, hasEmbeddedAnswers:false};
resetLastQuestionTextFormat();
questionId = null; questionTags = null;
return question }
Question
= ResetIdsTags __
TagComment*
title:QuestionTitle? _
stem1:QuestionStem? _
'{' _
answers:(MatchingAnswers / TrueFalseAnswer / MCAnswers / NumericalAnswerType / SingleCorrectShortAnswer / EssayAnswer ) _
'}' _
stem2:(
Comment /
QuestionStem)?
QuestionSeparator
{
var embedded = (stem2 !== null);
var stem1Text = stem1 ? (stem1.text + (embedded ? " " : "")) : "";
var format = (stem1 && stem1.format) || (stem2 && stem2.format) || "moodle";
var text = stem1Text + ( embedded ? "_____ " + stem2.text : "");
var question = {type:answers.type, title:title, stem: {format: format, text: text}, hasEmbeddedAnswers:embedded};
question = processAnswers(question, answers);
resetLastQuestionTextFormat();
return question;
}
MatchingAnswers "{= match1 -> Match1\n...}"
= matchPairs:Matches _ globalFeedback:GlobalFeedback? _
{ return { type: "Matching", matchPairs:matchPairs, globalFeedback:globalFeedback }; }
Matches "matches"
= matchPairs:(Match)+ { return matchPairs }
Match "match"
= _ '=' _ left:MatchRichText? _ '->' _ right:PlainText _
{ var matchPair = {
subquestion:{
format:(left !== null ? left.format : getLastQuestionTextFormat()),
text:(left !== null ? left.text : "")
},
subanswer:right};
return matchPair }
///////////
TrueFalseAnswer "{T} or {F} or {TRUE} or {FALSE}"
= isTrue:TrueOrFalseType _
feedback:(_ Feedback? Feedback?) _
globalFeedback:GlobalFeedback?
{ return { type:"TF", isTrue: isTrue, feedback:feedback, globalFeedback:globalFeedback}; }
TrueOrFalseType
= isTrue:(TrueType / FalseType) { return isTrue }
TrueType
= ('TRUE' / 'T') {return true}
FalseType
= ('FALSE' / 'F') {return false}
////////////////////
MCAnswers "{=correct choice ~incorrect choice ... }"
= choices:Choices _
globalFeedback:GlobalFeedback? _
{ return { type: "MC", choices:choices, globalFeedback:globalFeedback}; }
Choices "Choices"
= choices:(Choice)+ { return choices; }
Choice "Choice"
= _ choice:([=~] _ Weight? _ RichText) feedback:Feedback? _
{ var wt = choice[2];
var txt = choice[4];
var choice = { isCorrect: (choice[0] == '='),
weight:wt,
text: txt,
feedback:feedback };
return choice }
Weight "(weight)"
= '%' percent:([-]? PercentValue) '%' { return parseFloat(percent.join('')) }
PercentValue "(percent)"
= '100' / [0-9][0-9]?[.]?[0-9]* { return text() }
Feedback "(feedback)"
= '#' !'###' _ feedback:RichText? { return feedback }
////////////////////
EssayAnswer "Essay question { ... }"
= '' _
globalFeedback:GlobalFeedback? _
{ return { type: "Essay", globalFeedback:globalFeedback}; }
///////////////////
SingleCorrectShortAnswer "Single short answer { ... }"
= answer:RichText _
feedback:Feedback? _
globalFeedback:GlobalFeedback? _
{ var choices = [];
choices.push({isCorrect:true, text:answer, feedback:feedback, weight:null});
return { type: "Short", choices:choices, globalFeedback:globalFeedback}; }
///////////////////
NumericalAnswerType "{#... }" // Number ':' Range / Number '..' Number / Number
= '#' _
numericalAnswers:NumericalAnswers _
globalFeedback:GlobalFeedback?
{ return { type:"Numerical",
choices:numericalAnswers,
globalFeedback:globalFeedback}; }
NumericalAnswers "Numerical Answers"
= MultipleNumericalChoices / SingleNumericalAnswer
MultipleNumericalChoices "Multiple Numerical Choices"
= choices:(NumericalChoice)+ { return choices; }
NumericalChoice "Numerical Choice"
= _ choice:([=~] Weight? SingleNumericalAnswer?) _ feedback:Feedback? _
{ var symbol = choice[0];
var wt = choice[1];
var txt = choice[2];
var choice = { isCorrect:(symbol == '='),
weight:wt,
text: (txt !== null ? txt : {format:getLastQuestionTextFormat(), text:'*'}), // Moodle unit tests show this, not in documentation
feedback: feedback };
return choice }
SingleNumericalAnswer "Single numeric answer"
= NumberWithRange / NumberHighLow / NumberAlone
NumberWithRange "(number with range)"
= number:Number ':' range:Number
{ var numericAnswer = {type: 'range', number: number, range:range}; return numericAnswer}
NumberHighLow "(number with high-low)"
= numberLow:Number '..' numberHigh:Number
{ var numericAnswer = {type: 'high-low', numberHigh: numberHigh, numberLow:numberLow}; return numericAnswer}
NumberAlone "(number answer)"
= number:Number
{ var numericAnswer = {type: 'simple', number: number}; return numericAnswer}
//////////////
QuestionTitle ":: Title ::"
= '::' title:TitleText+ '::' { return escapedCharacterDecode(title.join('')) }
QuestionStem "Question stem"
= stem:RichText
{ setLastQuestionTextFormat(stem.format); // save format for question, for default of other non-formatted text
return stem }
QuestionSeparator "(blank lines separator)"
= BlankLines
/ EndOfLine? EndOfFile
BlankLines "(blank lines)"
= EndOfLine BlankLine+
BlankLine "blank line"
= Space* EndOfLine
TitleText "(Title text)"
= !'::' t:(EscapeSequence / UnescapedChar) {return t}
TextChar "(text character)"
= (UnescapedChar / EscapeSequence / EscapeChar)
MatchTextChar "(text character)"
= (UnescapedMatchChar / EscapeSequence / EscapeChar)
Format "format"
= '[' format:('html' /
'markdown' /
'plain' /
'moodle')
']' {return format}
EscapeChar "(escape character)"
= '\\'
EscapeSequence "escape sequence"
= "\\" char: ("\\" / ":" / "#" / "=" / "{" / "}" / "~" / "n") {
return escapedCharacters['\\' + char];
}
// return the text if it's not escaped
UnescapedChar ""
= !(EscapeSequence / ControlChar / QuestionSeparator) . {return text()}
// return the text if it's not escaped
UnescapedMatchChar ""
= !(EscapeSequence / ControlChar / '->' / QuestionSeparator) . {return text()}
ControlChar
= '=' / '~' / "#" / '{' / '}' / '\\' / ':'
MatchRichText "(formatted text excluding '->')"
= format:Format? _ txt:MatchTextChar+ { return formattedText(format, txt) }
RichText "(formatted text)"
= format:Format? _ txt:TextChar+ { return formattedText(format, txt) }
PlainText "(unformatted text)"
= txt:TextChar+ { return removeNewLinesDuplicateSpaces(txt.join('').trim())}
CategoryText "(category text)"
= txt:(!EndOfLine .)* &(EndOfLine / EndOfFile) { return txt.flat().join('') }
Number
= Sign? DecimalValue { return parseFloat(text()); }
DecimalValue
= Digits ('.' Digits)?
Digits
= [0-9]+
Sign
= [+-]
GlobalFeedback
= '####' _ rt:RichText _ {return rt;}
_ "(single line whitespace)"
= (Space / EndOfLine !BlankLine)*
__ "(multiple line whitespace)"
= (TagComment / EndOfLine / Space )*
ResetIdsTags
= &' '* // useless match to reset any previously parsed tags/ids
{questionId = null; questionTags = null}
Comment "(comment)"
= '//' p:([^\n\r]*)
{return null}
TagComment "(comment)"
= '//' p:([^\n\r]*)
{
var comment = p.join("");
// use a regex like the Moodle parser
var idIsFound = comment.match(/\[id:([^\x00-\x1F\x7F]+?)]/);
if(idIsFound) {
questionId = idIsFound[1].trim().replace('\\]', ']');
}
// use a regex like the Moodle parser
var tagMatches = comment.matchAll(/\[tag:([^\x00-\x1F\x7F]+?)]/g);
Array.from(
comment.matchAll(/\[tag:([^\x00-\x1F\x7F]+?)]/g),
function(m) { return m[1] })
.forEach(function(element) {
if(!questionTags) questionTags = [];
questionTags.push(element);
});
return null // hacking, must "reset" values each time a partial match happens
}
Space "(space)"
= ' ' / '\t'
EndOfLine "(end of line)"
= '\r\n' / '\n' / '\r'
EndOfFile
= !. { return "EOF"; }