diff --git a/package.json b/package.json index f32bdaa4..64c9eeb4 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ }, "dependencies": { "chart.js": "^4.4.2", + "clozecraft": "^0.4.0", "pagerank.js": "^1.0.2" }, "packageManager": "^pnpm@8.15.4" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f08b92ce..53452ff9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,9 @@ dependencies: chart.js: specifier: ^4.4.2 version: 4.4.2 + clozecraft: + specifier: ^0.4.0 + version: 0.4.0 pagerank.js: specifier: ^1.0.2 version: 1.0.2 @@ -2207,6 +2210,10 @@ packages: requiresBuild: true dev: true + /clozecraft@0.4.0: + resolution: {integrity: sha512-VeXEZV6/Ar0sLbru53lpn9bNf6dpBtQtywUJ0K76WOCrI9a61jSgEo/aspwUuKdpR7kAtAhAlsYDDEaZj87wqQ==} + dev: false + /co@4.6.0: resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==} engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'} diff --git a/src/NoteQuestionParser.ts b/src/NoteQuestionParser.ts index acb668cf..5737d5e0 100644 --- a/src/NoteQuestionParser.ts +++ b/src/NoteQuestionParser.ts @@ -143,9 +143,7 @@ export class NoteQuestionParser { settings.singleLineReversedCardSeparator, settings.multilineCardSeparator, settings.multilineReversedCardSeparator, - settings.convertHighlightsToClozes, - settings.convertBoldTextToClozes, - settings.convertCurlyBracketsToClozes, + settings.clozePatterns, ); return result; } diff --git a/src/QuestionType.ts b/src/QuestionType.ts index 175ce946..d5e54e3f 100644 --- a/src/QuestionType.ts +++ b/src/QuestionType.ts @@ -1,3 +1,4 @@ +import { ClozeCrafter, IClozeFormatter } from "clozecraft"; import { CardType } from "./Question"; import { SRSettings } from "./settings"; import { findLineIndexOfSearchStringIgnoringWs } from "./util/utils"; @@ -92,44 +93,15 @@ class QuestionType_MultiLineReversed implements IQuestionTypeHandler { class QuestionType_Cloze implements IQuestionTypeHandler { expand(questionText: string, settings: SRSettings): CardFrontBack[] { - const siblings: RegExpMatchArray[] = []; - if (settings.convertHighlightsToClozes) { - siblings.push(...questionText.matchAll(/==(.*?)==/gm)); - } - if (settings.convertBoldTextToClozes) { - siblings.push(...questionText.matchAll(/\*\*(.*?)\*\*/gm)); - } - if (settings.convertCurlyBracketsToClozes) { - siblings.push(...questionText.matchAll(/{{(.*?)}}/gm)); - } - siblings.sort((a, b) => { - if (a.index < b.index) { - return -1; - } - if (a.index > b.index) { - return 1; - } - // What is unit test to cover following statement; otherwise jest please ignore - return 0; - }); + const clozecrafter = new ClozeCrafter(settings.clozePatterns); + const clozeNote = clozecrafter.createClozeNote(questionText); + const clozeFormatter = new QuestionType_ClozeFormatter(); let front: string, back: string; const result: CardFrontBack[] = []; - for (const m of siblings) { - const deletionStart: number = m.index, - deletionEnd: number = deletionStart + m[0].length; - front = - questionText.substring(0, deletionStart) + - QuestionType_ClozeUtil.renderClozeFront() + - questionText.substring(deletionEnd); - front = QuestionType_ClozeUtil.removeClozeTokens(front, settings); - back = - questionText.substring(0, deletionStart) + - QuestionType_ClozeUtil.renderClozeBack( - questionText.substring(deletionStart, deletionEnd), - ) + - questionText.substring(deletionEnd); - back = QuestionType_ClozeUtil.removeClozeTokens(back, settings); + for (let i = 0; i < clozeNote.numCards; i++) { + front = clozeNote.getCardFront(i, clozeFormatter); + back = clozeNote.getCardBack(i, clozeFormatter); result.push(new CardFrontBack(front, back)); } @@ -137,23 +109,15 @@ class QuestionType_Cloze implements IQuestionTypeHandler { } } -export class QuestionType_ClozeUtil { - static renderClozeFront(): string { - return "[...]"; +export class QuestionType_ClozeFormatter implements IClozeFormatter { + asking(answer?: string, hint?: string): string { + return `${!hint ? "[...]" : `[${hint}]`}`; } - - static renderClozeBack(str: string): string { - return "" + str + ""; + showingAnswer(answer: string, _hint?: string): string { + return `${answer}`; } - - static removeClozeTokens(text: string, settings: SRSettings): string { - let result: string = text; - if (settings.convertHighlightsToClozes) result = result.replace(/==/gm, ""); - if (settings.convertBoldTextToClozes) result = result.replace(/\*\*/gm, ""); - if (settings.convertCurlyBracketsToClozes) { - result = result.replace(/{{/gm, "").replace(/}}/gm, ""); - } - return result; + hiding(answer?: string, hint?: string): string { + return `${!hint ? "[...]" : `[${hint}]`}`; } } diff --git a/src/lang/locale/ar.ts b/src/lang/locale/ar.ts index d4dee92e..4c285781 100644 --- a/src/lang/locale/ar.ts +++ b/src/lang/locale/ar.ts @@ -95,6 +95,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "Convert ==hightlights== to clozes?", CONVERT_BOLD_TEXT_TO_CLOZES: "Convert **bolded text** to clozes?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "Convert {{curly brackets}} to clozes?", + CLOZE_PATTERNS: "Cloze Patterns", + CLOZE_PATTERNS_DESC: "Enter cloze patterns separated by newlines", INLINE_CARDS_SEPARATOR: "فاصل من أجل البطاقات المضمنة", FIX_SEPARATORS_MANUALLY_WARNING: "ضع في حسابك أنه بعد تغيير هذا ، يجب عليك تعديل أي بطاقات لديك بالفعل يدويًا", diff --git a/src/lang/locale/cz.ts b/src/lang/locale/cz.ts index ebece0a5..38b5a415 100644 --- a/src/lang/locale/cz.ts +++ b/src/lang/locale/cz.ts @@ -98,6 +98,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "Převést ==zvýraznění== na clozes?", CONVERT_BOLD_TEXT_TO_CLOZES: "Převést **tučný text** na clozes?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "Převést {{složené závorky}} na clozes?", + CLOZE_PATTERNS: "Cloze vzory", + CLOZE_PATTERNS_DESC: "Zadejte cloze vzory oddělené odřádkováním", INLINE_CARDS_SEPARATOR: "Oddělovač pro inline kartičky", FIX_SEPARATORS_MANUALLY_WARNING: "Pozor. Jakmile toto změníte, budete muset ručně upravit všechny existující kartičky.", diff --git a/src/lang/locale/de.ts b/src/lang/locale/de.ts index d4e142d9..d7317b15 100644 --- a/src/lang/locale/de.ts +++ b/src/lang/locale/de.ts @@ -110,6 +110,8 @@ export default { CONVERT_BOLD_TEXT_TO_CLOZES: "**Fettgedruckten** Text in Lückentextkarten umwandeln?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "{{Geschweifte Klammern}} Text in Lückentextkarten umwandeln?", + CLOZE_PATTERNS: "Lückentextmuster", + CLOZE_PATTERNS_DESC: "Geben Sie Lückentextmuster durch Zeilenumbrüche getrennt ein", INLINE_CARDS_SEPARATOR: "Trennzeichen für einzeilige Lernkarten", FIX_SEPARATORS_MANUALLY_WARNING: "Wenn diese Einstellung geändert wird, dann müssen die entsprechenden Lernkarten manuell angepasst werden.", diff --git a/src/lang/locale/en.ts b/src/lang/locale/en.ts index 2112229c..447f5f7a 100644 --- a/src/lang/locale/en.ts +++ b/src/lang/locale/en.ts @@ -97,6 +97,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "Convert ==hightlights== to clozes?", CONVERT_BOLD_TEXT_TO_CLOZES: "Convert **bolded text** to clozes?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "Convert {{curly brackets}} to clozes?", + CLOZE_PATTERNS: "Cloze Patterns", + CLOZE_PATTERNS_DESC: "Enter cloze patterns separated by newlines", INLINE_CARDS_SEPARATOR: "Separator for inline flashcards", FIX_SEPARATORS_MANUALLY_WARNING: "Note that after changing this you have to manually edit any flashcards you already have.", diff --git a/src/lang/locale/es.ts b/src/lang/locale/es.ts index 337105ad..7898be45 100644 --- a/src/lang/locale/es.ts +++ b/src/lang/locale/es.ts @@ -98,6 +98,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "¿Convertir ==resaltados== a deletreo de huecos?", CONVERT_BOLD_TEXT_TO_CLOZES: "¿Convertir **texto en negrita** a deletreo de huecos?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "¿Convertir {{llaves rizadas}} a deletreo de huecos?", + CLOZE_PATTERNS: "Patrones de deletreo de huecos", + CLOZE_PATTERNS_DESC: "Escriba los patrones de deletreo de huecos separados por saltos de línea", INLINE_CARDS_SEPARATOR: "Separador de tarjetas de memorización en línea", FIX_SEPARATORS_MANUALLY_WARNING: "Note que después de cambiar este ajuste, tendrá que cambiar manualmente todas las notas que tenga.", diff --git a/src/lang/locale/it.ts b/src/lang/locale/it.ts index 33ddff94..59d2e27f 100644 --- a/src/lang/locale/it.ts +++ b/src/lang/locale/it.ts @@ -103,6 +103,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "Convertire ==testo evidenziato== in spazi da riempire?", CONVERT_BOLD_TEXT_TO_CLOZES: "Convertire **testo in grassetto** in spazi da riempire", CONVERT_CURLY_BRACKETS_TO_CLOZES: "Convertire {{parentesi graffe}} in spazi da riempire?", + CLOZE_PATTERNS: "Modelli di spazi da riempire", + CLOZE_PATTERNS_DESC: "Inserisci i modelli di spazi da riempire separati da a capo", INLINE_CARDS_SEPARATOR: "Separatore per schede sulla stessa riga", FIX_SEPARATORS_MANUALLY_WARNING: "Si avvisa che dopo aver cambiato questo dovrai manualmente modificare le schede che hai già.", diff --git a/src/lang/locale/ja.ts b/src/lang/locale/ja.ts index 96bbbcfd..24e7f413 100644 --- a/src/lang/locale/ja.ts +++ b/src/lang/locale/ja.ts @@ -101,6 +101,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "==ハイライト==を穴埋めとして使用しますか?", CONVERT_BOLD_TEXT_TO_CLOZES: "**ボールド体**を穴埋めとして使用しますか?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "{{中括弧}}を穴埋めとして使用しますか?", + CLOZE_PATTERNS: "穴埋めパターン", + CLOZE_PATTERNS_DESC: "改行で区切って穴埋めパターンを入力してください。", INLINE_CARDS_SEPARATOR: "インラインフラッシュカードに使用するセパレーター", FIX_SEPARATORS_MANUALLY_WARNING: "このオプションを変更する場合には、作成済みのフラッシュカードを手動で編集し直す必要があることに注意してください。", diff --git a/src/lang/locale/ko.ts b/src/lang/locale/ko.ts index 4f1e6206..d80bdf48 100644 --- a/src/lang/locale/ko.ts +++ b/src/lang/locale/ko.ts @@ -99,6 +99,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "==hightlights== 를 빈 칸 채우기로 전환하시겠습니까?", CONVERT_BOLD_TEXT_TO_CLOZES: "**bolded text** 를 빈 칸 채우기로 전환하시겠습니까?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "{{curly brackets}} 를 빈 칸 채우기로 전환하시겠습니까?", + CLOZE_PATTERNS: "빈 칸 채우기 패턴", + CLOZE_PATTERNS_DESC: "빈 칸 채우기 패턴을 입력해주세요. 줄바꿈으로 구분합니다.", INLINE_CARDS_SEPARATOR: "인라인 플래시카드 구분자", FIX_SEPARATORS_MANUALLY_WARNING: "주의: 이 옵션을 수정한 후에는 이미 작성된 플래시카드를 수동으로 수정해야 함을 주의하십시오.", diff --git a/src/lang/locale/pl.ts b/src/lang/locale/pl.ts index 3d3cf47d..b31be89d 100644 --- a/src/lang/locale/pl.ts +++ b/src/lang/locale/pl.ts @@ -101,6 +101,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "Konwertować ==podświetlenia== na karty zamaskowane?", CONVERT_BOLD_TEXT_TO_CLOZES: "Konwertować pogrubiony tekst na karty zamaskowane?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "Konwertować {{klamry}} na karty zamaskowane?", + CLOZE_PATTERNS: "Wzory kart zamaskowanych", + CLOZE_PATTERNS_DESC: "Wprowadź wzory kart zamaskowanych oddzielone nowymi liniami", INLINE_CARDS_SEPARATOR: "Separator dla kart zamaskowanych w linii", FIX_SEPARATORS_MANUALLY_WARNING: "Pamiętaj, że po zmianie tego musisz ręcznie edytować wszystkie karty zamaskowane, które już masz.", diff --git a/src/lang/locale/pt-br.ts b/src/lang/locale/pt-br.ts index 7656563f..caac1f2d 100644 --- a/src/lang/locale/pt-br.ts +++ b/src/lang/locale/pt-br.ts @@ -101,6 +101,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "Converter ==marca-texto== em omissões?", CONVERT_BOLD_TEXT_TO_CLOZES: "Converter **texto em negrito** em omissões?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "Converter {{chaves}} em omissões?", + CLOZE_PATTERNS: "Padrões de Omissão", + CLOZE_PATTERNS_DESC: "Entre os padrões de omissão separados por quebras de linha", INLINE_CARDS_SEPARATOR: "Separador para flashcards inline", FIX_SEPARATORS_MANUALLY_WARNING: "Note que depois de mudar isso você vai ter que manualmente mudar quaisquer flashcards que você tenha.", diff --git a/src/lang/locale/ru.ts b/src/lang/locale/ru.ts index 6a05f222..f2295b08 100644 --- a/src/lang/locale/ru.ts +++ b/src/lang/locale/ru.ts @@ -109,6 +109,8 @@ export default { CONVERT_BOLD_TEXT_TO_CLOZES: "Конвертировать **жирный текст** в пропуски (пример: [...])?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "Конвертировать {{фигурные скобки}} в пропуски (пример: [...])?", + CLOZE_PATTERNS: "Шаблоны пропусков", + CLOZE_PATTERNS_DESC: "Введите шаблоны пропусков, разделенные переводами строк", INLINE_CARDS_SEPARATOR: "Разделитель для внутристрочных карточек", FIX_SEPARATORS_MANUALLY_WARNING: "Внимание! После изменения этого вам придётся вручную редактировать уже существующие карточки", diff --git a/src/lang/locale/zh-cn.ts b/src/lang/locale/zh-cn.ts index d34d01ca..e08698ab 100644 --- a/src/lang/locale/zh-cn.ts +++ b/src/lang/locale/zh-cn.ts @@ -90,6 +90,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "将 ==高亮== 转换为完形填空?", CONVERT_BOLD_TEXT_TO_CLOZES: "将 **粗体** 转换为完形填空?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "将 {{大括号}} 转换为完形填空?", + CLOZE_PATTERNS: "完形填空模式", + CLOZE_PATTERNS_DESC: "输入以换行符分隔的完形填空模式", INLINE_CARDS_SEPARATOR: "单行卡片的分隔符", FIX_SEPARATORS_MANUALLY_WARNING: "注意:更改此选项后你将需要自行更改已存在卡片的分隔符。", INLINE_REVERSED_CARDS_SEPARATOR: "单行翻转卡片的分隔符", diff --git a/src/lang/locale/zh-tw.ts b/src/lang/locale/zh-tw.ts index 6b2dd287..acb107ea 100644 --- a/src/lang/locale/zh-tw.ts +++ b/src/lang/locale/zh-tw.ts @@ -90,6 +90,8 @@ export default { CONVERT_HIGHLIGHTS_TO_CLOZES: "將 ==高亮== 轉換為填空克漏字?", CONVERT_BOLD_TEXT_TO_CLOZES: "將 **粗體** 轉換為填空克漏字?", CONVERT_CURLY_BRACKETS_TO_CLOZES: "將 {{大括號}} 轉換為填空克漏字?", + CLOZE_PATTERNS: "填空克漏字模式", + CLOZE_PATTERNS_DESC: "輸入以換行符分隔的填空克漏字模式", INLINE_CARDS_SEPARATOR: "單行卡片的分隔字元", FIX_SEPARATORS_MANUALLY_WARNING: "注意:更改此選項後你將需要自行更改已存在卡片的分隔字元。", INLINE_REVERSED_CARDS_SEPARATOR: "單行反轉卡片的分隔字元", diff --git a/src/parser.ts b/src/parser.ts index 3cc06542..b2d1d4e7 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -1,3 +1,4 @@ +import { ClozeCrafter } from "clozecraft"; import { CardType } from "./Question"; export class ParsedQuestionInfo { @@ -43,15 +44,14 @@ export function parseEx( singlelineReversedCardSeparator: string, multilineCardSeparator: string, multilineReversedCardSeparator: string, - convertHighlightsToClozes: boolean, - convertBoldTextToClozes: boolean, - convertCurlyBracketsToClozes: boolean, + clozePatterns: string[], ): ParsedQuestionInfo[] { let cardText = ""; const cards: ParsedQuestionInfo[] = []; let cardType: CardType | null = null; let firstLineNo = 0; let lastLineNo = 0; + const clozecrafter = new ClozeCrafter(clozePatterns); const lines: string[] = text.replaceAll("\r\n", "\n").split("\n"); for (let i = 0; i < lines.length; i++) { @@ -96,12 +96,7 @@ export function parseEx( cards.push(new ParsedQuestionInfo(cardType, cardText, firstLineNo, lastLineNo)); cardType = null; cardText = ""; - } else if ( - cardType === null && - ((convertHighlightsToClozes && /==.*?==/gm.test(currentLine)) || - (convertBoldTextToClozes && /\*\*.*?\*\*/gm.test(currentLine)) || - (convertCurlyBracketsToClozes && /{{.*?}}/gm.test(currentLine))) - ) { + } else if (cardType === null && clozecrafter.isClozeNote(currentLine)) { cardType = CardType.Cloze; // Explicitly don't change firstLineNo, as we might not see the cloze markers on the first line diff --git a/src/settings.ts b/src/settings.ts index 3622e73c..d0dba6c0 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -20,6 +20,7 @@ export interface SRSettings { convertHighlightsToClozes: boolean; convertBoldTextToClozes: boolean; convertCurlyBracketsToClozes: boolean; + clozePatterns: string[]; singleLineCardSeparator: string; singleLineReversedCardSeparator: string; multilineCardSeparator: string; @@ -64,6 +65,7 @@ export const DEFAULT_SETTINGS: SRSettings = { convertHighlightsToClozes: true, convertBoldTextToClozes: false, convertCurlyBracketsToClozes: false, + clozePatterns: ["==[123;;]answer[;;hint]=="], singleLineCardSeparator: "::", singleLineReversedCardSeparator: ":::", multilineCardSeparator: "?", @@ -336,8 +338,19 @@ export class SRSettingTab extends PluginSettingTab { toggle .setValue(this.plugin.data.settings.convertHighlightsToClozes) .onChange(async (value) => { + const hightlightPattern = "==[123;;]answer[;;hint]=="; + const clozePatternSet = new Set(this.plugin.data.settings.clozePatterns); + + if (value) { + clozePatternSet.add(hightlightPattern); + } else { + clozePatternSet.delete(hightlightPattern); + } + + this.plugin.data.settings.clozePatterns = [...clozePatternSet]; this.plugin.data.settings.convertHighlightsToClozes = value; await this.plugin.savePluginData(); + this.display(); }), ); @@ -345,8 +358,19 @@ export class SRSettingTab extends PluginSettingTab { toggle .setValue(this.plugin.data.settings.convertBoldTextToClozes) .onChange(async (value) => { + const boldPattern = "**[123;;]answer[;;hint]**"; + const clozePatternSet = new Set(this.plugin.data.settings.clozePatterns); + + if (value) { + clozePatternSet.add(boldPattern); + } else { + clozePatternSet.delete(boldPattern); + } + + this.plugin.data.settings.clozePatterns = [...clozePatternSet]; this.plugin.data.settings.convertBoldTextToClozes = value; await this.plugin.savePluginData(); + this.display(); }), ); @@ -356,8 +380,65 @@ export class SRSettingTab extends PluginSettingTab { toggle .setValue(this.plugin.data.settings.convertCurlyBracketsToClozes) .onChange(async (value) => { + const curlyBracketsPattern = "{{[123;;]answer[;;hint]}}"; + const clozePatternSet = new Set(this.plugin.data.settings.clozePatterns); + + if (value) { + clozePatternSet.add(curlyBracketsPattern); + } else { + clozePatternSet.delete(curlyBracketsPattern); + } + + this.plugin.data.settings.clozePatterns = [...clozePatternSet]; this.plugin.data.settings.convertCurlyBracketsToClozes = value; await this.plugin.savePluginData(); + this.display(); + }), + ); + + new Setting(containerEl) + .setName(t("CLOZE_PATTERNS")) + .setDesc(t("CLOZE_PATTERNS_DESC")) + .addTextArea((text) => + text + .setPlaceholder( + "Example:\n==[123;;]answer[;;hint]==\n**[123;;]answer[;;hint]**\n{{[123;;]answer[;;hint]}}", + ) + .setValue(this.plugin.data.settings.clozePatterns.join("\n")) + .onChange((value) => { + applySettingsUpdate(async () => { + const hightlightPattern = "==[123;;]answer[;;hint]=="; + const boldPattern = "**[123;;]answer[;;hint]**"; + const curlyBracketsPattern = "{{[123;;]answer[;;hint]}}"; + + const clozePatternSet = new Set( + value + .split(/\n+/) + .map((v) => v.trim()) + .filter((v) => v), + ); + + if (clozePatternSet.has(hightlightPattern)) { + this.plugin.data.settings.convertHighlightsToClozes = true; + } else { + this.plugin.data.settings.convertHighlightsToClozes = false; + } + + if (clozePatternSet.has(boldPattern)) { + this.plugin.data.settings.convertBoldTextToClozes = true; + } else { + this.plugin.data.settings.convertBoldTextToClozes = false; + } + + if (clozePatternSet.has(curlyBracketsPattern)) { + this.plugin.data.settings.convertCurlyBracketsToClozes = true; + } else { + this.plugin.data.settings.convertCurlyBracketsToClozes = false; + } + + this.plugin.data.settings.clozePatterns = [...clozePatternSet]; + await this.plugin.savePluginData(); + }); }), ); diff --git a/tests/unit/QuestionType.test.ts b/tests/unit/QuestionType.test.ts index 108c153b..05497a0d 100644 --- a/tests/unit/QuestionType.test.ts +++ b/tests/unit/QuestionType.test.ts @@ -1,5 +1,5 @@ import { CardType } from "src/Question"; -import { CardFrontBack, CardFrontBackUtil, QuestionType_ClozeUtil } from "src/QuestionType"; +import { CardFrontBack, CardFrontBackUtil, QuestionType_ClozeFormatter } from "src/QuestionType"; import { DEFAULT_SETTINGS, SRSettings } from "src/settings"; test("CardType.SingleLineBasic", () => { @@ -37,7 +37,7 @@ test("CardType.MultiLineReversed", () => { }); test("CardType.Cloze", () => { - let frontHtml = QuestionType_ClozeUtil.renderClozeFront(); + const clozeFormatter = new QuestionType_ClozeFormatter(); expect( CardFrontBackUtil.expand( @@ -47,22 +47,24 @@ test("CardType.Cloze", () => { ), ).toEqual([ new CardFrontBack( - "This is a very " + frontHtml + " test", - "This is a very " + QuestionType_ClozeUtil.renderClozeBack("interesting") + " test", + "This is a very " + clozeFormatter.asking() + " test", + "This is a very " + clozeFormatter.showingAnswer("interesting") + " test", ), ]); - let settings2: SRSettings = DEFAULT_SETTINGS; - settings2.convertBoldTextToClozes = true; - settings2.convertHighlightsToClozes = true; - settings2.convertCurlyBracketsToClozes = true; + const settings2: SRSettings = DEFAULT_SETTINGS; + settings2.clozePatterns = [ + "{{[123;;]answer[;;hint]}}", + "==[123;;]answer[;;hint]==", + "**[123;;]answer[;;hint]**", + ]; expect( CardFrontBackUtil.expand(CardType.Cloze, "This is a very **interesting** test", settings2), ).toEqual([ new CardFrontBack( - "This is a very " + frontHtml + " test", - "This is a very " + QuestionType_ClozeUtil.renderClozeBack("interesting") + " test", + "This is a very " + clozeFormatter.asking() + " test", + "This is a very " + clozeFormatter.showingAnswer("interesting") + " test", ), ]); @@ -70,8 +72,8 @@ test("CardType.Cloze", () => { CardFrontBackUtil.expand(CardType.Cloze, "This is a very {{interesting}} test", settings2), ).toEqual([ new CardFrontBack( - "This is a very " + frontHtml + " test", - "This is a very " + QuestionType_ClozeUtil.renderClozeBack("interesting") + " test", + "This is a very " + clozeFormatter.asking() + " test", + "This is a very " + clozeFormatter.showingAnswer("interesting") + " test", ), ]); @@ -83,16 +85,24 @@ test("CardType.Cloze", () => { ), ).toEqual([ new CardFrontBack( - "This is a really very [...] and fascinating and great test", - "This is a really very interesting and fascinating and great test", + "This is a really very " + clozeFormatter.asking() + " and fascinating and great test", + "This is a really very " + + clozeFormatter.showingAnswer("interesting") + + " and fascinating and great test", ), new CardFrontBack( - "This is a really very interesting and [...] and great test", - "This is a really very interesting and fascinating and great test", + "This is a really very interesting and " + clozeFormatter.asking() + " and great test", + "This is a really very interesting and " + + clozeFormatter.showingAnswer("fascinating") + + " and great test", ), new CardFrontBack( - "This is a really very interesting and fascinating and [...] test", - "This is a really very interesting and fascinating and great test", + "This is a really very interesting and fascinating and " + + clozeFormatter.asking() + + " test", + "This is a really very interesting and fascinating and " + + clozeFormatter.showingAnswer("great") + + " test", ), ]); }); diff --git a/tests/unit/parser.test.ts b/tests/unit/parser.test.ts index 9d2c7b6f..0b44075a 100644 --- a/tests/unit/parser.test.ts +++ b/tests/unit/parser.test.ts @@ -1,14 +1,12 @@ import { parseEx, ParsedQuestionInfo } from "src/parser"; import { CardType } from "src/Question"; -const defaultArgs: [string, string, string, string, boolean, boolean, boolean] = [ +const defaultArgs: [string, string, string, string, string[]] = [ "::", ":::", "?", "??", - true, - true, - true, + ["==[123;;]answer[;;hint]==", "**[123;;]answer[;;hint]**", "{{[123;;]answer[;;hint]}}"], ]; /** @@ -22,9 +20,7 @@ function parse( singlelineReversedCardSeparator: string, multilineCardSeparator: string, multilineReversedCardSeparator: string, - convertHighlightsToClozes: boolean, - convertBoldTextToClozes: boolean, - convertCurlyBracketsToClozes: boolean, + clozePatterns: string[], ): [CardType, string, number, number][] { const list: ParsedQuestionInfo[] = parseEx( text, @@ -32,9 +28,7 @@ function parse( singlelineReversedCardSeparator, multilineCardSeparator, multilineReversedCardSeparator, - convertHighlightsToClozes, - convertBoldTextToClozes, - convertCurlyBracketsToClozes, + clozePatterns, ); const result: [CardType, string, number, number][] = []; for (const item of list) { @@ -162,9 +156,9 @@ test("Test parsing of cloze cards", () => { expect(parse("lorem ipsum ==p\ndolor won==", ...defaultArgs)).toEqual([]); expect(parse("lorem ipsum ==dolor won=", ...defaultArgs)).toEqual([]); // ==highlights== turned off - expect(parse("cloze ==deletion== test", "::", ":::", "?", "??", false, true, false)).toEqual( - [], - ); + expect( + parse("cloze ==deletion== test", "::", ":::", "?", "??", ["**[123;;]answer[;;hint]**"]), + ).toEqual([]); // **bolded** expect(parse("cloze **deletion** test", ...defaultArgs)).toEqual([ @@ -193,9 +187,9 @@ test("Test parsing of cloze cards", () => { expect(parse("lorem ipsum **p\ndolor won**", ...defaultArgs)).toEqual([]); expect(parse("lorem ipsum **dolor won*", ...defaultArgs)).toEqual([]); // **bolded** turned off - expect(parse("cloze **deletion** test", "::", ":::", "?", "??", true, false, false)).toEqual( - [], - ); + expect( + parse("cloze **deletion** test", "::", ":::", "?", "??", ["==[123;;]answer[;;hint]=="]), + ).toEqual([]); // both expect(parse("cloze **deletion** test ==another deletion==!", ...defaultArgs)).toEqual([