-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathcore.ts
More file actions
288 lines (243 loc) · 10.9 KB
/
core.ts
File metadata and controls
288 lines (243 loc) · 10.9 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
import { App, TFile } from "obsidian";
import { RepItemScheduleInfo } from "src/algorithms/base/rep-item-schedule-info";
import { ReviewResponse } from "src/algorithms/base/repetition-item";
import { SrsAlgorithm } from "src/algorithms/base/srs-algorithm";
import { IOsrVaultNoteLinkInfoFinder } from "src/algorithms/osr/obsidian-vault-notelink-info-finder";
import { OsrNoteGraph } from "src/algorithms/osr/osr-note-graph";
import { FlashcardReviewMode } from "src/card/flashcard-review-sequencer";
import { QuestionPostponementList } from "src/card/questions/question-postponement-list";
import { Deck, DeckTreeFilter } from "src/deck/deck";
import { DeckTreeStatsCalculator } from "src/deck/deck-tree-stats-calculator";
import { Stats } from "src/deck/stats";
import { TopicPath } from "src/deck/topic-path";
import { CardDueDateHistogram, NoteDueDateHistogram } from "src/due-date-histogram";
import { ISRFile, SrTFile } from "src/file";
import { Note } from "src/note/note";
import { NoteFileLoader } from "src/note/note-file-loader";
import { NoteReviewQueue } from "src/note/note-review-queue";
import { SettingsUtil, SRSettings } from "src/settings";
import { globalDateProvider, IDayBoundary } from "src/utils/dates";
import { TextDirection } from "src/utils/strings";
export interface IOsrVaultEvents {
dataChanged: () => void;
}
export class OsrCore {
public defaultTextDirection: TextDirection;
protected settings: SRSettings;
private dataChangedHandler: () => void;
protected osrNoteGraph: OsrNoteGraph;
private osrNoteLinkInfoFinder: IOsrVaultNoteLinkInfoFinder;
private _questionPostponementList: QuestionPostponementList;
private _noteReviewQueue: NoteReviewQueue;
private fullDeckTree: Deck;
private _reviewableDeckTree: Deck = new Deck("root", null);
private _remainingDeckTree: Deck;
private _cardStats: Stats;
private _dueDateFlashcardHistogram: CardDueDateHistogram;
private _dueDateNoteHistogram: NoteDueDateHistogram;
get noteReviewQueue(): NoteReviewQueue {
return this._noteReviewQueue;
}
get remainingDeckTree(): Deck {
return this._remainingDeckTree;
}
get reviewableDeckTree(): Deck {
return this._reviewableDeckTree;
}
get questionPostponementList(): QuestionPostponementList {
return this._questionPostponementList;
}
get dueDateFlashcardHistogram(): CardDueDateHistogram {
return this._dueDateFlashcardHistogram;
}
get dueDateNoteHistogram(): NoteDueDateHistogram {
return this._dueDateNoteHistogram;
}
get cardStats(): Stats {
return this._cardStats;
}
init(
questionPostponementList: QuestionPostponementList,
osrNoteLinkInfoFinder: IOsrVaultNoteLinkInfoFinder,
settings: SRSettings,
dataChangedHandler: () => void,
noteReviewQueue: NoteReviewQueue,
): void {
this.settings = settings;
this.osrNoteLinkInfoFinder = osrNoteLinkInfoFinder;
this.dataChangedHandler = dataChangedHandler;
this._noteReviewQueue = noteReviewQueue;
this._questionPostponementList = questionPostponementList;
this._dueDateFlashcardHistogram = new CardDueDateHistogram();
this._dueDateNoteHistogram = new NoteDueDateHistogram();
try {
const startOfDayElements: string[] = this.settings.startOfDay.split(":");
if (startOfDayElements.length !== 3) {
throw new Error("Invalid format for start of day");
}
const dayBoundary: IDayBoundary = {
hour: parseInt(startOfDayElements[0]),
minute: parseInt(startOfDayElements[1]),
second: parseInt(startOfDayElements[2]),
};
globalDateProvider.setDayBoundary(dayBoundary);
} catch (e) {
console.error("Invalid format for start of day", e);
}
}
protected loadInit(): void {
// reset notes stuff
this.osrNoteGraph = new OsrNoteGraph(this.osrNoteLinkInfoFinder);
this._noteReviewQueue.init();
// reset flashcards stuff
this.fullDeckTree = new Deck("root", null);
}
protected async processFile(noteFile: ISRFile): Promise<void> {
const schedule: RepItemScheduleInfo = await noteFile.getNoteSchedule();
let note: Note | null = null;
// Update the graph of links between notes
// (Performance note: This only requires accessing Obsidian's metadata cache and not loading the file)
this.osrNoteGraph.processLinks(noteFile.path);
const tags = noteFile.getAllTagsFromCache();
// Does the note contain any tags that are specified as flashcard tags in the settings
// (Doing this check first saves us from loading and parsing the note if not necessary)
const topicPath: TopicPath = this.findTopicPath(noteFile);
if (topicPath.hasPath && !SettingsUtil.isAnyTagIgnoredForFlashcards(this.settings, tags)) {
note = await this.loadNote(noteFile, topicPath);
if (note !== null) note.appendCardsToDeck(this.fullDeckTree);
}
// Give the algorithm a chance to do something with the loaded note
// e.g. OSR - calculate the average ease across all the questions within the note
// TODO: should this move to this.loadNote
SrsAlgorithm.getInstance().noteOnLoadedNote(noteFile.path, note, schedule?.latestEase);
const matchedNoteTags = SettingsUtil.filterForNoteReviewTag(this.settings, tags);
if (matchedNoteTags.length === 0) {
return;
}
if (SettingsUtil.isAnyTagIgnoredForNotes(this.settings, tags)) {
return;
}
const noteSchedule: RepItemScheduleInfo = await noteFile.getNoteSchedule();
this._noteReviewQueue.addNoteToQueue(noteFile, noteSchedule, matchedNoteTags);
}
protected finalizeLoad(): void {
this.osrNoteGraph.generatePageRanks();
// Reviewable cards are all except those with the "edit later" tag
this._reviewableDeckTree = DeckTreeFilter.filterForReviewableCards(this.fullDeckTree);
// sort the deck names
this._reviewableDeckTree.sortSubdecksList();
this._remainingDeckTree = DeckTreeFilter.filterForRemainingCards(
this._questionPostponementList,
this._reviewableDeckTree,
FlashcardReviewMode.Review,
);
const calc: DeckTreeStatsCalculator = new DeckTreeStatsCalculator();
this._cardStats = calc.calculate(this._reviewableDeckTree);
// Generate the histogram for the due dates for (1) all the notes (2) all the cards
this.calculateDerivedInfo();
this._dueDateFlashcardHistogram.calculateFromDeckTree(this._reviewableDeckTree);
// Tell the interested party that the data has changed
if (this.dataChangedHandler) this.dataChangedHandler();
}
async saveNoteReviewResponse(
noteFile: ISRFile,
response: ReviewResponse,
settings: SRSettings,
): Promise<void> {
// Get the current schedule for the note (null if new note)
const originalNoteSchedule: RepItemScheduleInfo = await noteFile.getNoteSchedule();
// Calculate the new/updated schedule
let noteSchedule: RepItemScheduleInfo;
if (originalNoteSchedule === null) {
noteSchedule = SrsAlgorithm.getInstance().noteCalcNewSchedule(
noteFile.path,
this.osrNoteGraph,
response,
this._dueDateNoteHistogram,
);
} else {
noteSchedule = SrsAlgorithm.getInstance().noteCalcUpdatedSchedule(
noteFile.path,
originalNoteSchedule,
response,
this._dueDateNoteHistogram,
);
}
// Store away the new schedule info
await noteFile.setNoteSchedule(noteSchedule);
// Generate the histogram for the due dates for all the notes
// (This could be optimized to make the small adjustments to the histogram, but simpler to implement
// by recalculating from scratch)
this._noteReviewQueue.updateScheduleInfo(noteFile, noteSchedule);
this.calculateDerivedInfo();
// If configured in the settings, bury all cards within the note
await this.buryAllCardsInNote(settings, noteFile);
// Tell the interested party that the data has changed
if (this.dataChangedHandler) this.dataChangedHandler();
}
private calculateDerivedInfo(): void {
const todayUnix: number = globalDateProvider.today.valueOf();
this.noteReviewQueue.calcDueNotesCount(todayUnix);
this._dueDateNoteHistogram.calculateFromReviewDecksAndSort(
this.noteReviewQueue.reviewDecks,
this.osrNoteGraph,
);
}
private async buryAllCardsInNote(settings: SRSettings, noteFile: ISRFile): Promise<void> {
if (settings.burySiblingCards) {
const topicPath: TopicPath = this.findTopicPath(noteFile);
const noteX: Note | null = await this.loadNote(noteFile, topicPath);
if (noteX !== null && noteX.questionList.length > 0) {
for (const question of noteX.questionList) {
this._questionPostponementList.add(question);
}
await this._questionPostponementList.write();
}
}
}
async loadNote(noteFile: ISRFile, topicPath: TopicPath): Promise<Note | null> {
const loader: NoteFileLoader = new NoteFileLoader(this.settings);
const note: Note | null = await loader.load(noteFile, this.defaultTextDirection, topicPath);
if (note !== null && note.hasChanged) {
await note.writeNoteFile(this.settings);
}
return note;
}
private findTopicPath(note: ISRFile): TopicPath {
return TopicPath.getTopicPathOfFile(note, this.settings);
}
}
export class OsrAppCore extends OsrCore {
private app: App;
private _syncLock = false;
get syncLock(): boolean {
return this._syncLock;
}
constructor(app: App) {
super();
this.app = app;
}
async loadVault(): Promise<void> {
if (this._syncLock) {
return;
}
this._syncLock = true;
try {
this.loadInit();
const notes: TFile[] = this.app.vault.getMarkdownFiles();
for (const noteFile of notes) {
if (SettingsUtil.isPathInNoteIgnoreFolder(this.settings, noteFile.path)) {
continue;
}
const file: SrTFile = this.createSrTFile(noteFile);
await this.processFile(file);
}
this.finalizeLoad();
} finally {
this._syncLock = false;
}
}
createSrTFile(note: TFile): SrTFile {
return new SrTFile(this.app.vault, this.app.metadataCache, this.app.fileManager, note);
}
}