-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmultiple-choice.jsx
More file actions
446 lines (388 loc) · 13.8 KB
/
multiple-choice.jsx
File metadata and controls
446 lines (388 loc) · 13.8 KB
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
import React from 'react';
import PropTypes from 'prop-types';
import CorrectAnswerToggle from '@pie-lib/correct-answer-toggle';
import classNames from 'classnames';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import { color, Collapsible, PreviewPrompt, transformDataHeadings } from '@pie-lib/render-ui';
import Translator from '@pie-lib/translator';
import Choice from './choice';
const { translator } = Translator;
const MainContainer = styled(Box)({
color: color.text(),
backgroundColor: color.background(),
'& *': {
'-webkit-font-smoothing': 'antialiased',
},
position: 'relative',
// remove border from legend tags inside main to override the OT default styles
'& legend': {
border: 'none !important',
},
});
const PartLabel = styled('h2')(({ theme }) => ({
display: 'block',
fontSize: 'inherit',
margin: '0',
fontWeight: 'normal',
paddingBottom: theme.spacing(2),
}));
const TeacherInstructions = styled(Box)(({ theme }) => ({
marginBottom: theme.spacing(2),
}));
const HorizontalLayout = styled(Box)({
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
});
const GridLayout = styled(Box)({
display: 'grid',
});
const StyledFieldset = styled('fieldset')({
border: '0px',
padding: '0.01em 0 0 0',
margin: '0px',
minWidth: '0px',
'&:focus': {
outline: 'none',
},
});
const SrOnly = styled('h3')({
position: 'absolute',
left: '-10000px',
top: 'auto',
width: '1px',
height: '1px',
overflow: 'hidden',
});
const ErrorText = styled('div')(({ theme }) => ({
fontSize: theme.typography.fontSize - 2,
color: theme.palette.error.main,
paddingTop: theme.spacing(1),
}));
export class MultipleChoice extends React.Component {
static propTypes = {
className: PropTypes.string,
mode: PropTypes.oneOf(['gather', 'view', 'evaluate']),
choiceMode: PropTypes.oneOf(['radio', 'checkbox']),
keyMode: PropTypes.oneOf(['numbers', 'letters', 'none']),
choices: PropTypes.array,
partLabel: PropTypes.string,
prompt: PropTypes.string,
teacherInstructions: PropTypes.string,
session: PropTypes.object,
disabled: PropTypes.bool,
onChoiceChanged: PropTypes.func,
responseCorrect: PropTypes.bool,
correctResponse: PropTypes.array,
choicesLayout: PropTypes.oneOf(['vertical', 'grid', 'horizontal']),
gridColumns: PropTypes.string,
alwaysShowCorrect: PropTypes.bool,
animationsDisabled: PropTypes.bool,
language: PropTypes.string,
selectedAnswerBackgroundColor: PropTypes.string,
selectedAnswerStrokeColor: PropTypes.string,
selectedAnswerStrokeWidth: PropTypes.string,
hoverAnswerBackgroundColor: PropTypes.string,
hoverAnswerStrokeColor: PropTypes.string,
hoverAnswerStrokeWidth: PropTypes.string,
onShowCorrectToggle: PropTypes.func,
isSelectionButtonBelow: PropTypes.bool,
minSelections: PropTypes.number,
maxSelections: PropTypes.number,
autoplayAudioEnabled: PropTypes.bool,
customAudioButton: {
playImage: PropTypes.string,
pauseImage: PropTypes.string,
},
options: PropTypes.object,
baseHeadingLevel: PropTypes.number,
includeSrHeading: PropTypes.bool,
};
constructor(props) {
super(props);
this.state = {
showCorrect: (this.props.options && this.props.alwaysShowCorrect) || false,
maxSelectionsErrorState: false,
};
this.onToggle = this.onToggle.bind(this);
this.firstInputRef = React.createRef();
}
isSelected(value) {
const sessionValue = this.props.session && this.props.session.value;
return sessionValue && sessionValue.indexOf && sessionValue.indexOf(value) >= 0;
}
// handleChange was added for accessibility. Please see comments and videos from PD-2441.
handleChange = (event) => {
const { value, checked } = event.target;
const { maxSelections, onChoiceChanged, session } = this.props;
if (session.value && session.value.length >= maxSelections) {
// show/hide max selections error when user select/deselect an answer
this.setState({ maxSelectionsErrorState: checked });
if (checked) {
// prevent selecting more answers
return;
}
}
onChoiceChanged({ value, selected: checked, selector: 'Mouse' });
};
onToggle = () => {
if (this.props.mode === 'evaluate') {
this.setState({ showCorrect: !this.state.showCorrect }, () => {
if (this.props.onShowCorrectToggle) {
this.props.onShowCorrectToggle();
}
});
}
};
UNSAFE_componentWillReceiveProps(nextProps) {
if (!nextProps.correctResponse && this.state.showCorrect !== false) {
this.setState({ showCorrect: false }, () => {
if (this.props.onShowCorrectToggle) {
this.props.onShowCorrectToggle();
}
});
}
if (nextProps.options && nextProps.alwaysShowCorrect && this.state.showCorrect !== true) {
this.setState({ showCorrect: true }, () => {
if (this.props.onShowCorrectToggle) {
this.props.onShowCorrectToggle();
}
});
}
}
indexToSymbol(index) {
if (this.props.keyMode === 'numbers') {
return `${index + 1}`;
}
if (this.props.keyMode === 'letters') {
return String.fromCharCode(97 + index).toUpperCase();
}
return '';
}
getCorrectness = (choice = {}) => {
const isCorrect = choice.correct;
const isChecked = this.isSelected(choice.value);
if (this.state.showCorrect) {
return isCorrect ? 'correct' : undefined;
}
if (isCorrect) {
if (isChecked) {
// A correct answer is selected: marked with a green checkmark
return 'correct';
} else {
// A correct answer is NOT selected: marked with an orange X
return 'incorrect';
}
} else {
if (isChecked) {
// An incorrect answer is selected: marked with an orange X
return 'incorrect';
} else {
// An incorrect answer is NOT selected: not marked
return undefined;
}
}
};
getChecked(choice) {
// check for print context: options prop is passed from print.js and alwaysShowCorrect is true
const isPrintMode = this.props.options && this.props.alwaysShowCorrect;
if (isPrintMode) {
return choice.correct || false;
}
// evaluate mode with show correct toggled
const isEvaluateMode = this.state.showCorrect && this.props.mode === 'evaluate';
if (isEvaluateMode) {
return choice.correct || false;
}
// default behavior: show what the user has selected
return this.isSelected(choice.value);
}
// renderHeading function was added for accessibility.
renderHeading() {
const { mode, choiceMode, includeSrHeading, baseHeadingLevel, partLabel } = this.props;
// When a part label is present the item is an EBSR part — the SR heading
// is provided by the EBSR element, not here.
const shouldRenderSrHeading = !partLabel && includeSrHeading !== false;
if (!shouldRenderSrHeading || mode !== 'gather') {
return null;
}
const clampedLevel = baseHeadingLevel ? Math.min(6, baseHeadingLevel) : 2;
const HeadingTag = SrOnly.withComponent(`h${clampedLevel}`);
const label = choiceMode === 'radio' ? 'Multiple Choice Question' : 'Multiple Select Question';
return <HeadingTag>{label}</HeadingTag>;
}
handleGroupFocus = (e) => {
const fieldset = e.currentTarget;
const activeEl = document.activeElement;
if (fieldset.contains(activeEl) && activeEl !== fieldset) {
return;
}
// Only focus the first input if user is tabbing forward
if (!e.relatedTarget || fieldset.compareDocumentPosition(e.relatedTarget) & Node.DOCUMENT_POSITION_PRECEDING) {
if (this.firstInputRef?.current) {
this.firstInputRef.current.focus();
}
}
};
render() {
const {
mode,
disabled,
className,
choices = [],
choiceMode,
gridColumns,
partLabel,
prompt,
responseCorrect,
teacherInstructions,
alwaysShowCorrect,
animationsDisabled,
language,
isSelectionButtonBelow,
minSelections,
maxSelections,
autoplayAudioEnabled,
session,
customAudioButton,
options,
baseHeadingLevel,
} = this.props;
const { showCorrect, maxSelectionsErrorState } = this.state;
const isEvaluateMode = mode === 'evaluate';
const showCorrectAnswerToggle = isEvaluateMode && !responseCorrect;
const columnsStyle = gridColumns > 1 ? { gridTemplateColumns: `repeat(${gridColumns}, 1fr)` } : undefined;
const selections = (session.value && session.value.length) || 0;
// Heading levels are optional and only applied when baseHeadingLevel is provided.
const getContentHeadingLevel = () => {
if (!baseHeadingLevel) return undefined;
// SR heading (rendered or external) sits at baseHeadingLevel.
// Content is always one below that; part label (EBSR) sits between them.
let offset = 1; // content default: baseHeadingLevel + 1
if (partLabel) offset += 1; // part label at base + 1, content pushed to base + 2
return Math.min(6, baseHeadingLevel + offset);
};
const contentHeadingLevel = getContentHeadingLevel();
const transformPrompt = (html) => (html && contentHeadingLevel) ? transformDataHeadings(html, contentHeadingLevel) : html;
const teacherInstructionsDiv = (
<PreviewPrompt
tagName="div"
className="prompt"
defaultClassName="teacher-instructions"
prompt={teacherInstructions}
/>
);
const getMultipleChoiceMinSelectionErrorMessage = () => {
if (minSelections && maxSelections) {
return minSelections === maxSelections
? translator.t('translation:multipleChoice:minmaxSelections_equal', { lng: language, minSelections })
: translator.t('translation:multipleChoice:minmaxSelections_range', {
lng: language,
minSelections,
maxSelections,
});
}
if (minSelections) {
return translator.t('translation:multipleChoice:minSelections', { lng: language, minSelections });
}
return '';
};
const LayoutComponent = this.props.choicesLayout === 'grid'
? GridLayout
: this.props.choicesLayout === 'horizontal'
? HorizontalLayout
: Box;
return (
<MainContainer id={'main-container'} className={classNames(className, 'multiple-choice')}>
{partLabel && <PartLabel as={baseHeadingLevel ? `h${Math.min(6, baseHeadingLevel + 1)}` : 'h2'}>{partLabel}</PartLabel>}
{this.renderHeading()}
{teacherInstructions && (
<TeacherInstructions>
{!animationsDisabled ? (
<Collapsible
labels={{
hidden: 'Show Teacher Instructions',
visible: 'Hide Teacher Instructions',
}}
>
{teacherInstructionsDiv}
</Collapsible>
) : (
teacherInstructionsDiv
)}
</TeacherInstructions>
)}
<StyledFieldset
tabIndex={0}
onFocus={this.handleGroupFocus}
role={choiceMode === 'radio' ? 'radiogroup' : 'group'}
>
<PreviewPrompt
className="prompt"
defaultClassName="prompt"
prompt={transformPrompt(prompt)}
tagName={'legend'}
autoplayAudioEnabled={autoplayAudioEnabled}
customAudioButton={customAudioButton}
/>
{!(options && alwaysShowCorrect) && (
<CorrectAnswerToggle
show={showCorrectAnswerToggle}
toggled={showCorrect}
onToggle={this.onToggle.bind(this)}
language={language}
/>
)}
<LayoutComponent style={columnsStyle}>
{choices.map((choice, index) => (
<Choice
autoFocusRef={index === 0 ? this.firstInputRef : null}
choicesLayout={this.props.choicesLayout}
selectedAnswerBackgroundColor={this.props.selectedAnswerBackgroundColor}
selectedAnswerStrokeColor={this.props.selectedAnswerStrokeColor}
selectedAnswerStrokeWidth={this.props.selectedAnswerStrokeWidth}
hoverAnswerBackgroundColor={this.props.hoverAnswerBackgroundColor}
hoverAnswerStrokeColor={this.props.hoverAnswerStrokeColor}
hoverAnswerStrokeWidth={this.props.hoverAnswerStrokeWidth}
gridColumns={gridColumns}
key={`choice-${index}`}
choice={choice}
index={index}
choicesLength={choices.length}
showCorrect={showCorrect}
isEvaluateMode={isEvaluateMode}
choiceMode={choiceMode}
disabled={disabled}
tagName={partLabel ? `group-${partLabel}` : 'group'}
onChoiceChanged={this.handleChange}
hideTick={choice.hideTick}
checked={this.getChecked(choice)}
correctness={isEvaluateMode ? this.getCorrectness(choice) : undefined}
displayKey={this.indexToSymbol(index)}
isSelectionButtonBelow={isSelectionButtonBelow}
/>
))}
</LayoutComponent>
</StyledFieldset>
{choiceMode === 'checkbox' && selections < minSelections && (
<ErrorText>{getMultipleChoiceMinSelectionErrorMessage()}</ErrorText>
)}
{choiceMode === 'checkbox' && maxSelectionsErrorState && (
<ErrorText>
{translator.t(`translation:multipleChoice:maxSelections_${maxSelections === 1 ? 'one' : 'other'}`, {
lng: language,
maxSelections,
})}
</ErrorText>
)}
</MainContainer>
);
}
}
MultipleChoice.defaultProps = {
session: {
value: [],
},
};
export default MultipleChoice;