generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.ts
414 lines (365 loc) · 14.5 KB
/
main.ts
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import { App, ButtonComponent, Modal, Notice, Plugin, PluginSettingTab, Setting, TextComponent } from 'obsidian';
import { createDailyNote, getAllDailyNotes, getDailyNote, getDailyNoteSettings } from 'obsidian-daily-notes-interface';
interface IReviewSettings {
dailyNotesFolder: string;
reviewSectionHeading: string;
linePrefix: string;
headingPrefix: string;
defaultReviewDate: string;
blockLinePrefix: string;
}
const DEFAULT_SETTINGS: IReviewSettings = {
dailyNotesFolder: "",
reviewSectionHeading: "## Review",
linePrefix: "- ",
headingPrefix: "",
defaultReviewDate: "tomorrow",
blockLinePrefix: "!",
}
enum ReviewType {
Note,
Block,
Heading,
}
export default class Review extends Plugin {
settings: IReviewSettings;
async onload() {
console.log('Loading the Review plugin v1.6.5.');
this.settings = Object.assign({}, DEFAULT_SETTINGS, (await this.loadData()))
if (this.app.workspace.layoutReady) {
this.onLayoutReady();
} else {
this.app.workspace.on("layout-ready", this.onLayoutReady.bind(this));
}
this.addCommand({
id: 'future-review',
name: 'Add this note to a daily note for review',
checkCallback: (checking: boolean) => { // If a note is currently active, open the plugin's modal to receive a date string.
let leaf = this.app.workspace.activeLeaf;
if (leaf) {
if (!checking) {
new ReviewModal(this.app, ReviewType.Note).open();
}
return true;
}
return false;
}
});
this.addCommand({
id: 'future-review-block',
name: 'Add this block to a daily note for review',
checkCallback: (checking: boolean) => {
let leaf = this.app.workspace.activeLeaf;
if (leaf) {
if (!checking) {
new ReviewModal(this.app, ReviewType.Block).open();
}
return true;
}
return false;
}
});
this.addCommand({
id: 'future-review-heading',
name: 'Add this heading to a daily note for review',
checkCallback: (checking: boolean) => {
let leaf = this.app.workspace.activeLeaf;
if (leaf) {
if (!checking) {
new ReviewModal(this.app, ReviewType.Heading).open();
}
return true;
}
return false;
}
});
this.addSettingTab(new ReviewSettingTab(this.app, this));
}
onLayoutReady() {
// Check for the Natural Language Dates plugin after all the plugins are loaded.
// If not found, tell the user to install it/initialize it.
let naturalLanguageDates = (<any>this.app).plugins.getPlugin('nldates-obsidian');
if (!naturalLanguageDates) {
new Notice("The Natural Language Dates plugin was not found. The Review plugin requires the Natural Language Dates plugin. Please install it first and make sure it is enabled before using Review.");
}
}
onunload() {
console.log('The Review Dates plugin has been disabled and unloaded.');
}
createBlockHash(inputText: string): string { // Credit to https://stackoverflow.com/a/1349426
let result = '';
var characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < 7; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
getBlock(inputLine: string, noteFile: object): string { //Returns the string of a block ID if block is found, or "" if not.
let obsidianApp = this.app;
let noteBlocks = obsidianApp.metadataCache.getFileCache(noteFile).blocks;
console.log("Checking if line '" + inputLine + "' is a block.");
let blockString = "";
if (noteBlocks) { // the file does contain blocks. If not, return ""
for (let eachBlock in noteBlocks) { // iterate through the blocks.
console.log("Checking block ^" + eachBlock);
let blockRegExp = new RegExp("(" + eachBlock + ")$", "gim");
if (inputLine.match(blockRegExp)) { // if end of inputLine matches block, return it
blockString = eachBlock;
console.log("Found block ^" + blockString);
return blockString;
}
}
return blockString;
}
return blockString;
}
async setReviewDate(reviewDate: string, reviewType: ReviewType) {
let obsidianApp = this.app;
let naturalLanguageDates = obsidianApp.plugins.getPlugin('nldates-obsidian'); // Get the Natural Language Dates plugin.
let notesFolder = await getDailyNoteSettings().folder;
if (!naturalLanguageDates) {
new Notice("The Natural Language Dates plugin is not available. Please make sure it is installed and enabled before trying again.");
return;
}
if (reviewDate === "") {
reviewDate = this.settings.defaultReviewDate;
}
// Use the Natural Language Dates plugin's processDate method to convert the input date into a daily note title.
let parsedResult = naturalLanguageDates.parseDate(reviewDate);
let inputDate = parsedResult.formattedString;
console.debug("Date string to use: " + inputDate);
// Get the folder path.
let notesPath = "";
if (notesFolder === "") {
notesPath = "/"; // If the user is using the root for their daily notes, don't add a second /.
} else {
notesPath = "/" + notesFolder + "/";
}
console.debug("The path to daily notes: " + notesPath);
// Get the review section header.
let reviewHeading = this.settings.reviewSectionHeading;
console.debug("The review section heading is: " + reviewHeading);
// Get the line prefix.
let reviewLinePrefix = this.settings.linePrefix;
console.debug("The line prefix is: " + reviewLinePrefix);
// If the date is recognized and valid
if (parsedResult.moment.isValid()) {
// get the current note name
let noteName = obsidianApp.workspace.activeLeaf.getDisplayText();
let noteFile = obsidianApp.workspace.activeLeaf.view.file;
let noteLink = obsidianApp.metadataCache.fileToLinktext(noteFile, noteFile.path, true);
switch (reviewType) {
case ReviewType.Note:
break;
case ReviewType.Block:
let editor = this.app.workspace.activeLeaf.view.sourceMode.cmEditor;
let cursor = editor.getCursor();
let lineText = editor.getLine(cursor.line);
if (lineText != undefined) {
console.log("Checking for block:");
let lineBlockID = this.getBlock(lineText, noteFile);
console.debug(lineBlockID);
if (this.getBlock(lineText, noteFile) === "") { // The line is not already a block
console.debug("This line is not currently a block. Adding a block ID.");
lineBlockID = this.createBlockHash(lineText).toString();
let lineWithBlock = lineText + " ^" + lineBlockID;
obsidianApp.vault.read(noteFile).then(function (result) {
let previousNoteText = result;
let newNoteText = previousNoteText.replace(lineText, lineWithBlock);
obsidianApp.vault.modify(noteFile, newNoteText);
});
}
noteLink = noteLink + "#^" + lineBlockID;
reviewLinePrefix = this.settings.blockLinePrefix;
}
break;
case ReviewType.Heading:
let heading = this.findHeadingOfLine();
if (heading) {
heading = heading.replace(/^#(#*) /gm, "");
noteLink = noteLink + "#" + heading;
reviewLinePrefix = this.settings.headingPrefix;
}
break;
default:
break;
}
let dailyNotes = getAllDailyNotes();
let dateFile = getDailyNote(parsedResult.moment, dailyNotes);
console.debug("File found:" + dateFile);
if (!dateFile) { //the date file does not already exist
console.debug("The daily note for the given date does not exist yet. Creating it, then appending the review section.")
let noteText = reviewHeading + "\n" + reviewLinePrefix + "[[" + noteLink + "]]";
// let newDateFile = obsidianApp.vault.create(notesPath + inputDate + ".md", noteText); //previous approach
let newDateFile = await createDailyNote(parsedResult.moment); // Use @liamcain's obsidian-daily-notes-interface to create a daily note with core-defined templates
let templateText = await obsidianApp.vault.read(newDateFile);
//console.log(templateText); // for debugging
if (templateText.includes(reviewHeading)) {
noteText = templateText.replace(reviewHeading, noteText);
} else {
noteText = templateText + "\n" + noteText;
}
obsidianApp.vault.modify(newDateFile, noteText);
new Notice("Set note \"" + noteName + "\" for review on " + inputDate + ".");
} else {
console.debug("The daily note already exists for the date given. Adding this note to it for review.")
let previousNoteText = "";
obsidianApp.vault.read(dateFile).then(function (result) { // Get the text in the note. Search it for ## Review and append to that section. Else, append ## Review and the link to the note for review.
previousNoteText = result;
console.log("Previous Note text:\n" + previousNoteText);
let newNoteText = "";
if (previousNoteText.includes(reviewHeading)) {
newNoteText = previousNoteText.replace(reviewHeading, reviewHeading + "\n" + reviewLinePrefix + "[[" + noteLink + "]]");
} else {
newNoteText = previousNoteText + "\n" + reviewHeading + "\n" + reviewLinePrefix + "[[" + noteLink + "]]";
}
obsidianApp.vault.modify(dateFile, newNoteText);
new Notice("Set note \"" + noteName + "\" for review on " + inputDate + ".");
});
}
} else {
new Notice("You've entered an invalid date (note that \"two weeks\" will not work, but \"in two weeks\" will). The note was not set for review. Please try again.");
}
return;
}
lookupOffset(string: string, regex: RegExp, offset?: number) : number {
regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiline ? "m" : ""));
if (typeof (offset) == "undefined") {
offset = string.length;
} else if(offset < 0) {
offset = 0;
}
var stringToWorkWith = string.substring(0, offset + 1);
var lastIndexOf = -1;
var nextStop = 0;
var result;
while((result = regex.exec(stringToWorkWith)) != null) {
lastIndexOf = result.index;
regex.lastIndex = ++nextStop;
}
return lastIndexOf;
}
findHeadingOfLine() : string | undefined {
let editor = this.app.workspace.activeLeaf.view.sourceMode.cmEditor;
let cursor = editor.getCursor();
cursor.ch = editor.getLine(cursor.line).length;
const cursorOffset = editor.posToOffset(cursor);
let headingOffset = this.lookupOffset(editor.getValue(), /^#(#*) /gm, cursorOffset);
// If not found from the cursor position, return undefined
if (headingOffset === -1) {
return undefined;
}
return editor.getLine(editor.offsetToPos(headingOffset).line);
}
}
class ReviewModal extends Modal {
reviewType: ReviewType;
constructor(app: App, reviewType: ReviewType) {
super(app);
this.reviewType = reviewType;
}
onOpen() {
let _this = this;
console.debug(_this);
let { contentEl } = this;
let inputDateField = new TextComponent(contentEl)
.setPlaceholder(this.app.plugins.getPlugin("review-obsidian").settings.defaultReviewDate);
let inputButton = new ButtonComponent(contentEl)
.setButtonText("Set Review Date")
.onClick(() => {
let inputDate = inputDateField.getValue();
_this.app.plugins.getPlugin("review-obsidian").setReviewDate(inputDate, _this.reviewType);
this.close();
});
inputDateField.inputEl.focus();
inputDateField.inputEl.addEventListener('keypress', function (keypressed) {
if (keypressed.key === 'Enter') {
var inputDate = inputDateField.getValue()
_this.app.plugins.getPlugin("review-obsidian").setReviewDate(inputDate, _this.reviewType);
_this.close();
}
});
}
onClose() {
let { contentEl } = this;
contentEl.empty();
}
}
class ReviewSettingTab extends PluginSettingTab {
display(): void {
let { containerEl } = this;
const plugin: any = (this as any).plugin;
containerEl.empty();
containerEl.createEl('h2', { text: 'Review Settings' });
new Setting(containerEl)
.setName('Review section heading')
.setDesc('Set the heading to use for the review section. BE CAREFUL: it must be unique in each daily note.')
.addText((text) =>
text
.setPlaceholder('## Review')
.setValue(plugin.settings.reviewSectionHeading)
.onChange((value) => {
if (value === "") {
plugin.settings.reviewSectionHeading = "## Review";
} else {
plugin.settings.reviewSectionHeading = value;
}
plugin.saveData(plugin.settings);
})
);
new Setting(containerEl)
.setName('Line prefix')
.setDesc('Set the prefix to use on each new line. E.g., use `- ` for bullets or `- [ ] ` for tasks. **Include the trailing space.**')
.addText((text) =>
text
.setPlaceholder('- ')
.setValue(plugin.settings.linePrefix)
.onChange((value) => {
plugin.settings.linePrefix = value;
plugin.saveData(plugin.settings);
})
);
new Setting(containerEl)
.setName('Heading prefix')
.setDesc('Set the prefix to use for reviewed headings. You probably want this to be a - bulleted list item or an ! embed.')
.addText((text) =>
text
.setPlaceholder('- ')
.setValue(plugin.settings.headingPrefix)
.onChange((value) => {
plugin.settings.headingPrefix = value;
plugin.saveData(plugin.settings);
})
);
new Setting(containerEl)
.setName('Block review line prefix')
.setDesc('Set the prefix used when adding blocks to daily notes with Review. Use e.g., `- [ ] ` to link the block as a task, or `!` to create embeds.')
.addText((text) =>
text
.setPlaceholder('!')
.setValue(plugin.settings.blockLinePrefix)
.onChange((value) => {
plugin.settings.blockLinePrefix = value;
plugin.saveData(plugin.settings);
})
);
new Setting(containerEl)
.setName('Default review date')
.setDesc('Set a default date to be used when no date is entered. Use natural language: "Next Monday", "November 5th", and "tomorrow" all work.')
.addText((text) =>
text
.setPlaceholder('')
.setValue(plugin.settings.defaultReviewDate)
.onChange((value) => {
plugin.settings.defaultReviewDate = value;
plugin.saveData(plugin.settings);
})
);
// containerEl.createEl('h3', { text: 'Preset review schedules' });
/*
TKTKTK: Figure out how to add a function to a button inside the setting element. Currently `doSomething`, below, throws errors.
containerEl.createEl('button', { text: "Add a new review schedule preset", attr: { onclick: "doSomething({ console.log('button clicked') });"}});
*/
}
}