forked from super-productivity/super-productivity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask-shared-scheduling.reducer.ts
More file actions
394 lines (357 loc) · 12.3 KB
/
task-shared-scheduling.reducer.ts
File metadata and controls
394 lines (357 loc) · 12.3 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
import { Action, ActionReducer, MetaReducer } from '@ngrx/store';
import { Update } from '@ngrx/entity';
import { RootState } from '../../root-state';
import { TaskSharedActions } from '../task-shared.actions';
import {
TASK_FEATURE_NAME,
taskAdapter,
} from '../../../features/tasks/store/task.reducer';
import { Task } from '../../../features/tasks/task.model';
import { TODAY_TAG } from '../../../features/tag/tag.const';
import { unique } from '../../../util/unique';
import { isTodayWithOffset } from '../../../util/is-today.util';
import { getDbDateStr } from '../../../util/get-db-date-str';
import { appStateFeatureKey } from '../../app-state/app-state.reducer';
import { moveItemBeforeItem } from '../../../util/move-item-before-item';
import {
ActionHandlerMap,
getTag,
removeTasksFromList,
removeTasksFromPlannerDays,
updateProject,
getProjectOrUndefined,
updateTags,
} from './task-shared-helpers';
import { filterOutId } from '../../../util/filter-out-id';
// =============================================================================
// ACTION HANDLERS
// =============================================================================
//
// IMPORTANT: These handlers implement the dueDay/dueWithTime mutual exclusivity pattern.
// When setting dueWithTime, dueDay is cleared (set to undefined).
// See: docs/ai/dueDay-dueWithTime-mutual-exclusivity.md
//
// =============================================================================
const handleScheduleTaskWithTime = (
state: RootState,
task: { id: string; projectId?: string | null },
dueWithTime: number,
remindAt?: number,
isMoveToBacklog?: boolean,
): RootState => {
// Check if task already has the same dueWithTime
const currentTask = state[TASK_FEATURE_NAME].entities[task.id] as Task;
if (!currentTask) {
return state;
}
const todayTag = getTag(state, TODAY_TAG.id);
const todayStr = state[appStateFeatureKey]?.todayStr ?? getDbDateStr();
const startOfNextDayDiffMs = state[appStateFeatureKey]?.startOfNextDayDiffMs ?? 0;
const isScheduledForToday = isTodayWithOffset(
dueWithTime,
todayStr,
startOfNextDayDiffMs,
);
const isCurrentlyInToday = todayTag.taskIds.includes(task.id);
// If task is already correctly scheduled, don't change state (unless backlog move requested)
if (
currentTask.dueWithTime === dueWithTime &&
currentTask.remindAt === remindAt &&
isScheduledForToday === isCurrentlyInToday &&
!isMoveToBacklog
) {
return state;
}
// First, update the task entity with the scheduling data
let updatedState: RootState = {
...state,
[TASK_FEATURE_NAME]: taskAdapter.updateOne(
{
id: task.id,
changes: {
dueWithTime,
// CRITICAL: Mutual exclusivity pattern - setting dueWithTime clears dueDay
// This prevents state inconsistency where both fields are set with conflicting dates
// See: docs/ai/dueDay-dueWithTime-mutual-exclusivity.md
dueDay: undefined,
remindAt,
},
},
state[TASK_FEATURE_NAME],
),
};
// Handle backlog move atomically if requested
if (isMoveToBacklog && currentTask.projectId) {
const project = getProjectOrUndefined(updatedState, currentTask.projectId);
if (project && project.isEnableBacklog) {
const todaysTaskIdsBefore = project.taskIds;
const backlogIdsBefore = project.backlogTaskIds;
// Only move if not already in backlog
if (!backlogIdsBefore.includes(task.id)) {
updatedState = updateProject(updatedState, currentTask.projectId, {
taskIds: todaysTaskIdsBefore.filter(filterOutId(task.id)),
backlogTaskIds: [task.id, ...backlogIdsBefore],
});
}
}
}
// No tag change needed
if (isScheduledForToday === isCurrentlyInToday) {
return updatedState;
}
const newTaskIds = isScheduledForToday
? unique([task.id, ...todayTag.taskIds]) // Add to top, prevent duplicates
: todayTag.taskIds.filter((id) => id !== task.id); // Remove
return updateTags(updatedState, [
{
id: TODAY_TAG.id,
changes: { taskIds: newTaskIds },
},
]);
};
const handleUnScheduleTask = (
state: RootState,
taskId: string,
isLeaveInToday = false,
): RootState => {
// First, update the task entity to clear scheduling data
const todayStrForUnschedule = state[appStateFeatureKey]?.todayStr ?? getDbDateStr();
const updatedState = {
...state,
[TASK_FEATURE_NAME]: taskAdapter.updateOne(
{
id: taskId,
changes: {
dueDay: isLeaveInToday ? todayStrForUnschedule : undefined,
dueWithTime: undefined,
remindAt: undefined,
},
},
state[TASK_FEATURE_NAME],
),
};
// Then, handle today tag updates
const todayTag = getTag(updatedState, TODAY_TAG.id);
if (!todayTag.taskIds.includes(taskId) || isLeaveInToday) {
return updatedState;
}
return updateTags(updatedState, [
{
id: TODAY_TAG.id,
changes: {
taskIds: todayTag.taskIds.filter((id) => id !== taskId),
},
},
]);
};
const handleDismissReminderOnly = (state: RootState, taskId: string): RootState => {
// Only clear remindAt (the reminder notification) but keep dueWithTime, dueDay, and Today tag
return {
...state,
[TASK_FEATURE_NAME]: taskAdapter.updateOne(
{
id: taskId,
changes: {
remindAt: undefined,
},
},
state[TASK_FEATURE_NAME],
),
};
};
const handlePlanTasksForToday = (
state: RootState,
taskIds: string[],
parentTaskMap: Record<string, string | undefined>,
todayFromAction?: string,
startOfNextDayDiffMsFromAction?: number,
isClearScheduledTime?: boolean,
): RootState => {
const todayTag = getTag(state, TODAY_TAG.id);
const today = todayFromAction ?? state[appStateFeatureKey]?.todayStr ?? getDbDateStr();
const offsetMs =
startOfNextDayDiffMsFromAction ??
state[appStateFeatureKey]?.startOfNextDayDiffMs ??
0;
// Filter out tasks that don't exist, are already in today, or whose parent is in today
const newTasksForToday = taskIds.filter((taskId) => {
// Skip tasks that don't exist in the store (can happen during sync)
if (!state[TASK_FEATURE_NAME].entities[taskId]) return false;
if (todayTag.taskIds.includes(taskId)) return false;
const parentId = parentTaskMap[taskId];
return !parentId || !todayTag.taskIds.includes(parentId);
});
// Filter for tasks that need updates:
// 1. Tasks that need dueDay updated (not yet scheduled for today)
// 2. Tasks already scheduled for today that need remindAt/dueWithTime cleared
const tasksNeedingUpdate = taskIds.filter((taskId) => {
const task = state[TASK_FEATURE_NAME].entities[taskId] as Task;
if (!task) return false;
// Include tasks that need dueDay updated
if (task.dueDay !== today) {
return newTasksForToday.includes(taskId) || todayTag.taskIds.includes(taskId);
}
// Include tasks already scheduled for today when we need to clear scheduling
if (task.dueDay === today && isClearScheduledTime) {
// Need to clear remindAt and/or dueWithTime
return task.remindAt !== undefined || task.dueWithTime !== undefined;
}
return false;
});
// Early return if no actual changes needed
if (newTasksForToday.length === 0 && tasksNeedingUpdate.length === 0) {
return state;
}
// Only create updates for tasks that need dueDay change
const taskUpdates: Update<Task>[] = tasksNeedingUpdate.map((taskId) => {
const task = state[TASK_FEATURE_NAME].entities[taskId] as Task;
// Preserve dueWithTime if it matches today's date
// Only clear it if the task has a time scheduled for a different day
// However, if isClearScheduledTime is true (from reminder dialog), always clear the time
const shouldClearTime = isClearScheduledTime
? !!task?.dueWithTime
: task?.dueWithTime && !isTodayWithOffset(task.dueWithTime, today, offsetMs);
return {
id: taskId,
changes: {
dueDay: today,
remindAt: undefined, // Always clear reminder when explicitly adding to today
...(shouldClearTime ? { dueWithTime: undefined } : {}),
},
};
});
const updatedState = {
...state,
[TASK_FEATURE_NAME]: taskAdapter.updateMany(taskUpdates, state[TASK_FEATURE_NAME]),
};
// Update the today tag
const stateWithTodayTag = updateTags(updatedState, [
{
id: TODAY_TAG.id,
changes: {
taskIds: unique([...newTasksForToday, ...todayTag.taskIds]),
},
},
]);
// Remove taskIds from planner days
return removeTasksFromPlannerDays(stateWithTodayTag, taskIds);
};
const handleRemoveTasksFromTodayTag = (
state: RootState,
taskIds: string[],
): RootState => {
const todayTag = getTag(state, TODAY_TAG.id);
return updateTags(state, [
{
id: TODAY_TAG.id,
changes: {
taskIds: removeTasksFromList(todayTag.taskIds, taskIds),
},
},
]);
};
const handleMoveTaskInTodayTagList = (
state: RootState,
toTaskId: string,
fromTaskId: string,
): RootState => {
const todayTag = getTag(state, TODAY_TAG.id);
// If either task is not in the Today list, don't perform the move
if (!todayTag.taskIds.includes(fromTaskId) || !todayTag.taskIds.includes(toTaskId)) {
return state;
}
return updateTags(state, [
{
id: todayTag.id,
changes: {
taskIds: moveItemBeforeItem(todayTag.taskIds, fromTaskId, toTaskId),
},
},
]);
};
// =============================================================================
// META REDUCER
// =============================================================================
const createActionHandlers = (state: RootState, action: Action): ActionHandlerMap => ({
[TaskSharedActions.scheduleTaskWithTime.type]: () => {
const { task, dueWithTime, remindAt, isMoveToBacklog } = action as ReturnType<
typeof TaskSharedActions.scheduleTaskWithTime
>;
return handleScheduleTaskWithTime(
state,
task,
dueWithTime,
remindAt,
isMoveToBacklog,
);
},
[TaskSharedActions.reScheduleTaskWithTime.type]: () => {
const { task, dueWithTime, remindAt, isMoveToBacklog } = action as ReturnType<
typeof TaskSharedActions.reScheduleTaskWithTime
>;
return handleScheduleTaskWithTime(
state,
task,
dueWithTime,
remindAt,
isMoveToBacklog,
);
},
[TaskSharedActions.unscheduleTask.type]: () => {
const { id, isLeaveInToday } = action as ReturnType<
typeof TaskSharedActions.unscheduleTask
>;
return handleUnScheduleTask(state, id, isLeaveInToday);
},
[TaskSharedActions.dismissReminderOnly.type]: () => {
const { id } = action as ReturnType<typeof TaskSharedActions.dismissReminderOnly>;
return handleDismissReminderOnly(state, id);
},
[TaskSharedActions.planTasksForToday.type]: () => {
const {
taskIds,
today,
startOfNextDayDiffMs,
parentTaskMap = {},
isClearScheduledTime,
} = action as ReturnType<typeof TaskSharedActions.planTasksForToday>;
return handlePlanTasksForToday(
state,
taskIds,
parentTaskMap,
today,
startOfNextDayDiffMs,
isClearScheduledTime,
);
},
[TaskSharedActions.removeTasksFromTodayTag.type]: () => {
const { taskIds } = action as ReturnType<
typeof TaskSharedActions.removeTasksFromTodayTag
>;
return handleRemoveTasksFromTodayTag(state, taskIds);
},
[TaskSharedActions.localRemoveOverdueFromToday.type]: () => {
const { taskIds } = action as ReturnType<
typeof TaskSharedActions.localRemoveOverdueFromToday
>;
return handleRemoveTasksFromTodayTag(state, taskIds);
},
[TaskSharedActions.moveTaskInTodayTagList.type]: () => {
const { toTaskId, fromTaskId } = action as ReturnType<
typeof TaskSharedActions.moveTaskInTodayTagList
>;
return handleMoveTaskInTodayTagList(state, toTaskId, fromTaskId);
},
});
export const taskSharedSchedulingMetaReducer: MetaReducer = (
reducer: ActionReducer<RootState, Action>,
) => {
return (state: unknown, action: Action) => {
if (!state) return reducer(state as RootState | undefined, action);
const rootState = state as RootState;
const actionHandlers = createActionHandlers(rootState, action);
const handler = actionHandlers[action.type];
const updatedState = handler ? handler(rootState) : rootState;
return reducer(updatedState, action);
};
};