Skip to content

Commit

Permalink
Merge pull request #438 from chhoumann/capture-improvements
Browse files Browse the repository at this point in the history
Capture to active file improvements and fix minor issues in tests and formatters
  • Loading branch information
chhoumann authored Apr 3, 2023
2 parents 27ab71d + a8a6d08 commit 83b5076
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 76 deletions.
73 changes: 24 additions & 49 deletions src/engine/CaptureChoiceEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
appendToCurrentLine,
openFile,
replaceTemplaterTemplatesInCreatedFile,
templaterParseTemplate,
} from "../utilityObsidian";
import { VALUE_SYNTAX } from "../constants";
import type QuickAdd from "../main";
Expand Down Expand Up @@ -40,21 +39,7 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine {

async run(): Promise<void> {
try {
if (this.choice?.captureToActiveFile) {
await this.captureToActiveFile();
return;
}

const captureTo = this.choice.captureTo;
invariant(captureTo, () => {
return `Invalid capture to for ${this.choice.name}. ${
captureTo.length === 0
? "Capture path is empty."
: `Capture path is not valid: ${captureTo}`
}`;
});

const filePath = await this.formatFilePath(captureTo);
const filePath = await this.getFormattedPathToCaptureTo();
const content = this.getCaptureContent();

let getFileAndAddContentFn: typeof this.onFileExists;
Expand Down Expand Up @@ -111,6 +96,29 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine {
return content;
}

private async getFormattedPathToCaptureTo(): Promise<string> {
if (this.choice.captureToActiveFile) {
const activeFile = this.app.workspace.getActiveFile();
invariant(
activeFile,
`Cannot capture to active file - no active file.`
);

return activeFile.path;
}

const captureTo = this.choice.captureTo;
invariant(captureTo, () => {
return `Invalid capture to for ${this.choice.name}. ${
captureTo.length === 0
? "Capture path is empty."
: `Capture path is not valid: ${captureTo}`
}`;
});

return await this.formatFilePath(captureTo);
}

private async onFileExists(
filePath: string,
content: string
Expand Down Expand Up @@ -201,37 +209,4 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine {

return this.normalizeMarkdownFilePath("", formattedCaptureTo);
}

private async captureToActiveFile() {
const activeFile = this.app.workspace.getActiveFile();

if (!activeFile) {
log.logError("Cannot capture to active file - no active file.");
return;
}

let content: string = this.getCaptureContent();
content = await this.formatter.formatContent(content, this.choice);

if (this.choice.format.enabled) {
content = await templaterParseTemplate(
this.app,
content,
activeFile
);
}

if (!content) return;

if (this.choice.prepend) {
const fileContent: string = await this.app.vault.cachedRead(
activeFile
);
const newFileContent = `${fileContent}${content}`;

await this.app.vault.modify(activeFile, newFileContent);
} else {
appendToCurrentLine(content, this.app);
}
}
}
1 change: 1 addition & 0 deletions src/formatters/captureChoiceFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ export class CaptureChoiceFormatter extends CompleteFormatter {
targetPosition,
!!this.choice.insertAfter.considerSubsections
);

targetPosition = endOfSectionIndex ?? fileContentLines.length - 1;
}

Expand Down
42 changes: 40 additions & 2 deletions src/formatters/helpers/getEndOfSection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ test("getEndOfSection - target is heading, should consider subsections", () => {
expect(result).toBe(10);
});

test("getEndOfSection - Capture to first line, shoudlConsiderSubsections ON", () => {
test("getEndOfSection - Capture to first line, shouldConsiderSubsections ON", () => {
const lines = [
"# Meeting Notes", // target (0)
"",
Expand All @@ -222,7 +222,7 @@ test("getEndOfSection - Capture to first line, shoudlConsiderSubsections ON", ()
expect(result).toBe(6);
});

test("getEndOfSection - Capture to first line, shoudlConsiderSubsections OFF", () => {
test("getEndOfSection - Capture to first line, shouldConsiderSubsections OFF", () => {
const lines = [
"# Meeting Notes", // target (0)
"", // result (1)
Expand All @@ -238,3 +238,41 @@ test("getEndOfSection - Capture to first line, shoudlConsiderSubsections OFF", (
const result = getEndOfSection(lines, targetLine, false);
expect(result).toBe(1);
});

test("getEndOfSection - capture to last line, shouldConsiderSubsections OFF", () => {
const lines = [
"",
"## Heading",
"",
"## Todos",
"- [ ] test",
"- [ ] asd",
"- [ ] d",
"",
"## Schedule" // target (8) & result (8)
]

const targetLine = 8;

const result = getEndOfSection(lines, targetLine, false);
expect(result).toBe(8);
})

test("getEndOfSection - capture to last line, shouldConsiderSubsections ON", () => {
const lines = [
"",
"## Heading",
"",
"## Todos",
"- [ ] test",
"- [ ] asd",
"- [ ] d",
"",
"## Schedule" // target (8) & result (8)
]

const targetLine = 8;

const result = getEndOfSection(lines, targetLine, true);
expect(result).toBe(8);
})
5 changes: 5 additions & 0 deletions src/formatters/helpers/getEndOfSection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ export default function getEndOfSection(
);

if (lastNonEmptyLineInSectionIdx !== null) {
// Since we're finding the end, it doesn't make sense to go above the target line
if (lastNonEmptyLineInSectionIdx < targetLine) {
return targetLine;
}

if (lastNonEmptyLineInSectionIdx + 1 === lastLineInBodyIdx) {
return endOfSectionLineIdx;
}
Expand Down
49 changes: 28 additions & 21 deletions src/gui/ChoiceBuilder/captureChoiceBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,14 @@ export class CaptureChoiceBuilder extends ChoiceBuilder {

this.addPrependSetting();

this.addAppendLinkSetting();
this.addInsertAfterSetting();
if (!this.choice.captureToActiveFile) {
this.addAppendLinkSetting();
this.addInsertAfterSetting();
this.addOpenFileSetting();
if (this.choice.openFile) this.addOpenFileInNewTabSetting();

if (this.choice.openFile) {
this.addOpenFileInNewTabSetting();
}
}

this.addFormatSetting();
Expand Down Expand Up @@ -254,25 +257,29 @@ export class CaptureChoiceBuilder extends ChoiceBuilder {
.addToggle((toggle) =>
toggle
.setValue(this.choice.insertAfter?.considerSubsections)
.onChange(
(value) => {
// Trying to disable
if (!value) {
this.choice.insertAfter.considerSubsections = false;
return;
}

// Trying to enable but `after` is not a heading
const targetIsHeading = this.choice.insertAfter.after.startsWith("#");
if (targetIsHeading) {
this.choice.insertAfter.considerSubsections = value;
} else {
this.choice.insertAfter.considerSubsections = false;
log.logError("'Consider subsections' can only be enabled if the insert after line starts with a # (heading).");
this.display();
}
.onChange((value) => {
// Trying to disable
if (!value) {
this.choice.insertAfter.considerSubsections =
false;
return;
}
)

// Trying to enable but `after` is not a heading
const targetIsHeading =
this.choice.insertAfter.after.startsWith("#");
if (targetIsHeading) {
this.choice.insertAfter.considerSubsections =
value;
} else {
this.choice.insertAfter.considerSubsections =
false;
log.logError(
"'Consider subsections' can only be enabled if the insert after line starts with a # (heading)."
);
this.display();
}
})
);

const createLineIfNotFound: Setting = new Setting(this.contentEl);
Expand Down
3 changes: 0 additions & 3 deletions src/gui/GlobalSettings.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/utils/invariant.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export default function invariant(
condition: unknown,
message?: string | (() => string)
): void {
): asserts condition {
if (!condition) {
throw new Error(typeof message === "function" ? message() : message);
}
Expand Down

1 comment on commit 83b5076

@vercel
Copy link

@vercel vercel bot commented on 83b5076 Apr 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

quickadd – ./

quickadd.obsidian.guide
quickadd-git-master-chrisbbh.vercel.app
quickadd-chrisbbh.vercel.app

Please sign in to comment.