mirror of
https://github.com/alexmickelson/canvasManagement.git
synced 2026-03-27 07:58:31 -06:00
refactoring files to be located by feature
This commit is contained in:
149
src/features/local/quizzes/models/utils/quizMarkdownUtils.ts
Normal file
149
src/features/local/quizzes/models/utils/quizMarkdownUtils.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
import { verifyDateOrThrow, verifyDateStringOrUndefined } from "@/models/local/utils/timeUtils";
|
||||
import { LocalQuiz } from "../localQuiz";
|
||||
import { quizQuestionMarkdownUtils } from "./quizQuestionMarkdownUtils";
|
||||
|
||||
const extractLabelValue = (input: string, label: string): string => {
|
||||
const pattern = new RegExp(`${label}: (.*?)\n`);
|
||||
const match = pattern.exec(input);
|
||||
return match ? match[1].trim() : "";
|
||||
};
|
||||
|
||||
const extractDescription = (input: string): string => {
|
||||
const pattern = new RegExp("Description: (.*?)$", "s");
|
||||
const match = pattern.exec(input);
|
||||
return match ? match[1].trim() : "";
|
||||
};
|
||||
|
||||
const parseBooleanOrThrow = (value: string, label: string): boolean => {
|
||||
if (value.toLowerCase() === "true") return true;
|
||||
if (value.toLowerCase() === "false") return false;
|
||||
throw new Error(`Error with ${label}: ${value}`);
|
||||
};
|
||||
|
||||
const parseBooleanOrDefault = (
|
||||
value: string,
|
||||
label: string,
|
||||
defaultValue: boolean
|
||||
): boolean => {
|
||||
if (value.toLowerCase() === "true") return true;
|
||||
if (value.toLowerCase() === "false") return false;
|
||||
return defaultValue;
|
||||
};
|
||||
|
||||
const parseNumberOrThrow = (value: string, label: string): number => {
|
||||
const parsed = parseInt(value, 10);
|
||||
if (isNaN(parsed)) {
|
||||
throw new Error(`Error with ${label}: ${value}`);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
const getQuizWithOnlySettings = (settings: string, name: string): LocalQuiz => {
|
||||
|
||||
const rawShuffleAnswers = extractLabelValue(settings, "ShuffleAnswers");
|
||||
const shuffleAnswers = parseBooleanOrThrow(
|
||||
rawShuffleAnswers,
|
||||
"ShuffleAnswers"
|
||||
);
|
||||
|
||||
const password = extractLabelValue(settings, "Password") || undefined;
|
||||
|
||||
const rawShowCorrectAnswers = extractLabelValue(
|
||||
settings,
|
||||
"ShowCorrectAnswers"
|
||||
);
|
||||
const showCorrectAnswers = parseBooleanOrDefault(
|
||||
rawShowCorrectAnswers,
|
||||
"ShowCorrectAnswers",
|
||||
true
|
||||
);
|
||||
|
||||
const rawOneQuestionAtATime = extractLabelValue(
|
||||
settings,
|
||||
"OneQuestionAtATime"
|
||||
);
|
||||
const oneQuestionAtATime = parseBooleanOrThrow(
|
||||
rawOneQuestionAtATime,
|
||||
"OneQuestionAtATime"
|
||||
);
|
||||
|
||||
const rawAllowedAttempts = extractLabelValue(settings, "AllowedAttempts");
|
||||
const allowedAttempts = parseNumberOrThrow(
|
||||
rawAllowedAttempts,
|
||||
"AllowedAttempts"
|
||||
);
|
||||
|
||||
const rawDueAt = extractLabelValue(settings, "DueAt");
|
||||
const dueAt = verifyDateOrThrow(rawDueAt, "DueAt");
|
||||
|
||||
const rawLockAt = extractLabelValue(settings, "LockAt");
|
||||
const lockAt = verifyDateStringOrUndefined(rawLockAt);
|
||||
|
||||
const description = extractDescription(settings);
|
||||
const localAssignmentGroupName = extractLabelValue(
|
||||
settings,
|
||||
"AssignmentGroup"
|
||||
);
|
||||
|
||||
const quiz: LocalQuiz = {
|
||||
name,
|
||||
description,
|
||||
password,
|
||||
lockAt,
|
||||
dueAt,
|
||||
shuffleAnswers,
|
||||
showCorrectAnswers,
|
||||
oneQuestionAtATime,
|
||||
localAssignmentGroupName,
|
||||
allowedAttempts,
|
||||
questions: [],
|
||||
};
|
||||
return quiz;
|
||||
};
|
||||
|
||||
export const quizMarkdownUtils = {
|
||||
toMarkdown(quiz: LocalQuiz): string {
|
||||
if (!quiz) {
|
||||
throw Error(`quiz was undefined, cannot parse markdown`);
|
||||
}
|
||||
if (
|
||||
typeof quiz.questions === "undefined" ||
|
||||
typeof quiz.oneQuestionAtATime === "undefined"
|
||||
) {
|
||||
console.log("quiz is probably not a quiz", quiz);
|
||||
throw Error(`quiz ${quiz.name} is probably not a quiz`);
|
||||
}
|
||||
const questionMarkdownArray = quiz.questions.map((q) =>
|
||||
quizQuestionMarkdownUtils.toMarkdown(q)
|
||||
);
|
||||
const questionDelimiter = "\n\n---\n\n";
|
||||
const questionMarkdown = questionMarkdownArray.join(questionDelimiter);
|
||||
|
||||
return `LockAt: ${quiz.lockAt ?? ""}
|
||||
DueAt: ${quiz.dueAt}
|
||||
Password: ${quiz.password ?? ""}
|
||||
ShuffleAnswers: ${quiz.shuffleAnswers.toString().toLowerCase()}
|
||||
ShowCorrectAnswers: ${quiz.showCorrectAnswers.toString().toLowerCase()}
|
||||
OneQuestionAtATime: ${quiz.oneQuestionAtATime.toString().toLowerCase()}
|
||||
AssignmentGroup: ${quiz.localAssignmentGroupName}
|
||||
AllowedAttempts: ${quiz.allowedAttempts}
|
||||
Description: ${quiz.description}
|
||||
---
|
||||
${questionMarkdown}`;
|
||||
},
|
||||
|
||||
parseMarkdown(input: string, name: string): LocalQuiz {
|
||||
const splitInput = input.split("---\n");
|
||||
const settings = splitInput[0];
|
||||
const quizWithoutQuestions = getQuizWithOnlySettings(settings, name);
|
||||
|
||||
const rawQuestions = splitInput.slice(1);
|
||||
const questions = rawQuestions
|
||||
.filter((str) => str.trim().length > 0)
|
||||
.map((q, i) => quizQuestionMarkdownUtils.parseMarkdown(q, i));
|
||||
|
||||
return {
|
||||
...quizWithoutQuestions,
|
||||
questions,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import { QuestionType } from "../localQuizQuestion";
|
||||
import { LocalQuizQuestionAnswer } from "../localQuizQuestionAnswer";
|
||||
|
||||
const parseMatchingAnswer = (input: string) => {
|
||||
const matchingPattern = /^\^?/;
|
||||
const textWithoutMatchDelimiter = input.replace(matchingPattern, "");
|
||||
const [text, ...matchedParts] = textWithoutMatchDelimiter.split(" - ");
|
||||
const answer: LocalQuizQuestionAnswer = {
|
||||
correct: true,
|
||||
text: text.trim(),
|
||||
matchedText: matchedParts.join("-").trim(),
|
||||
};
|
||||
return answer;
|
||||
};
|
||||
|
||||
export const quizQuestionAnswerMarkdownUtils = {
|
||||
// getHtmlText(): string {
|
||||
// return MarkdownService.render(this.text);
|
||||
// }
|
||||
|
||||
parseMarkdown(input: string, questionType: string): LocalQuizQuestionAnswer {
|
||||
const isCorrect = input.startsWith("*") || input[1] === "*";
|
||||
|
||||
if (questionType === QuestionType.MATCHING) {
|
||||
return parseMatchingAnswer(input);
|
||||
}
|
||||
|
||||
const startingQuestionPattern = /^(\*?[a-z]?\))|\[\s*\]|\[\*\]|\^ /;
|
||||
|
||||
let replaceCount = 0;
|
||||
const text = input
|
||||
.replace(startingQuestionPattern, (m) => (replaceCount++ === 0 ? "" : m))
|
||||
.trim();
|
||||
|
||||
const answer: LocalQuizQuestionAnswer = {
|
||||
correct: isCorrect,
|
||||
text: text,
|
||||
};
|
||||
return answer;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,253 @@
|
||||
import { LocalQuizQuestion, QuestionType } from "../localQuizQuestion";
|
||||
import { LocalQuizQuestionAnswer } from "../localQuizQuestionAnswer";
|
||||
import { quizQuestionAnswerMarkdownUtils } from "./quizQuestionAnswerMarkdownUtils";
|
||||
|
||||
const _validFirstAnswerDelimiters = [
|
||||
"*a)",
|
||||
"a)",
|
||||
"*)",
|
||||
")",
|
||||
"[ ]",
|
||||
"[]",
|
||||
"[*]",
|
||||
"^",
|
||||
];
|
||||
const _multipleChoicePrefix = ["a)", "*a)", "*)", ")"];
|
||||
const _multipleAnswerPrefix = ["[ ]", "[*]", "[]"];
|
||||
|
||||
const getAnswerStringsWithMultilineSupport = (
|
||||
linesWithoutPoints: string[],
|
||||
questionIndex: number
|
||||
) => {
|
||||
const indexOfAnswerStart = linesWithoutPoints.findIndex((l) =>
|
||||
_validFirstAnswerDelimiters.some((prefix) =>
|
||||
l.trimStart().startsWith(prefix)
|
||||
)
|
||||
);
|
||||
if (indexOfAnswerStart === -1) {
|
||||
const debugLine = linesWithoutPoints.find((l) => l.trim().length > 0);
|
||||
throw Error(
|
||||
`question ${
|
||||
questionIndex + 1
|
||||
}: no answers when detecting question type on ${debugLine}`
|
||||
);
|
||||
}
|
||||
|
||||
const answerLinesRaw = linesWithoutPoints.slice(indexOfAnswerStart);
|
||||
|
||||
const answerStartPattern = /^(\*?[a-z]?\))|(?<!\S)\[\s*\]|\[\*\]|\^/;
|
||||
const answerLines = answerLinesRaw.reduce((acc: string[], line: string) => {
|
||||
const isNewAnswer = answerStartPattern.test(line);
|
||||
if (isNewAnswer) {
|
||||
acc.push(line);
|
||||
} else if (acc.length !== 0) {
|
||||
acc[acc.length - 1] += "\n" + line;
|
||||
} else {
|
||||
acc.push(line);
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
return answerLines;
|
||||
};
|
||||
const getQuestionType = (
|
||||
linesWithoutPoints: string[],
|
||||
questionIndex: number
|
||||
): QuestionType => {
|
||||
if (linesWithoutPoints.length === 0) return QuestionType.NONE;
|
||||
if (
|
||||
linesWithoutPoints[linesWithoutPoints.length - 1].toLowerCase() === "essay"
|
||||
)
|
||||
return QuestionType.ESSAY;
|
||||
if (
|
||||
linesWithoutPoints[linesWithoutPoints.length - 1].toLowerCase() ===
|
||||
"short answer"
|
||||
)
|
||||
return QuestionType.SHORT_ANSWER;
|
||||
if (
|
||||
linesWithoutPoints[linesWithoutPoints.length - 1].toLowerCase() ===
|
||||
"short_answer"
|
||||
)
|
||||
return QuestionType.SHORT_ANSWER;
|
||||
if (
|
||||
linesWithoutPoints[linesWithoutPoints.length - 1].toLowerCase().trim() ===
|
||||
"short_answer="
|
||||
)
|
||||
return QuestionType.SHORT_ANSWER_WITH_ANSWERS;
|
||||
|
||||
const answerLines = getAnswerStringsWithMultilineSupport(
|
||||
linesWithoutPoints,
|
||||
questionIndex
|
||||
);
|
||||
const firstAnswerLine = answerLines[0];
|
||||
const isMultipleChoice = _multipleChoicePrefix.some((prefix) =>
|
||||
firstAnswerLine.startsWith(prefix)
|
||||
);
|
||||
|
||||
if (isMultipleChoice) return QuestionType.MULTIPLE_CHOICE;
|
||||
|
||||
const isMultipleAnswer = _multipleAnswerPrefix.some((prefix) =>
|
||||
firstAnswerLine.startsWith(prefix)
|
||||
);
|
||||
if (isMultipleAnswer) return QuestionType.MULTIPLE_ANSWERS;
|
||||
|
||||
const isMatching = firstAnswerLine.startsWith("^");
|
||||
if (isMatching) return QuestionType.MATCHING;
|
||||
|
||||
return QuestionType.NONE;
|
||||
};
|
||||
|
||||
const getAnswers = (
|
||||
linesWithoutPoints: string[],
|
||||
questionIndex: number,
|
||||
questionType: string
|
||||
): LocalQuizQuestionAnswer[] => {
|
||||
if (questionType == QuestionType.SHORT_ANSWER_WITH_ANSWERS)
|
||||
linesWithoutPoints = linesWithoutPoints.slice(
|
||||
0,
|
||||
linesWithoutPoints.length - 1
|
||||
);
|
||||
const answerLines = getAnswerStringsWithMultilineSupport(
|
||||
linesWithoutPoints,
|
||||
questionIndex
|
||||
);
|
||||
|
||||
const answers = answerLines.map((a) =>
|
||||
quizQuestionAnswerMarkdownUtils.parseMarkdown(a, questionType)
|
||||
);
|
||||
return answers;
|
||||
};
|
||||
|
||||
const getAnswerMarkdown = (
|
||||
question: LocalQuizQuestion,
|
||||
answer: LocalQuizQuestionAnswer,
|
||||
index: number
|
||||
): string => {
|
||||
const multilineMarkdownCompatibleText = answer.text.startsWith("```")
|
||||
? "\n" + answer.text
|
||||
: answer.text;
|
||||
|
||||
if (question.questionType === "multiple_answers") {
|
||||
const correctIndicator = answer.correct ? "*" : " ";
|
||||
const questionTypeIndicator = `[${correctIndicator}] `;
|
||||
|
||||
return `${questionTypeIndicator}${multilineMarkdownCompatibleText}`;
|
||||
} else if (question.questionType === "matching") {
|
||||
return `^ ${answer.text} - ${answer.matchedText}`;
|
||||
} else {
|
||||
const questionLetter = String.fromCharCode(97 + index);
|
||||
const correctIndicator = answer.correct ? "*" : "";
|
||||
const questionTypeIndicator = `${correctIndicator}${questionLetter}) `;
|
||||
|
||||
return `${questionTypeIndicator}${multilineMarkdownCompatibleText}`;
|
||||
}
|
||||
};
|
||||
|
||||
export const quizQuestionMarkdownUtils = {
|
||||
toMarkdown(question: LocalQuizQuestion): string {
|
||||
const answerArray = question.answers.map((a, i) =>
|
||||
getAnswerMarkdown(question, a, i)
|
||||
);
|
||||
|
||||
const distractorText =
|
||||
question.questionType === QuestionType.MATCHING
|
||||
? question.matchDistractors?.map((d) => `\n^ - ${d}`).join("") ?? ""
|
||||
: "";
|
||||
|
||||
const answersText = answerArray.join("\n");
|
||||
const questionTypeIndicator =
|
||||
question.questionType === "essay" ||
|
||||
question.questionType === "short_answer"
|
||||
? question.questionType
|
||||
: question.questionType === QuestionType.SHORT_ANSWER_WITH_ANSWERS
|
||||
? `\n${QuestionType.SHORT_ANSWER_WITH_ANSWERS}`
|
||||
: "";
|
||||
|
||||
return `Points: ${question.points}\n${question.text}\n${answersText}${distractorText}${questionTypeIndicator}`;
|
||||
},
|
||||
|
||||
parseMarkdown(input: string, questionIndex: number): LocalQuizQuestion {
|
||||
const lines = input.trim().split("\n");
|
||||
const firstLineIsPoints = lines[0].toLowerCase().includes("points: ");
|
||||
|
||||
const textHasPoints =
|
||||
lines.length > 0 &&
|
||||
lines[0].includes(": ") &&
|
||||
lines[0].split(": ").length > 1 &&
|
||||
!isNaN(parseFloat(lines[0].split(": ")[1]));
|
||||
|
||||
const points =
|
||||
firstLineIsPoints && textHasPoints
|
||||
? parseFloat(lines[0].split(": ")[1])
|
||||
: 1;
|
||||
|
||||
const linesWithoutPoints = firstLineIsPoints ? lines.slice(1) : lines;
|
||||
|
||||
const { linesWithoutAnswers } = linesWithoutPoints.reduce(
|
||||
({ linesWithoutAnswers, taking }, currentLine) => {
|
||||
if (!taking)
|
||||
return { linesWithoutAnswers: linesWithoutAnswers, taking: false };
|
||||
|
||||
const lineIsAnswer = _validFirstAnswerDelimiters.some((prefix) =>
|
||||
currentLine.trimStart().startsWith(prefix)
|
||||
);
|
||||
if (lineIsAnswer)
|
||||
return { linesWithoutAnswers: linesWithoutAnswers, taking: false };
|
||||
|
||||
return {
|
||||
linesWithoutAnswers: [...linesWithoutAnswers, currentLine],
|
||||
taking: true,
|
||||
};
|
||||
},
|
||||
{ linesWithoutAnswers: [] as string[], taking: true }
|
||||
);
|
||||
const questionType = getQuestionType(linesWithoutPoints, questionIndex);
|
||||
|
||||
const questionTypesWithoutAnswers = [
|
||||
"essay",
|
||||
"short answer",
|
||||
"short_answer",
|
||||
];
|
||||
|
||||
const descriptionLines = questionTypesWithoutAnswers.includes(
|
||||
questionType.toLowerCase()
|
||||
)
|
||||
? linesWithoutAnswers
|
||||
.slice(0, linesWithoutPoints.length)
|
||||
.filter(
|
||||
(line) =>
|
||||
!questionTypesWithoutAnswers.includes(line.toLowerCase())
|
||||
)
|
||||
: linesWithoutAnswers;
|
||||
|
||||
const description = descriptionLines.join("\n");
|
||||
|
||||
const typesWithAnswers = [
|
||||
"multiple_choice",
|
||||
"multiple_answers",
|
||||
"matching",
|
||||
"short_answer=",
|
||||
];
|
||||
const answers = typesWithAnswers.includes(questionType)
|
||||
? getAnswers(linesWithoutPoints, questionIndex, questionType)
|
||||
: [];
|
||||
|
||||
const answersWithoutDistractors =
|
||||
questionType === QuestionType.MATCHING
|
||||
? answers.filter((a) => a.text)
|
||||
: answers;
|
||||
|
||||
const distractors =
|
||||
questionType === QuestionType.MATCHING
|
||||
? answers.filter((a) => !a.text).map((a) => a.matchedText ?? "")
|
||||
: [];
|
||||
|
||||
const question: LocalQuizQuestion = {
|
||||
text: description,
|
||||
questionType,
|
||||
points,
|
||||
answers: answersWithoutDistractors,
|
||||
matchDistractors: distractors,
|
||||
};
|
||||
return question;
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user