Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/features/recurring-tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ For **scheduled-anchored** recurring tasks, moving the next occurrence keeps its

For **completion-anchored** recurring tasks, changing the scheduled date re-anchors the timeline and clears every completed and skipped instance dated **on or after** the new date, while keeping older instances as history.

Whenever a reschedule would clear recorded instances from the context menu or the scheduled-date field, TaskNotes asks you to confirm first — listing the dates that will be cleared — and cancelling leaves both the schedule and the recorded instances untouched.
Whenever a reschedule would clear recorded instances from the context menu, the scheduled-date field or the Calendar view (dragging the next occurrence to another day, or dropping the task onto the calendar from a note), TaskNotes asks you to confirm first — listing the dates that will be cleared — and cancelling leaves both the schedule and the recorded instances untouched.

## Flexible Scheduling

Expand Down
2 changes: 2 additions & 0 deletions docs/releases/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ When a change has user-facing documentation, include a canonical tasknotes.dev l
## Fixed

- (#2691) Moving the next occurrence of a scheduled-anchored recurring task no longer clears completed or skipped history on other dates. Moves without a `recurrence_original_date` (such as Google-synced or legacy off-pattern notes) clear only the landing day when it is already recorded, still behind confirmation; completion-anchored recurring tasks keep clearing recorded instances on or after the new date. See [Recurring Tasks](https://tasknotes.dev/features/recurring-tasks/#rescheduling-and-recorded-instances). Thanks to @martin-forge for reporting.
- (#2633) Fixed the Calendar view clearing a recurring task's completed and skipped occurrences without asking. Dragging the next occurrence to another day, or dropping the task onto the calendar from elsewhere, such as a task link in a note, now asks first and lists the dates it would clear, as the date picker does; **Cancel** leaves the task where it was, with its history. See [Recurring Tasks](https://tasknotes.dev/features/recurring-tasks/#rescheduling-and-recorded-instances).
- Thanks to @martin-forge for contributing
- (#2706) Fixed mdbase validation of scheduled and due times written by TaskNotes. Existing generated type definitions are updated when TaskNotes loads the vault.
- Thanks to @iantierney for reporting
- Protect task notes from being emptied by a failed save, including during workflow loops. If TaskNotes cannot restore an empty note, it keeps a recovery copy and includes its location in the error. Thanks to @chrabia for reporting ([Workflows issue 27](https://github.com/callumalpass/tasknotes-workflows/issues/27)).
Expand Down
16 changes: 14 additions & 2 deletions src/bases/CalendarView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2267,8 +2267,20 @@ export class CalendarView extends BasesViewBase {
return;
}
this.expectImmediateUpdate();
const receipt = await captureTaskUndo(this.plugin, task, () => this.plugin.taskService.updateProperty(task, "scheduled", arg.startStr));
if (receipt.task) await this.refreshAfterDirectCalendarTaskWrite(receipt.task);
// Declining the clear leaves the task as it was, so there is nothing to refresh or undo.
let declined = false;
const receipt = await captureTaskUndo(this.plugin, task, async () => {
const updated = await this.plugin.taskService.updateProperty(task, "scheduled", arg.startStr, {
confirmClearInstances: async (cleared) => {
const proceed = await this.plugin.confirmClearRescheduledInstances(cleared);
declined = !proceed;
return proceed;
},
});
return declined ? null : updated;
});
if (!receipt.task) return;
await this.refreshAfterDirectCalendarTaskWrite(receipt.task);
showTaskUndo(receipt.undo ? [receipt.undo] : [], false, 1, this.plugin.app.vault, task.title);
} catch (error) {
tasknotesLogger.error("[TaskNotes][CalendarView] Error scheduling dropped task", {
Expand Down
4 changes: 3 additions & 1 deletion src/bases/calendarMutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,9 @@ async function applyTaskCalendarGesture(
end: info.event.end?.toISOString(),
allDay: info.event.allDay,
},
context.timezone
context.timezone,
// Declining returns null, which reverts the gesture below and keeps the recorded instances.
{ confirmClearInstances: (cleared) => context.plugin.confirmClearRescheduledInstances(cleared) }
));
if (result.task) {
await context.refreshTask(result.task);
Expand Down
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1284,7 +1284,7 @@ export default class TaskNotesPlugin extends Plugin {
* reschedule would remove (the landing day for unmarked scheduled-anchored
* moves, or instances on or after the new date for completion-anchored tasks).
*/
private async confirmClearRescheduledInstances(cleared: {
async confirmClearRescheduledInstances(cleared: {
complete: string[];
skipped: string[];
}): Promise<boolean> {
Expand Down
216 changes: 216 additions & 0 deletions tests/unit/bases/calendarRecurringRescheduleConfirm.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
// Calendar planning needs the real recurrence parser, and the drop feedback formats real dates.
jest.mock("rrule", () => jest.requireActual("rrule/dist/es5/rrule.js"));
jest.mock("date-fns", () => jest.requireActual("../../../node_modules/date-fns"));
jest.mock("../../../src/ui/taskMutationUndo", () => ({
captureTaskUndo: async (_plugin: unknown, _task: unknown, operation: () => Promise<unknown>) => ({
task: await operation(),
}),
}));
jest.mock("../../../src/ui/taskPropertyPickers", () => ({ showTaskUndo: jest.fn() }));

import { buildCalendarEntries } from "@tasknotes/model/calendar";
import { CalendarView } from "../../../src/bases/CalendarView";
import { eventApiFromItem, type CalendarEventChange } from "../../../src/bases/calendarEngine";
import {
handleCalendarEventDrop,
type CalendarMutationContext,
} from "../../../src/bases/calendarMutations";
import type TaskNotesPlugin from "../../../src/main";
import { TaskService } from "../../../src/services/TaskService";
import { showTaskUndo } from "../../../src/ui/taskPropertyPickers";
import type { TaskInfo } from "../../../src/types";
import { TASK_PATH_DRAG_TYPE } from "../../../src/utils/DragDropManager";
import { PluginFactory, TaskFactory } from "../../helpers/mock-factories";

/**
* A weekly task whose next occurrence is Sunday 22 November, with the previous
* Sunday completed and the following Sunday skipped.
*/
function weeklyTask(overrides: Partial<TaskInfo>): TaskInfo {
return TaskFactory.createTask({
id: "weekly",
path: "Tasks/Weekly review.md",
title: "Weekly review",
scheduled: "2026-11-22",
recurrence: "DTSTART:20261101;FREQ=WEEKLY",
complete_instances: ["2026-11-15"],
skipped_instances: ["2026-11-29"],
...overrides,
});
}

/**
* A completion-anchored move clears every recorded instance on or after the new
* date, so moving this task to Saturday 21 November clears the skipped 29 November.
*/
function completionAnchoredTask(): TaskInfo {
return weeklyTask({ recurrence_anchor: "completion" });
}

/**
* A task synced to Google Calendar gets no `recurrence_original_date` when it moves,
* so a move clears the day it lands on if that day is already completed or skipped.
*/
function syncedTask(): TaskInfo {
return weeklyTask({ googleCalendarEventId: "gcal-1" });
}

function harness(task: TaskInfo, confirmed: boolean) {
const frontmatter: Record<string, unknown> = {
scheduled: task.scheduled,
recurrence: task.recurrence,
complete_instances: [...(task.complete_instances ?? [])],
skipped_instances: [...(task.skipped_instances ?? [])],
};
const confirm = jest.fn(async () => confirmed);
const plugin = PluginFactory.createMockPlugin({
settings: { calendarViewSettings: { timeFormat: "24" } },
cacheManager: {
getTaskInfo: jest.fn(async () => task),
updateTaskInfoInCache: jest.fn(),
},
taskCalendarSyncService: { isEnabled: () => false },
confirmClearRescheduledInstances: confirm,
});
plugin.app.fileManager.processFrontMatter = jest.fn(
async (_file: unknown, update: (frontmatter: Record<string, unknown>) => void) => {
update(frontmatter);
}
);
plugin.taskService = new TaskService(plugin);
return { task, frontmatter, confirm, plugin: plugin as TaskNotesPlugin };
}

/** Drags the task's next occurrence to Saturday 21 November in the calendar grid. */
function dragNextOccurrence(task: TaskInfo): CalendarEventChange {
const [entry] = buildCalendarEntries({
tasks: [task],
timezone: "UTC",
now: "2026-11-20T12:00:00Z",
range: { start: "2026-11-16", end: "2026-11-23" },
}).filter((candidate) => candidate.recurringKind === "next-scheduled");
const oldEvent = eventApiFromItem({
id: entry.id,
title: entry.title,
start: entry.start,
end: entry.end,
allDay: entry.allDay,
data: { modelEntry: entry, taskInfo: task, eventType: entry.type },
});
return {
oldEvent,
event: { ...oldEvent, start: new Date("2026-11-21T00:00:00Z"), end: null },
isPointer: true,
jsEvent: null,
revert: jest.fn(),
};
}

/** Drops the task on a day, Saturday 21 November by default, from outside the calendar, such as from a task link in a note. */
async function dropFromOutside(plugin: TaskNotesPlugin, task: TaskInfo, startStr = "2026-11-21") {
const view = Object.assign(Object.create(CalendarView.prototype), {
plugin,
expectImmediateUpdate: jest.fn(),
refreshAfterDirectCalendarTaskWrite: jest.fn(),
}) as CalendarView & { refreshAfterDirectCalendarTaskWrite: jest.Mock };
const dataTransfer = {
types: [TASK_PATH_DRAG_TYPE],
getData: (type: string) => (type === TASK_PATH_DRAG_TYPE ? task.path : ""),
} as unknown as DataTransfer;
await (view as unknown as {
handleExternalTaskDrop(arg: { dataTransfer: DataTransfer; startStr: string }): Promise<void>;
}).handleExternalTaskDrop({ dataTransfer, startStr });
return view;
}

function mutationContext(plugin: TaskNotesPlugin): CalendarMutationContext {
return {
plugin,
options: { startDateProperty: null, endDateProperty: null },
timezone: "UTC",
refreshTask: jest.fn(),
refreshEvent: jest.fn(),
};
}

describe("calendar reschedules that would clear a recurring task's recorded instances", () => {
describe("dragging the next occurrence within the calendar", () => {
it("asks first, and Cancel reverts the drop and keeps the schedule and its history", async () => {
const { task, frontmatter, confirm, plugin } = harness(completionAnchoredTask(), false);
const info = dragNextOccurrence(task);

await handleCalendarEventDrop(mutationContext(plugin), info);

expect(confirm).toHaveBeenCalledWith({ complete: [], skipped: ["2026-11-29"] });
expect(info.revert).toHaveBeenCalled();
expect(plugin.app.fileManager.processFrontMatter).not.toHaveBeenCalled();
expect(frontmatter).toMatchObject({
scheduled: "2026-11-22",
complete_instances: ["2026-11-15"],
skipped_instances: ["2026-11-29"],
});
expect(showTaskUndo).not.toHaveBeenCalled();
});

it("clears the listed instances once confirmed", async () => {
const { task, frontmatter, confirm, plugin } = harness(completionAnchoredTask(), true);
const info = dragNextOccurrence(task);

await handleCalendarEventDrop(mutationContext(plugin), info);

expect(confirm).toHaveBeenCalledWith({ complete: [], skipped: ["2026-11-29"] });
expect(info.revert).not.toHaveBeenCalled();
expect(frontmatter.scheduled).toBe("2026-11-21");
expect(frontmatter.complete_instances).toEqual(["2026-11-15"]);
expect(frontmatter.skipped_instances ?? []).toEqual([]);
expect(showTaskUndo).toHaveBeenCalledTimes(1);
});
});

describe("dropping the task into the calendar from outside it", () => {
it("asks first, and Cancel keeps the schedule and its history", async () => {
const { task, frontmatter, confirm, plugin } = harness(completionAnchoredTask(), false);

const view = await dropFromOutside(plugin, task);

expect(confirm).toHaveBeenCalledWith({ complete: [], skipped: ["2026-11-29"] });
expect(plugin.app.fileManager.processFrontMatter).not.toHaveBeenCalled();
expect(frontmatter).toMatchObject({
scheduled: "2026-11-22",
complete_instances: ["2026-11-15"],
skipped_instances: ["2026-11-29"],
});
expect(view.refreshAfterDirectCalendarTaskWrite).not.toHaveBeenCalled();
expect(showTaskUndo).not.toHaveBeenCalled();
});

it("clears the listed instances once confirmed", async () => {
const { task, frontmatter, confirm, plugin } = harness(completionAnchoredTask(), true);

const view = await dropFromOutside(plugin, task);

expect(confirm).toHaveBeenCalledWith({ complete: [], skipped: ["2026-11-29"] });
expect(frontmatter.scheduled).toBe("2026-11-21");
expect(frontmatter.complete_instances).toEqual(["2026-11-15"]);
expect(frontmatter.skipped_instances ?? []).toEqual([]);
expect(view.refreshAfterDirectCalendarTaskWrite).toHaveBeenCalledTimes(1);
expect(showTaskUndo).toHaveBeenCalledTimes(1);
});

it("asks before clearing the recorded day a move without recurrence_original_date lands on", async () => {
const { task, frontmatter, confirm, plugin } = harness(syncedTask(), false);

const view = await dropFromOutside(plugin, task, "2026-11-29");

expect(confirm).toHaveBeenCalledWith({ complete: [], skipped: ["2026-11-29"] });
expect(plugin.app.fileManager.processFrontMatter).not.toHaveBeenCalled();
expect(frontmatter).toMatchObject({
scheduled: "2026-11-22",
complete_instances: ["2026-11-15"],
skipped_instances: ["2026-11-29"],
});
expect(view.refreshAfterDirectCalendarTaskWrite).not.toHaveBeenCalled();
expect(showTaskUndo).not.toHaveBeenCalled();
});
});
});
Loading