EvalueTonSavoir/client/src/components/GiftTemplate/templates/MultipleChoiceAnswersTemplate.ts
C. Fuhrman 3d9015febd
Some checks failed
CI/CD Pipeline for Backend / build_and_push_backend (push) Failing after 18s
CI/CD Pipeline for Nginx Router / build_and_push_nginx (push) Failing after 17s
CI/CD Pipeline for Frontend / build_and_push_frontend (push) Failing after 18s
Tests / lint-and-tests (client) (push) Failing after 57s
Tests / lint-and-tests (server) (push) Failing after 1m2s
Fix bug with multiple choice (radio vs checkbox)
Snapshot update
2025-03-21 11:25:06 -04:00

63 lines
2.5 KiB
TypeScript

import { nanoid } from 'nanoid';
import { TemplateOptions } from './types';
import {FormattedTextTemplate} from './TextTypeTemplate';
import AnswerIcon from './AnswerIconTemplate';
import { state } from '.';
import { ParagraphStyle } from '../constants';
import { MultipleChoiceQuestion, TextChoice } from 'gift-pegjs';
type MultipleChoiceAnswerOptions = TemplateOptions & Pick<MultipleChoiceQuestion, 'choices'>;
type AnswerFeedbackOptions = TemplateOptions & Pick<TextChoice, 'formattedFeedback'>;
interface AnswerWeightOptions extends TemplateOptions {
weight: TextChoice['weight'];
}
// careful -- this template is re-used by True/False questions!
export default function MultipleChoiceAnswersTemplate({ choices }: MultipleChoiceAnswerOptions) {
const id = `id${nanoid(8)}`;
const hasManyCorrectChoices = choices.filter(({ isCorrect }) => isCorrect === true).length > 1;
const prompt = `<span style="${ParagraphStyle(state.theme)}">Choisir une réponse${
hasManyCorrectChoices ? ` ou plusieurs` : ``
}:</span>`;
const result = choices
.map(({ weight, isCorrect, formattedText, formattedFeedback }) => {
const CustomLabel = `
display: inline-block;
padding: 0.2em 0 0.2em 0;
`;
const inputId = `id${nanoid(6)}`;
const isPositiveWeight = (weight != undefined) && (weight > 0);
const isCorrectOption = hasManyCorrectChoices ? isPositiveWeight || isCorrect : isCorrect;
return `
<div class='multiple-choice-answers-container'>
<input class="gift-input" type="${
hasManyCorrectChoices ? 'checkbox' : 'radio'
}" id="${inputId}" name="${id}">
${AnswerWeight({ weight: weight })}
<label style="${CustomLabel} ${ParagraphStyle(state.theme)}" for="${inputId}">
${FormattedTextTemplate(formattedText)}
</label>
${AnswerIcon({ correct: isCorrectOption })}
${AnswerFeedback({ formattedFeedback: formattedFeedback })}
</input>
</div>
`;
})
.join('');
return `${prompt}${result}`;
}
function AnswerWeight({ weight }: AnswerWeightOptions): string {
return weight ? `<span class="answer-weight-container ${weight > 0 ? 'answer-positive-weight' : 'answer-zero-or-less-weight'}">${weight}%</span>` : ``;
}
function AnswerFeedback({ formattedFeedback }: AnswerFeedbackOptions): string {
return formattedFeedback ? `<span class="feedback-container">${FormattedTextTemplate(formattedFeedback)}</span>` : ``;
}