diff --git a/docs/features/recurring-tasks.md b/docs/features/recurring-tasks.md index ce5b6edad..8b80bd32e 100644 --- a/docs/features/recurring-tasks.md +++ b/docs/features/recurring-tasks.md @@ -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 diff --git a/docs/releases/unreleased.md b/docs/releases/unreleased.md index 48ca214dc..c2394d872 100644 --- a/docs/releases/unreleased.md +++ b/docs/releases/unreleased.md @@ -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)). diff --git a/src/bases/CalendarView.ts b/src/bases/CalendarView.ts index f603b4c4a..d20fe14b2 100644 --- a/src/bases/CalendarView.ts +++ b/src/bases/CalendarView.ts @@ -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", { diff --git a/src/bases/calendarMutations.ts b/src/bases/calendarMutations.ts index 42f12a459..da97798c3 100644 --- a/src/bases/calendarMutations.ts +++ b/src/bases/calendarMutations.ts @@ -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); diff --git a/src/main.ts b/src/main.ts index eec72f6c5..e97627724 100644 --- a/src/main.ts +++ b/src/main.ts @@ -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 { diff --git a/tests/unit/bases/calendarRecurringRescheduleConfirm.test.ts b/tests/unit/bases/calendarRecurringRescheduleConfirm.test.ts new file mode 100644 index 000000000..752d981ff --- /dev/null +++ b/tests/unit/bases/calendarRecurringRescheduleConfirm.test.ts @@ -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) => ({ + 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 { + 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 = { + 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) => 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; + }).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(); + }); + }); +});