-
-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathCaptureChoiceEngine.ts
More file actions
581 lines (501 loc) · 18 KB
/
CaptureChoiceEngine.ts
File metadata and controls
581 lines (501 loc) · 18 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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
import { Notice, type App, type TFile } from "obsidian";
import InputSuggester from "src/gui/InputSuggester/inputSuggester";
import invariant from "src/utils/invariant";
import merge from "three-way-merge";
import type { IChoiceExecutor } from "../IChoiceExecutor";
import {
QA_INTERNAL_CAPTURE_TARGET_FILE_PATH,
VALUE_SYNTAX,
} from "../constants";
import { CaptureChoiceFormatter } from "../formatters/captureChoiceFormatter";
import { log } from "../logger/logManager";
import type QuickAdd from "../main";
import type ICaptureChoice from "../types/choices/ICaptureChoice";
import { normalizeAppendLinkOptions, type AppendLinkOptions } from "../types/linkPlacement";
import {
appendToCurrentLine,
getMarkdownFilesInFolder,
getMarkdownFilesWithTag,
insertFileLinkToActiveView,
insertOnNewLineAbove,
insertOnNewLineBelow,
isTemplaterTriggerOnCreateEnabled,
jumpToNextTemplaterCursorIfPossible,
isFolder,
openExistingFileTab,
openFile,
overwriteTemplaterOnce,
templaterParseTemplate,
waitForTemplaterTriggerOnCreateToComplete,
} from "../utilityObsidian";
import { isCancellationError, reportError } from "../utils/errorUtils";
import { normalizeFileOpening } from "../utils/fileOpeningDefaults";
import { QuickAddChoiceEngine } from "./QuickAddChoiceEngine";
import { ChoiceAbortError } from "../errors/ChoiceAbortError";
import { MacroAbortError } from "../errors/MacroAbortError";
import { SingleTemplateEngine } from "./SingleTemplateEngine";
import { getCaptureAction, type CaptureAction } from "./captureAction";
import { handleMacroAbort } from "../utils/macroAbortHandler";
const DEFAULT_NOTICE_DURATION = 4000;
export class CaptureChoiceEngine extends QuickAddChoiceEngine {
choice: ICaptureChoice;
private formatter: CaptureChoiceFormatter;
private readonly plugin: QuickAdd;
private templatePropertyVars?: Map<string, unknown>;
private capturePropertyVars: Map<string, unknown> = new Map();
constructor(
app: App,
plugin: QuickAdd,
choice: ICaptureChoice,
private choiceExecutor: IChoiceExecutor,
) {
super(app);
this.choice = choice;
this.plugin = plugin;
this.formatter = new CaptureChoiceFormatter(app, plugin, choiceExecutor);
}
private showSuccessNotice(
file: TFile,
{ wasNewFile, action }: { wasNewFile: boolean; action: CaptureAction },
) {
const fileName = `'${file.basename}'`;
if (wasNewFile) {
new Notice(
`Created and captured to ${fileName}`,
DEFAULT_NOTICE_DURATION,
);
return;
}
let msg = "";
switch (action) {
case "currentLine":
msg = `Captured to current line in ${fileName}`;
break;
case "prepend":
case "activeFileTop":
msg = `Captured to top of ${fileName}`;
break;
case "append":
msg = `Captured to ${fileName}`;
break;
case "insertAfter": {
const heading = this.choice.insertAfter.after;
msg = heading
? `Captured to ${fileName} under '${heading}'`
: `Captured to ${fileName}`;
break;
}
}
new Notice(msg, DEFAULT_NOTICE_DURATION);
}
async run(): Promise<void> {
try {
// Reset any pending structured values before starting a new capture run
this.capturePropertyVars.clear();
const linkOptions = normalizeAppendLinkOptions(this.choice.appendLink);
this.formatter.setLinkToCurrentFileBehavior(
linkOptions.enabled && !linkOptions.requireActiveFile
? "optional"
: "required",
);
const selectionOverride = this.choice.useSelectionAsCaptureValue;
const globalSelectionAsValue =
this.plugin.settings.useSelectionAsCaptureValue ?? true;
const useSelectionAsCaptureValue =
typeof selectionOverride === "boolean"
? selectionOverride
: globalSelectionAsValue;
this.formatter.setUseSelectionAsCaptureValue(useSelectionAsCaptureValue);
const filePath = await this.getFormattedPathToCaptureTo(
this.choice.captureToActiveFile,
);
const content = this.getCaptureContent();
let getFileAndAddContentFn: typeof this.onFileExists;
const fileAlreadyExists = await this.fileExists(filePath);
if (fileAlreadyExists) {
getFileAndAddContentFn = this.onFileExists.bind(
this,
) as typeof this.onFileExists;
} else if (this.choice?.createFileIfItDoesntExist?.enabled) {
getFileAndAddContentFn = ((path, capture, _options) =>
this.onCreateFileIfItDoesntExist(path, capture, linkOptions)
) as typeof this.onCreateFileIfItDoesntExist;
} else {
throw new ChoiceAbortError(
`Target file missing: ${filePath}. Enable "Create file if it doesn't exist" or choose an existing file.`,
);
}
const { file, newFileContent, captureContent } =
await getFileAndAddContentFn(filePath, content);
const action = getCaptureAction(this.choice);
const isEditorInsertionAction =
action === "currentLine" ||
action === "newLineAbove" ||
action === "newLineBelow";
// Handle capture to active file with special actions
if (isEditorInsertionAction) {
// Parse Templater syntax in the capture content.
// If Templater isn't installed, it just returns the capture content.
const content = await templaterParseTemplate(
this.app,
captureContent,
file,
);
switch (action) {
case "currentLine":
appendToCurrentLine(content, this.app);
break;
case "newLineAbove":
insertOnNewLineAbove(content, this.app);
break;
case "newLineBelow":
insertOnNewLineBelow(content, this.app);
break;
}
} else {
await this.app.vault.modify(file, newFileContent);
if (this.choice.templater?.afterCapture === "wholeFile") {
await overwriteTemplaterOnce(this.app, file);
}
await this.applyCapturePropertyVars(file);
}
// Show success notification
if (this.plugin.settings.showCaptureNotification) {
this.showSuccessNotice(file, {
wasNewFile: !fileAlreadyExists,
action,
});
}
if (linkOptions.enabled) {
insertFileLinkToActiveView(this.app, file, linkOptions);
}
if (this.choice.openFile && file) {
const fileOpening = normalizeFileOpening(this.choice.fileOpening);
const focus = fileOpening.focus ?? true;
const openExistingTab = openExistingFileTab(this.app, file, focus);
if (!openExistingTab) {
await openFile(this.app, file, fileOpening);
}
await jumpToNextTemplaterCursorIfPossible(this.app, file);
}
} catch (err) {
if (
handleMacroAbort(err, {
logPrefix: "Capture execution aborted",
noticePrefix: "Capture execution aborted",
defaultReason: "Capture aborted",
})
) {
this.choiceExecutor.signalAbort?.(err as MacroAbortError);
return;
}
reportError(err, `Error running capture choice "${this.choice.name}"`);
}
}
private getCaptureContent(): string {
let content: string;
if (!this.choice.format.enabled) content = VALUE_SYNTAX;
else content = this.choice.format.format;
if (this.choice.task) content = `- [ ] ${content}\n`;
return content;
}
/**
* Gets a formatted file path to capture content to, either the active file or a specified location.
* If capturing to a folder, suggests a file within the folder to capture the content to.
*
* @param {boolean} shouldCaptureToActiveFile - Determines if the content should be captured to the active file.
* @returns {Promise<string>} A promise that resolves to the formatted file path where the content should be captured.
*
* @throws {Error} Throws an error if there's no active file when trying to capture to active file,
* if the capture path is invalid, or if the target folder is empty.
*/
private async getFormattedPathToCaptureTo(
shouldCaptureToActiveFile: boolean,
): Promise<string> {
// One-page preflight: if a specific target file was already chosen, use it
const preselected = this.choiceExecutor?.variables?.get(
QA_INTERNAL_CAPTURE_TARGET_FILE_PATH,
) as string | undefined;
if (
!shouldCaptureToActiveFile &&
preselected &&
typeof preselected === "string" &&
preselected.length > 0
) {
return preselected;
}
if (shouldCaptureToActiveFile) {
const activeFile = this.app.workspace.getActiveFile();
invariant(activeFile, "Cannot capture to active file - no active file.");
return activeFile.path;
}
const captureTo = this.choice.captureTo;
const formattedCaptureTo = await this.formatter.formatFileName(
captureTo,
this.choice.name,
);
const resolution = this.resolveCaptureTarget(formattedCaptureTo);
switch (resolution.kind) {
case "vault":
return this.selectFileInFolder("", true);
case "tag":
return this.selectFileWithTag(resolution.tag);
case "folder":
return this.selectFileInFolder(resolution.folder, false);
case "file":
return this.normalizeMarkdownFilePath("", resolution.path);
}
}
private resolveCaptureTarget(
formattedCaptureTo: string,
):
| { kind: "vault" }
| { kind: "tag"; tag: string }
| { kind: "folder"; folder: string }
| { kind: "file"; path: string } {
const normalizedCaptureTo = this.stripLeadingSlash(
formattedCaptureTo.trim(),
);
if (normalizedCaptureTo === "") {
return { kind: "vault" };
}
if (normalizedCaptureTo.startsWith("#")) {
return {
kind: "tag",
tag: normalizedCaptureTo.replace(/\.md$/, ""),
};
}
const endsWithSlash = normalizedCaptureTo.endsWith("/");
const folderPath = normalizedCaptureTo.replace(/\/+$/, "");
if (endsWithSlash) {
return { kind: "folder", folder: folderPath };
}
if (normalizedCaptureTo.endsWith(".md")) {
return { kind: "file", path: normalizedCaptureTo };
}
const fileCandidatePath = this.normalizeMarkdownFilePath(
"",
folderPath,
);
const fileCandidate = this.app.vault.getAbstractFileByPath(
fileCandidatePath,
);
const fileExists = !!fileCandidate;
if (isFolder(this.app, folderPath) && !fileExists) {
return { kind: "folder", folder: folderPath };
}
return { kind: "file", path: normalizedCaptureTo };
}
private async selectFileInFolder(
folderPath: string,
captureAnywhereInVault: boolean,
): Promise<string> {
const folderPathSlash =
folderPath.endsWith("/") || captureAnywhereInVault
? folderPath
: `${folderPath}/`;
const filesInFolder = getMarkdownFilesInFolder(this.app, folderPathSlash);
invariant(filesInFolder.length > 0, `Folder ${folderPathSlash} is empty.`);
const filePaths = filesInFolder.map((f) => f.path);
let targetFilePath: string;
try {
targetFilePath = await InputSuggester.Suggest(
this.app,
filePaths.map((item) => item.replace(folderPathSlash, "")),
filePaths,
);
} catch (error) {
if (isCancellationError(error)) {
throw new MacroAbortError("Input cancelled by user");
}
throw error;
}
invariant(
!!targetFilePath && targetFilePath.length > 0,
"No file selected for capture.",
);
// Ensure user has selected a file in target folder. InputSuggester allows user to write
// their own file path, so we need to make sure it's in the target folder.
const filePath = targetFilePath.startsWith(`${folderPathSlash}`)
? targetFilePath
: `${folderPathSlash}/${targetFilePath}`;
return await this.formatFilePath(filePath);
}
private async selectFileWithTag(tag: string): Promise<string> {
const tagWithHash = tag.startsWith("#") ? tag : `#${tag}`;
const filesWithTag = getMarkdownFilesWithTag(this.app, tagWithHash);
invariant(filesWithTag.length > 0, `No files with tag ${tag}.`);
const filePaths = filesWithTag.map((f) => f.path);
let targetFilePath: string;
try {
targetFilePath = await InputSuggester.Suggest(
this.app,
filePaths,
filePaths,
);
} catch (error) {
if (isCancellationError(error)) {
throw new MacroAbortError("Input cancelled by user");
}
throw error;
}
invariant(
!!targetFilePath && targetFilePath.length > 0,
"No file selected for capture.",
);
return await this.formatFilePath(targetFilePath);
}
private async onFileExists(
filePath: string,
content: string,
): Promise<{
file: TFile;
newFileContent: string;
captureContent: string;
}> {
const file: TFile = this.getFileByPath(filePath);
if (!file) throw new Error("File not found");
// Set the title to the existing file's basename
this.formatter.setTitle(file.basename);
// Set the destination file so formatters can generate proper relative links
this.formatter.setDestinationFile(file);
// First format pass...
const formatted = await this.formatter.formatContentOnly(content);
this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());
const fileContent: string = await this.app.vault.read(file);
// Second format pass, with the file content... User input (long running) should have been captured during first pass
// So this pass is to insert the formatted capture value into the file content, depending on the user's settings
const formattedFileContent: string =
await this.formatter.formatContentWithFile(
formatted,
this.choice,
fileContent,
file,
);
this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());
const secondReadFileContent: string = await this.app.vault.read(file);
let newFileContent = formattedFileContent;
if (secondReadFileContent !== fileContent) {
const res = merge(
secondReadFileContent,
fileContent,
formattedFileContent,
);
invariant(
!res.isSuccess,
() =>
`The file ${filePath} has been modified since the last read.\nQuickAdd could not merge the versions two without conflicts, and will not modify the file.\nThis is in order to prevent data loss.`,
);
newFileContent = res.joinedResults() as string;
}
return { file, newFileContent, captureContent: formatted };
}
private async onCreateFileIfItDoesntExist(
filePath: string,
captureContent: string,
linkOptions?: AppendLinkOptions,
): Promise<{
file: TFile;
newFileContent: string;
captureContent: string;
}> {
// Extract filename without extension from the full path
const fileBasename = filePath.split("/").pop()?.replace(/\.md$/, "") || "";
this.formatter.setTitle(fileBasename);
// Set the destination path so formatters can generate proper relative links
// even before the file is created
this.formatter.setDestinationSourcePath(filePath);
// First formatting pass: resolve QuickAdd placeholders and prompt for user input (e.g. {{value}})
// This mirrors the logic used when the target file already exists and prevents the timing issue
// where templater would run before the {{value}} placeholder is substituted (Issue #809).
const formattedCaptureContent: string =
await this.formatter.formatContentOnly(captureContent);
this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());
let fileContent = "";
if (this.choice.createFileIfItDoesntExist.createWithTemplate) {
const singleTemplateEngine: SingleTemplateEngine =
new SingleTemplateEngine(
this.app,
this.plugin,
this.choice.createFileIfItDoesntExist.template,
this.choiceExecutor,
);
if (linkOptions?.enabled && !linkOptions.requireActiveFile) {
singleTemplateEngine.setLinkToCurrentFileBehavior("optional");
}
fileContent = await singleTemplateEngine.run();
// Get template variables from the template engine's formatter
const templateVars = singleTemplateEngine.getAndClearTemplatePropertyVars();
log.logMessage(`CaptureChoiceEngine: Collected ${templateVars.size} template property variables`);
if (templateVars.size > 0) {
log.logMessage(`Variables: ${Array.from(templateVars.keys()).join(', ')}`);
}
// Store for later use
this.templatePropertyVars = templateVars;
}
// Create the new file with the (optional) template content
const file: TFile = await this.createFileWithInput(filePath, fileContent, {
suppressTemplaterOnCreate:
this.choice.createFileIfItDoesntExist.createWithTemplate,
});
// Post-process front matter for template property types if we used a template
if (this.choice.createFileIfItDoesntExist.createWithTemplate &&
this.templatePropertyVars &&
this.shouldPostProcessFrontMatter(file, this.templatePropertyVars)) {
await this.postProcessFrontMatter(file, this.templatePropertyVars);
}
// Process Templater commands in the template if a template was used
if (
this.choice.createFileIfItDoesntExist.createWithTemplate &&
fileContent
) {
await overwriteTemplaterOnce(this.app, file);
} else if (isTemplaterTriggerOnCreateEnabled(this.app)) {
await waitForTemplaterTriggerOnCreateToComplete(this.app, file);
}
// Read the file fresh from disk to avoid any potential cached content
// after the initial Templater run on newly created files.
const updatedFileContent: string = await this.app.vault.read(file);
// Second formatting pass: embed the already-resolved capture content into the newly created file
const newFileContent: string = await this.formatter.formatContentWithFile(
formattedCaptureContent,
this.choice,
updatedFileContent,
file,
);
this.mergeCapturePropertyVars(this.formatter.getAndClearTemplatePropertyVars());
return { file, newFileContent, captureContent: formattedCaptureContent };
}
private async formatFilePath(captureTo: string) {
const formattedCaptureTo: string = await this.formatter.formatFileName(
captureTo,
this.choice.name,
);
return this.normalizeMarkdownFilePath("", formattedCaptureTo);
}
private mergeCapturePropertyVars(vars: Map<string, unknown>): void {
if (!vars || vars.size === 0) {
return;
}
for (const [key, value] of vars) {
this.capturePropertyVars.set(key, value);
}
log.logMessage(
`CaptureChoiceEngine: Accumulated ${this.capturePropertyVars.size} structured capture variables`
);
}
private async applyCapturePropertyVars(file: TFile): Promise<void> {
if (this.capturePropertyVars.size === 0) {
return;
}
if (!this.shouldPostProcessFrontMatter(file, this.capturePropertyVars)) {
this.capturePropertyVars.clear();
return;
}
log.logMessage(
`CaptureChoiceEngine: Post-processing front matter with ${this.capturePropertyVars.size} capture variables`
);
await this.postProcessFrontMatter(file, this.capturePropertyVars);
this.capturePropertyVars.clear();
}
}