Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/src/content/docs/docs/Choices/TemplateChoice.md
Original file line number Diff line number Diff line change
Expand Up @@ -483,4 +483,8 @@ These options keep the existing file untouched and create a new file instead:
These options leave the existing file unchanged:

- **Open existing file** - opens the existing file, even when **Open** is off.
- **Do nothing** - opens the existing file only when **Open** is on.
- **Do nothing** - leaves the existing file closed, even when **Open** is on.

To open a note only on the run that creates it, such as a daily note created
by a macro with [Run on startup](/docs/Choices/MacroChoice/#run-on-startup), turn **Open**
on and choose **Do nothing**.
5 changes: 3 additions & 2 deletions src/engine/TemplateChoiceEngine.collision.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -751,8 +751,9 @@ describe("TemplateChoiceEngine collision behavior", () => {

it.each([
{ mode: "doNothing", openFile: false, opens: true, notice: [] },
{ mode: "leaveUnchanged", openFile: false, opens: false, notice: ["'Test Template' already exists."] },
{ mode: "leaveUnchanged", openFile: true, opens: true, notice: [] },
{ mode: "doNothing", openFile: true, opens: true, notice: [] },
{ mode: "leaveClosed", openFile: false, opens: false, notice: ["'Test Template' already exists."] },
{ mode: "leaveClosed", openFile: true, opens: false, notice: ["'Test Template' already exists."] },
] as const)("$mode with openFile=$openFile opens the existing note: $opens", async ({ mode, openFile, opens, notice }) => {
const { app, engine } = createEngine();
const existingFile = createExistingFile("Test Template.md");
Expand Down
18 changes: 8 additions & 10 deletions src/engine/TemplateChoiceEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ export class TemplateChoiceEngine extends TemplateEngine {
});

let createdFile: TFile | null;
let shouldAutoOpen = false;
let shouldOpen = this.choice.openFile;
let createdNew = false;
// What this run did to its target note (#1615). Derived from the file-exists
// resolution the engine actually performed rather than from a byte compare,
Expand Down Expand Up @@ -198,7 +198,8 @@ export class TemplateChoiceEngine extends TemplateEngine {
return;
}

({ createdFile, shouldAutoOpen } = await this.applyFileExistsMode(
let keptFileOpens: boolean | undefined;
({ createdFile, keptFileOpens } = await this.applyFileExistsMode(
modeId,
targetFilePath,
existingFile,
Expand All @@ -219,6 +220,7 @@ export class TemplateChoiceEngine extends TemplateEngine {
}
return;
}
shouldOpen = keptFileOpens ?? shouldOpen;
} else {
createdFile = await this.createFileWithTemplate(
targetFilePath,
Expand Down Expand Up @@ -276,7 +278,7 @@ export class TemplateChoiceEngine extends TemplateEngine {
await copyChoiceFileLink(createdFile);
}

if ((this.choice.openFile || shouldAutoOpen) && createdFile) {
if (shouldOpen && createdFile) {
await openChoiceFile({
app: this.app, file: createdFile,
opening: this.choice.fileOpening, originLeaf: this.originLeaf,
Expand Down Expand Up @@ -476,7 +478,7 @@ export class TemplateChoiceEngine extends TemplateEngine {
existingFile: TFile | null,
templatePath: string,
linkOptions: NormalizedAppendLinkOptions,
): Promise<{ createdFile: TFile | null; shouldAutoOpen: boolean }> {
): Promise<{ createdFile: TFile | null; keptFileOpens?: boolean }> {
const mode = getFileExistsMode(modeId);

switch (mode.resolutionKind) {
Expand All @@ -488,7 +490,6 @@ export class TemplateChoiceEngine extends TemplateEngine {
templatePath,
linkOptions,
),
shouldAutoOpen: false,
};
case "createNew": {
const nextFilePath = await resolveCreateNewCollisionFilePath(
Expand All @@ -513,15 +514,12 @@ export class TemplateChoiceEngine extends TemplateEngine {
new Notice(`Created '${createdFile.basename}'.`);
}

return {
createdFile,
shouldAutoOpen: false,
};
return { createdFile };
}
case "reuseExisting":
return {
createdFile: existingFile,
shouldAutoOpen: mode.opensExistingFile,
keptFileOpens: mode.opensExistingFile,
};
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/gui/ChoiceBuilder/TemplateChoiceForm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,9 +262,9 @@ describe("TemplateChoiceForm", () => {
expect(select.value).toBe("doNothing");
expect(Array.from(select.options, (option) => option.text)).toEqual(["Open existing file", "Do nothing"]);

await fireEvent.change(select, { target: { value: "leaveUnchanged" } });
await fireEvent.change(select, { target: { value: "leaveClosed" } });
flushSync();
expect(props.choice.fileExistsBehavior).toEqual({ kind: "apply", mode: "leaveUnchanged" });
expect(props.choice.fileExistsBehavior).toEqual({ kind: "apply", mode: "leaveClosed" });
});

it("persists the copy-link-to-clipboard toggle", async () => {
Expand Down
12 changes: 12 additions & 0 deletions src/migrations/helpers/normalizeTemplateFileExistsBehavior.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ type LegacyTemplateChoice = {
setFileExistsBehavior?: boolean;
fileExistsMode?: unknown;
fileExistsBehavior?: TemplateFileExistsBehavior;
openFile?: boolean;
};

export function isTemplateChoice(
Expand All @@ -24,6 +25,17 @@ function migrateFileExistsBehavior(
choice: LegacyTemplateChoice,
): TemplateFileExistsBehavior {
if (choice.fileExistsBehavior) {
// 2.33's leaveUnchanged opened the kept note only when Open was on, so it
// splits into the two keep modes with the same behavior.
if (
choice.fileExistsBehavior.kind === "apply" &&
(choice.fileExistsBehavior.mode as string) === "leaveUnchanged"
) {
return {
kind: "apply",
mode: choice.openFile ? "doNothing" : "leaveClosed",
};
}
return choice.fileExistsBehavior;
}

Expand Down
2 changes: 2 additions & 0 deletions src/migrations/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import migrateProviderApiKeysToSecretStorage from "./migrateProviderApiKeysToSec
import migrateToMultipleTemplateFolders from "./migrateToMultipleTemplateFolders";
import refreshStaleDefaultModelSeeds from "./refreshStaleDefaultModelSeeds";
import pinAiModelRefs from "./pinAiModelRefs";
import retireLeaveUnchangedKeepMode from "./retireLeaveUnchangedKeepMode";
import { settingsStore } from "src/settingsStore";

const migrations: Migrations = {
Expand All @@ -35,6 +36,7 @@ const migrations: Migrations = {
migrateToMultipleTemplateFolders,
refreshStaleDefaultModelSeeds,
pinAiModelRefs,
retireLeaveUnchangedKeepMode,
};

async function migrate(plugin: QuickAdd): Promise<void> {
Expand Down
44 changes: 44 additions & 0 deletions src/migrations/retireLeaveUnchangedKeepMode.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import migration from "./retireLeaveUnchangedKeepMode";
import { normalizeImportedChoice } from "../services/packageChoiceImport";
import type IChoice from "../types/choices/IChoice";
import { migrationPlugin } from "../../tests/helpers/utilities/migrationFixtures";

function template(mode: string, openFile: boolean) {
return {
id: `template-${mode}-${openFile}`,
name: "Daily",
type: "Template",
openFile,
fileExistsBehavior: { kind: "apply", mode },
};
}

describe("retireLeaveUnchangedKeepMode migration", () => {
it.each([
{ openFile: true, mode: "doNothing" },
{ openFile: false, mode: "leaveClosed" },
])("moves leaveUnchanged with Open=$openFile to $mode, which opens the kept note the same way", async ({ openFile, mode }) => {
const plugin = migrationPlugin({ choices: [template("leaveUnchanged", openFile)], macros: [] });
await migration.migrate(plugin);
expect(plugin.settings.choices[0].fileExistsBehavior).toEqual({ kind: "apply", mode });
});

it("leaves the current keep modes alone", async () => {
const plugin = migrationPlugin({
choices: [template("leaveClosed", true), template("doNothing", false)],
macros: [],
});
await migration.migrate(plugin);
expect(plugin.settings.choices.map((choice: { fileExistsBehavior: unknown }) => choice.fileExistsBehavior)).toEqual([
{ kind: "apply", mode: "leaveClosed" },
{ kind: "apply", mode: "doNothing" },
]);
});

it("maps leaveUnchanged in a package exported before the migration", () => {
const choice = template("leaveUnchanged", true) as unknown as IChoice;
normalizeImportedChoice(choice);
expect((choice as unknown as { fileExistsBehavior: unknown }).fileExistsBehavior).toEqual({ kind: "apply", mode: "doNothing" });
});
});
10 changes: 10 additions & 0 deletions src/migrations/retireLeaveUnchangedKeepMode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import consolidateFileExistsBehavior from "./consolidateFileExistsBehavior";
import type { Migration } from "./Migrations";

const retireLeaveUnchangedKeepMode: Migration = {
description:
"Move Template choices off the leaveUnchanged keep mode to the mode with the same behavior",
migrate: consolidateFileExistsBehavior.migrate,
};

export default retireLeaveUnchangedKeepMode;
2 changes: 2 additions & 0 deletions src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ export interface QuickAddSettings {
migrateToMultipleTemplateFolders: boolean;
refreshStaleDefaultModelSeeds: boolean;
pinAiModelRefs: boolean;
retireLeaveUnchangedKeepMode: boolean;
};
}

Expand Down Expand Up @@ -161,5 +162,6 @@ export const DEFAULT_SETTINGS: QuickAddSettings = {
migrateToMultipleTemplateFolders: false,
refreshStaleDefaultModelSeeds: false,
pinAiModelRefs: false,
retireLeaveUnchangedKeepMode: false,
},
};
2 changes: 1 addition & 1 deletion src/template/fileExistsPolicy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ describe("fileExistsPolicy registry", () => {
]);
expect(getModesForCategory("keep").map((mode) => mode.id)).toEqual([
"doNothing",
"leaveUnchanged",
"leaveClosed",
]);
});

Expand Down
10 changes: 6 additions & 4 deletions src/template/fileExistsPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,12 @@ export const fileExistsModes = [
opensExistingFile: true,
},
{
id: "leaveUnchanged",
// Replaces 2.33's leaveUnchanged, which opened the note when Open was on.
// normalizeTemplateChoice maps that id to doNothing or leaveClosed.
id: "leaveClosed",
category: "keep",
label: "Do nothing",
description: "Leaves the existing file unchanged. It opens only when Open is on.",
description: "Leaves the existing file unchanged and closed, even when Open is on.",
requiresExistingFile: true,
resolutionKind: "reuseExisting",
opensExistingFile: false,
Expand Down Expand Up @@ -145,7 +147,7 @@ const legacyFileExistsModeMap: Record<string, FileExistsModeId> = {
increment: "increment",
duplicateSuffix: "duplicateSuffix",
doNothing: "doNothing",
leaveUnchanged: "leaveUnchanged",
leaveClosed: "leaveClosed",
};

const createNewPathResolvers: Record<
Expand Down Expand Up @@ -180,7 +182,7 @@ function getCategoryForMode(
// existing file with the same behavior. Leaving the note alone from the prompt is
// what Escape already does.
export function getPromptModes(): FileExistsModeDefinition[] {
return fileExistsModes.filter((mode) => mode.id !== "leaveUnchanged");
return fileExistsModes.filter((mode) => mode.id !== "leaveClosed");
}

export function getDefaultBehaviorForCategory(
Expand Down
55 changes: 52 additions & 3 deletions tests/e2e/file-exists-behavior.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const behavior = {
appendTop: { kind: "apply", mode: "appendTop" },
overwrite: { kind: "apply", mode: "overwrite" },
doNothing: { kind: "apply", mode: "doNothing" },
leaveUnchanged: { kind: "apply", mode: "leaveUnchanged" },
leaveClosed: { kind: "apply", mode: "leaveClosed" },
prompt: { kind: "prompt" },
} as const;

Expand Down Expand Up @@ -331,15 +331,15 @@ describe("functional: file collision behaviors", () => {
});
});

describe("with Open off, only Open existing file opens the note (#2244)", () => {
describe("Open and the keep modes (#2244, #2279)", () => {
const expected = {
increment: { file: "open-off-increment1.md", effect: "created", opens: false },
duplicateSuffix: { file: "open-off-duplicateSuffix (1).md", effect: "created", opens: false },
appendBottom: { file: "open-off-appendBottom.md", effect: "changed", opens: false },
appendTop: { file: "open-off-appendTop.md", effect: "changed", opens: false },
overwrite: { file: "open-off-overwrite.md", effect: "changed", opens: false },
doNothing: { file: "open-off-doNothing.md", effect: "unchanged", opens: true },
leaveUnchanged: { file: "open-off-leaveUnchanged.md", effect: "unchanged", opens: false },
leaveClosed: { file: "open-off-leaveClosed.md", effect: "unchanged", opens: false },
} as const satisfies Record<Exclude<keyof typeof behavior, "prompt">, unknown>;
const modes = Object.keys(expected) as Array<keyof typeof expected>;

Expand Down Expand Up @@ -375,6 +375,29 @@ describe("with Open off, only Open existing file opens the note (#2244)", () =>
await obsidian.sleep(600);
expect(await openSandboxNotes()).toEqual(opens ? [sandbox.path(file)] : []);
});

it("with Open on, Do nothing opens the note only on the run that creates it (#2279)", async () => {
const name = "__qa-test-open-on-leaveClosed";
const file = sandbox.path("open-on-leaveClosed.md");
await qa.data<QuickAddData>().patch((data) => {
data.choices.push({
...templateChoice(name, `${sandbox.root}/open-on-leaveClosed`, behavior.leaveClosed),
openFile: true,
});
});
await qa.reload({ waitUntilReady: true });

expect(await obsidian.execJson("quickadd:run", { choice: name, verify: true })).toMatchObject({ ok: true, effect: "created", file });
await obsidian.sleep(600);
expect(await openSandboxNotes()).toEqual([file]);

await obsidian.dev.eval(`app.workspace.getLeavesOfType("markdown")
.filter((leaf) => leaf.view.file?.path === ${JSON.stringify(file)})
.forEach((leaf) => leaf.detach())`);
expect(await obsidian.execJson("quickadd:run", { choice: name, verify: true })).toMatchObject({ ok: true, effect: "unchanged", file });
await obsidian.sleep(600);
expect(await openSandboxNotes()).toEqual([]);
}, 30_000);
});

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -494,3 +517,29 @@ describe("migration: repairTemplateFileExistsBehavior", () => {
expect(choice?.fileExistsBehavior).toEqual(behavior.overwrite);
});
});

describe("migration: retireLeaveUnchangedKeepMode", () => {
beforeAll(async () => {
const leaveUnchanged = { kind: "apply", mode: "leaveUnchanged" };
await qa.data<QuickAddData>().patch((data) => {
clearTestChoices(data);
data.choices.push(
{ ...templateChoice("__qa-test-l1-open-on", `${sandbox.root}/l1`, leaveUnchanged), openFile: true },
templateChoice("__qa-test-l2-open-off", `${sandbox.root}/l2`, leaveUnchanged),
);
data.migrations.retireLeaveUnchangedKeepMode = false;
});

await qa.reload();
await qa.waitForData<QuickAddData>(
(data) => data.migrations.retireLeaveUnchangedKeepMode === true,
{ timeoutMs: 10_000, intervalMs: 300 },
);
}, 15_000);

it("keeps each choice's behavior: Open on opens the kept note, Open off leaves it closed", async () => {
const data = await qa.data<QuickAddData>().read();
expect(findChoice(data, "__qa-test-l1-open-on")?.fileExistsBehavior).toEqual(behavior.doNothing);
expect(findChoice(data, "__qa-test-l2-open-off")?.fileExistsBehavior).toEqual(behavior.leaveClosed);
});
});
Loading