Skip to content

Commit

Permalink
Trying to improve the structure.
Browse files Browse the repository at this point in the history
  • Loading branch information
alberti42 committed Aug 16, 2024
1 parent 0e35b5b commit f33cfeb
Show file tree
Hide file tree
Showing 6 changed files with 118 additions and 73 deletions.
6 changes: 1 addition & 5 deletions src/NoteQuestionParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,7 @@ export class NoteQuestionParser {

private parseQuestions(): ParsedQuestionInfo[] {
// We pass contentText which has the frontmatter blanked out; see extractFrontmatter for reasoning
const settings: SRSettings = this.settings;
const result: ParsedQuestionInfo[] = parseEx(
this.contentText,
settings
);
const result: ParsedQuestionInfo[] = parseEx(this.contentText);
return result;
}

Expand Down
14 changes: 9 additions & 5 deletions src/generateParser.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// generateParser.ts

import { SRSettings } from "./settings";
import { generate } from "peggy";
import { setParser } from "./parser";
import { generate, Parser } from "peggy";
import { setDefaultParser } from "./parser";

export function generateParser(settings: SRSettings): void {
export function generateParser(settings: SRSettings): Parser {

if(settings === null) throw Error("Something went wrong. The variable 'settings' was not initialized yet.");

const close_rules_list: string[] = [];

Expand Down Expand Up @@ -219,11 +221,13 @@ _ = ([ \\f\\t\\v\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f
`;

if (settings.showDebugMessages) {
console.log(grammar);
// console.log(grammar);
}

// const t0 = Date.now();
setParser(generate(grammar));
const parser = generate(grammar);
// const t1 = Date.now();
// console.log("To generate the parser, it took " + (t1 - t0) + " milliseconds.")

return parser;
}
5 changes: 4 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import { TextDirection } from "./util/TextDirection";
import { convertToStringOrEmpty } from "./util/utils";
import { isEqualOrSubPath } from "./util/utils";
import { generateParser } from "./generateParser";
import { setDefaultParser } from "./parser";

interface PluginData {
settings: SRSettings;
Expand Down Expand Up @@ -104,6 +105,8 @@ export default class SRPlugin extends Plugin {
this.data.buryList,
);

provideSettings(this.data.settings);

appIcon();

this.statusBar = this.addStatusBarItem();
Expand Down Expand Up @@ -821,7 +824,7 @@ export default class SRPlugin extends Plugin {
}

this.debouncedGenerateParserTimeout = window.setTimeout(async () => {
generateParser(this.data.settings);
setDefaultParser(generateParser(this.data.settings));
this.debouncedGenerateParserTimeout = null;
}, timeout_ms);
}
Expand Down
33 changes: 19 additions & 14 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import { Parser } from "peggy";
import { SRSettings } from "./settings";
import { generateParser } from "./generateParser";

let parser: Parser | null = null;
let defaultParser: Parser | null = null;

export function setParser(p: Parser): void {
parser = p;
// console.log(parser);
let defaultSettings: SRSettings | null = null;

export function provideSettings(providedSettings: SRSettings): void {
// we provides the plugin settings as a reference which is stored in the module
defaultSettings = providedSettings;
}

export class ParsedQuestionInfo {
Expand All @@ -31,32 +33,35 @@ export class ParsedQuestionInfo {
}
}

export function setDefaultParser(parser: Parser): void {
defaultParser = parser;
}

/**
* Returns flashcards found in `text`
*
* It is best that the text does not contain frontmatter, see extractFrontmatter for reasoning
*
* Multi-line question with blank lines user workaround:
* As of 3/04/2024 there is no support for including blank lines within multi-line questions
* As a workaround, one user uses a zero width Unicode character - U+200B
* https://github.com/st3v3nmw/obsidian-spaced-repetition/issues/915#issuecomment-2031003092
*
* @param text - The text to extract flashcards from
* @param settings - Plugin's settings
* @returns An array of [CardType, card text, line number] tuples
*/
export function parseEx(
text: string,
settings: SRSettings,
force_parser_generation = false
parser?: Parser,
): ParsedQuestionInfo[] {
// let cardText = "";
let cards: ParsedQuestionInfo[] = [];

if(force_parser_generation || parser === null) {
generateParser(settings);
if(parser === undefined) {
// if parser is not provided explicitly, use the parser configured
// with the plugin settings provided by the user
if(defaultParser === null) {
defaultParser = generateParser(defaultSettings);
}
parser = defaultParser;
}

// Use this function when you call the parse method
try {
cards = parser.parse(text + "\n\n\n", {
Expand Down
44 changes: 41 additions & 3 deletions tests/unit/FlashcardReviewSequencer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,40 @@ describe("updateCurrentQuestionText", () => {

describe("Checking update to file", () => {
describe("Single line card type; Settings - schedule on following line", () => {

test("Question starts line after tag (single space after tag before newline); New card", async () => {
let originalQuestionStr: string = `#flashcards${space}
Q2
?
A2`;

let fileText: string = `
${originalQuestionStr}
#flashcards Q1::A1
#flashcards Q3::A3`;

let updatedQuestionText: string = `Multiline question
Question starting immediately after tag
?
A2 (answer now includes more detail)
extra answer line 2`;

let expectedUpdatedStr: string = `#flashcards
${updatedQuestionText}`;

await checkUpdateCurrentQuestionText(
fileText,
updatedQuestionText,
originalQuestionStr,
expectedUpdatedStr,
DEFAULT_SETTINGS,
);
});

return;

test("Question has schedule on following line before/after update", async () => {
let text: string = `
#flashcards Q1::A1
Expand Down Expand Up @@ -802,7 +836,7 @@ describe("updateCurrentQuestionText", () => {
);
});
});

return;
describe("Single line card type; Settings - schedule on same line", () => {
let settings: SRSettings = { ...DEFAULT_SETTINGS };
settings.cardCommentOnSameLine = true;
Expand Down Expand Up @@ -1152,7 +1186,7 @@ async function checkUpdateCurrentQuestionText(
updatedStr: string,
settings: SRSettings,
): Promise<TestContext> {
let c: TestContext = TestContext.Create(
const c: TestContext = TestContext.Create(
order_DueFirst_Sequential,
FlashcardReviewMode.Review,
settings,
Expand All @@ -1165,7 +1199,11 @@ async function checkUpdateCurrentQuestionText(

// originalText should remain the same except for the specific substring change from originalStr => updatedStr
if (!c.originalText.includes(originalStr)) throw `Text not found: ${originalStr}`;
let expectedFileText: string = c.originalText.replace(originalStr, updatedStr);
const expectedFileText: string = c.originalText.replace(originalStr, updatedStr);
console.log("<<<"+await c.file.read()+">>>");
console.log("Original string:<<<"+originalStr+">>>");
console.log("Updated string:<<<"+updatedStr+">>>");
console.log("<<<"+expectedFileText+">>>");
expect(await c.file.read()).toEqual(expectedFileText);
return c;
}
Loading

0 comments on commit f33cfeb

Please sign in to comment.