forked from callumalpass/tasknotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskContextMenu.ts
More file actions
1646 lines (1482 loc) · 47 KB
/
Copy pathTaskContextMenu.ts
File metadata and controls
1646 lines (1482 loc) · 47 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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Menu, Notice, TFile, type MenuItem, type TAbstractFile } from "obsidian";
import TaskNotesPlugin from "../main";
import { TaskDependency, TaskInfo } from "../types";
import { formatDateForStorage } from "../utils/dateUtils";
import { ReminderModal } from "../modals/ReminderModal";
import { CalendarExportService } from "../services/CalendarExportService";
import { showConfirmationModal } from "../modals/ConfirmationModal";
import { DateContextMenu } from "./DateContextMenu";
import { RecurrenceContextMenu } from "./RecurrenceContextMenu";
import { showTextInputModal } from "../modals/TextInputModal";
import { openTaskSelector } from "../modals/TaskSelectorWithCreateModal";
import { ProjectSelectModal } from "../modals/ProjectSelectModal";
import {
DEFAULT_DEPENDENCY_RELTYPE,
extractDependencyUid,
formatDependencyLink,
normalizeDependencyEntry,
} from "../utils/dependencyUtils";
import { generateLink } from "../utils/linkUtils";
import { ContextMenu } from "./ContextMenu";
import { buildTimeblockPrefillForTask } from "../utils/timeblockPrefillUtils";
import { TimeblockCreationModal } from "../modals/TimeblockCreationModal";
type SubmenuMenuItem = {
setSubmenu(): Menu;
dom?: HTMLElement;
domEl?: HTMLElement;
};
type FileExplorerView = {
revealInFolder(file: TFile): void;
};
type TaskStatusOption = {
label: string;
value: string;
color?: string;
icon?: string;
};
function getSubmenu(item: MenuItem): Menu {
return (item as unknown as SubmenuMenuItem).setSubmenu();
}
function getMenuItemElement(item: MenuItem): HTMLElement | null {
const menuItem = item as unknown as SubmenuMenuItem;
return menuItem.dom ?? menuItem.domEl ?? null;
}
export interface TaskContextMenuOptions {
task: TaskInfo;
plugin: TaskNotesPlugin;
targetDate: Date;
onUpdate?: () => void;
}
export class TaskContextMenu {
private menu: ContextMenu;
private options: TaskContextMenuOptions;
private targetDoc: Document = activeDocument;
constructor(options: TaskContextMenuOptions) {
this.menu = new ContextMenu();
this.options = options;
this.buildMenu();
}
private t(key: string, params?: Record<string, string | number>): string {
return this.options.plugin.i18n.translate(key, params);
}
private buildMenu(): void {
const { task, plugin } = this.options;
// Status submenu
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.status"));
item.setIcon("circle");
const submenu = getSubmenu(item);
this.addStatusOptions(submenu, task, plugin);
});
// Add completion toggle for recurring tasks
if (task.recurrence) {
this.menu.addSeparator();
const dateStr = formatDateForStorage(this.options.targetDate);
const isCompletedForDate = task.complete_instances?.includes(dateStr) || false;
this.menu.addItem((item) => {
item.setTitle(
isCompletedForDate
? this.t("contextMenus.task.markIncomplete")
: this.t("contextMenus.task.markComplete")
);
item.setIcon(isCompletedForDate ? "x" : "check");
item.onClick(async () => {
try {
await plugin.toggleRecurringTaskComplete(task, this.options.targetDate);
this.options.onUpdate?.();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("Error toggling recurring task completion:", {
error: errorMessage,
taskPath: task.path,
});
new Notice(
this.t("contextMenus.task.notices.toggleCompletionFailure", {
message: errorMessage,
})
);
}
});
});
const isSkippedForDate = task.skipped_instances?.includes(dateStr) || false;
this.menu.addItem((item) => {
item.setTitle(
isSkippedForDate
? this.t("contextMenus.task.unskipInstance")
: this.t("contextMenus.task.skipInstance")
);
item.setIcon(isSkippedForDate ? "undo" : "x-circle");
item.onClick(async () => {
try {
await plugin.taskService.toggleRecurringTaskSkipped(
task,
this.options.targetDate
);
this.options.onUpdate?.();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("Error toggling recurring task skip:", {
error: errorMessage,
taskPath: task.path,
});
new Notice(
this.t("contextMenus.task.notices.toggleSkipFailure", {
message: errorMessage,
})
);
}
});
});
}
this.menu.addSeparator();
// Priority submenu
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.priority"));
item.setIcon("star");
const submenu = getSubmenu(item);
this.addPriorityOptions(submenu, task, plugin);
});
this.menu.addSeparator();
// Due Date submenu
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.dueDate"));
item.setIcon("calendar");
const submenu = getSubmenu(item);
this.addDateOptions(
submenu,
task.due,
async (value: string | null) => {
try {
await plugin.updateTaskProperty(task, "due", value || undefined);
this.options.onUpdate?.();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("Error updating task due date:", {
error: errorMessage,
taskPath: task.path,
});
new Notice(
this.t("contextMenus.task.notices.updateDueDateFailure", {
message: errorMessage,
})
);
}
},
() => {
void plugin.openDueDateModal(task);
}
);
});
// Scheduled Date submenu
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.scheduledDate"));
item.setIcon("calendar-clock");
const submenu = getSubmenu(item);
this.addDateOptions(
submenu,
task.scheduled,
async (value: string | null) => {
try {
await plugin.updateTaskProperty(task, "scheduled", value || undefined);
this.options.onUpdate?.();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("Error updating task scheduled date:", {
error: errorMessage,
taskPath: task.path,
});
new Notice(
this.t("contextMenus.task.notices.updateScheduledFailure", {
message: errorMessage,
})
);
}
},
() => {
void plugin.openScheduledDateModal(task);
}
);
});
// Reminders submenu
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.reminders"));
item.setIcon("bell");
const submenu = getSubmenu(item);
// Quick Add sections
this.addQuickRemindersSection(
submenu,
task,
plugin,
"due",
this.t("contextMenus.task.remindBeforeDue")
);
this.addQuickRemindersSection(
submenu,
task,
plugin,
"scheduled",
this.t("contextMenus.task.remindBeforeScheduled")
);
submenu.addSeparator();
// Manage reminders
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.manageReminders"));
subItem.setIcon("settings");
subItem.onClick(() => {
const modal = new ReminderModal(plugin.app, plugin, task, (reminders) => {
void (async () => {
try {
await plugin.updateTaskProperty(
task,
"reminders",
reminders.length > 0 ? reminders : undefined
);
this.options.onUpdate?.();
} catch (error) {
console.error("Error updating reminders:", error);
new Notice(
this.t("contextMenus.task.notices.updateRemindersFailure")
);
}
})();
});
modal.open();
});
});
// Clear reminders (if any exist)
if (task.reminders && task.reminders.length > 0) {
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.clearReminders"));
subItem.setIcon("trash");
subItem.onClick(async () => {
try {
await plugin.updateTaskProperty(task, "reminders", undefined);
this.options.onUpdate?.();
} catch (error) {
console.error("Error clearing reminders:", error);
new Notice(this.t("contextMenus.task.notices.clearRemindersFailure"));
}
});
});
}
});
this.menu.addSeparator();
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.dependencies.title"));
item.setIcon("git-branch");
const submenu = getSubmenu(item);
this.addDependencyMenuItems(submenu, task, plugin);
});
// this.menu.addSeparator();
// Organization submenu (projects and subtasks)
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.organization.title"));
item.setIcon("folder-tree");
const submenu = getSubmenu(item);
this.addOrganizationMenuItems(submenu, task, plugin);
});
this.menu.addSeparator();
// Time Tracking
this.menu.addItem((item) => {
const activeSession = plugin.getActiveTimeSession(task);
item.setTitle(
activeSession
? this.t("contextMenus.task.stopTimeTracking")
: this.t("contextMenus.task.startTimeTracking")
);
item.setIcon(activeSession ? "pause" : "play");
item.onClick(async () => {
const activeSession = plugin.getActiveTimeSession(task);
if (activeSession) {
await plugin.stopTimeTracking(task);
} else {
await plugin.startTimeTracking(task);
}
this.options.onUpdate?.();
});
});
// Edit Time Entries
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.editTimeEntries"));
item.setIcon("clock");
item.onClick(() => {
plugin.openTimeEntryEditor(task);
});
});
// Create timeblock from task
if (plugin.settings.calendarViewSettings.enableTimeblocking) {
this.menu.addItem((item) => {
item.setTitle("Create timeblock");
item.setIcon("calendar-plus");
item.onClick(() => {
const prefill = buildTimeblockPrefillForTask(task, this.options.targetDate);
const modal = new TimeblockCreationModal(plugin.app, plugin, {
date: prefill.date,
startTime: prefill.startTime,
endTime: prefill.endTime,
prefilledTitle: task.title,
prefilledAttachmentPaths: [task.path],
});
modal.open();
});
});
}
// Archive/Unarchive
this.menu.addItem((item) => {
item.setTitle(
task.archived
? this.t("contextMenus.task.unarchive")
: this.t("contextMenus.task.archive")
);
item.setIcon(task.archived ? "archive-restore" : "archive");
item.onClick(async () => {
try {
await plugin.toggleTaskArchive(task);
this.options.onUpdate?.();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("Error toggling task archive:", {
error: errorMessage,
taskPath: task.path,
});
new Notice(
this.t("contextMenus.task.notices.archiveFailure", {
message: errorMessage,
})
);
}
});
});
this.menu.addSeparator();
// Open Note
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.openNote"));
item.setIcon("file-text");
item.onClick(() => {
const file = plugin.app.vault.getAbstractFileByPath(task.path);
if (file instanceof TFile) {
void plugin.app.workspace.getLeaf(false).openFile(file);
}
});
});
// Copy Task Title
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.copyTitle"));
item.setIcon("copy");
item.onClick(async () => {
try {
await navigator.clipboard.writeText(task.title);
new Notice(this.t("contextMenus.task.notices.copyTitleSuccess"));
} catch {
new Notice(this.t("contextMenus.task.notices.copyFailure"));
}
});
});
// Note actions submenu
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.noteActions"));
item.setIcon("file-text");
const submenu = getSubmenu(item);
// Get the file for the task
const file = plugin.app.vault.getAbstractFileByPath(task.path);
if (file instanceof TFile) {
// Try to populate with Obsidian's native file menu
try {
// Trigger the file-menu event to populate with default actions
plugin.app.workspace.trigger("file-menu", submenu, file, "file-explorer");
} catch {
console.debug("Native file menu not available, using fallback");
}
// Add common file actions (these will either supplement or replace the native menu)
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.rename"));
subItem.setIcon("pencil");
subItem.onClick(async () => {
try {
// Modal-based rename
const currentName = file.basename;
const newName = await showTextInputModal(plugin.app, {
title: this.t("contextMenus.task.renameTitle"),
placeholder: this.t("contextMenus.task.renamePlaceholder"),
initialValue: currentName,
});
if (newName && newName.trim() !== "" && newName !== currentName) {
// Ensure the new name has the correct extension
const extension = file.extension;
const finalName = newName.endsWith(`.${extension}`)
? newName
: `${newName}.${extension}`;
// Construct the new path
const newPath = file.parent
? `${file.parent.path}/${finalName}`
: finalName;
// Rename the file
await plugin.app.vault.rename(file, newPath);
new Notice(
this.t("contextMenus.task.notices.renameSuccess", {
name: finalName,
})
);
// Trigger update callback
if (this.options.onUpdate) {
this.options.onUpdate();
}
}
} catch (error) {
console.error("Error renaming file:", error);
new Notice(this.t("contextMenus.task.notices.renameFailure"));
}
});
});
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.delete"));
subItem.setIcon("trash");
subItem.onClick(async () => {
// Show confirmation and delete
const confirmed = await showConfirmationModal(plugin.app, {
title: this.t("contextMenus.task.deleteTitle"),
message: this.t("contextMenus.task.deleteMessage", { name: file.name }),
confirmText: this.t("contextMenus.task.deleteConfirm"),
cancelText: this.t("common.cancel"),
isDestructive: true,
});
if (confirmed) {
// Delete from Google Calendar before trashing file
if (
plugin.taskCalendarSyncService &&
task.googleCalendarEventId
) {
plugin.taskCalendarSyncService
.deleteTaskFromCalendarByPath(
task.path,
task.googleCalendarEventId
)
.catch((error) => {
console.warn(
"Failed to delete task from Google Calendar:",
error
);
});
}
void plugin.app.fileManager.trashFile(file);
}
});
});
submenu.addSeparator();
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.copyPath"));
subItem.setIcon("copy");
subItem.onClick(() => {
void navigator.clipboard
.writeText(file.path)
.then(() => {
new Notice(this.t("contextMenus.task.notices.copyPathSuccess"));
})
.catch(() => {
new Notice(this.t("contextMenus.task.notices.copyFailure"));
});
});
});
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.copyUrl"));
subItem.setIcon("link");
subItem.onClick(() => {
const url = `obsidian://open?vault=${encodeURIComponent(plugin.app.vault.getName())}&file=${encodeURIComponent(file.path)}`;
void navigator.clipboard
.writeText(url)
.then(() => {
new Notice(this.t("contextMenus.task.notices.copyUrlSuccess"));
})
.catch(() => {
new Notice(this.t("contextMenus.task.notices.copyFailure"));
});
});
});
submenu.addSeparator();
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.showInExplorer"));
subItem.setIcon("folder-open");
subItem.onClick(() => {
// Reveal file in file explorer
void plugin.app.workspace
.getLeaf()
.setViewState({
type: "file-explorer",
state: {},
})
.then(() => {
// Focus the file in the explorer
const fileExplorer =
plugin.app.workspace.getLeavesOfType("file-explorer")[0];
if (fileExplorer?.view && "revealInFolder" in fileExplorer.view) {
(fileExplorer.view as FileExplorerView).revealInFolder(file);
}
})
.catch((error) => {
console.warn("Failed to reveal task in file explorer:", error);
});
});
});
}
});
this.menu.addSeparator();
// Add to Calendar submenu
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.addToCalendar"));
item.setIcon("calendar-plus");
const submenu = getSubmenu(item);
// Google Calendar
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.calendar.google"));
subItem.setIcon("external-link");
subItem.onClick(() => {
CalendarExportService.openCalendarURL(
{
type: "google",
task: task,
useScheduledAsDue: true,
},
this.t.bind(this)
);
});
});
// Outlook Calendar
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.calendar.outlook"));
subItem.setIcon("external-link");
subItem.onClick(() => {
CalendarExportService.openCalendarURL(
{
type: "outlook",
task: task,
useScheduledAsDue: true,
},
this.t.bind(this)
);
});
});
// Yahoo Calendar
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.calendar.yahoo"));
subItem.setIcon("external-link");
subItem.onClick(() => {
CalendarExportService.openCalendarURL(
{
type: "yahoo",
task: task,
useScheduledAsDue: true,
},
this.t.bind(this)
);
});
});
submenu.addSeparator();
// Download ICS file
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.calendar.downloadIcs"));
subItem.setIcon("download");
subItem.onClick(() => {
CalendarExportService.downloadICSFile(task, this.t.bind(this));
});
});
submenu.addSeparator();
// Sync to Google Calendar (via API)
submenu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.calendar.syncToGoogle"));
subItem.setIcon("refresh-cw");
subItem.onClick(async () => {
if (!plugin.taskCalendarSyncService?.isEnabled()) {
new Notice(this.t("contextMenus.task.calendar.syncToGoogleNotConfigured"));
return;
}
try {
await plugin.taskCalendarSyncService.syncTaskToCalendar(task);
new Notice(this.t("contextMenus.task.calendar.syncToGoogleSuccess"));
this.options.onUpdate?.();
} catch (error) {
console.error("Failed to sync task to Google Calendar:", error);
new Notice(this.t("contextMenus.task.calendar.syncToGoogleFailed"));
}
});
});
});
this.menu.addSeparator();
// Recurrence submenu
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.recurrence"));
item.setIcon("refresh-ccw");
const submenu = getSubmenu(item);
const currentRecurrence =
typeof task.recurrence === "string" ? task.recurrence : undefined;
this.addRecurrenceOptions(
submenu,
currentRecurrence,
async (value: string | null) => {
try {
await plugin.updateTaskProperty(task, "recurrence", value || undefined);
this.options.onUpdate?.();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("Error updating task recurrence:", {
error: errorMessage,
taskPath: task.path,
});
new Notice(
this.t("contextMenus.task.notices.updateRecurrenceFailure", {
message: errorMessage,
})
);
}
},
plugin
);
});
this.menu.addSeparator();
// Create subtask
this.menu.addItem((item) => {
item.setTitle(this.t("contextMenus.task.createSubtask"));
item.setIcon("plus");
item.onClick(() => {
const taskFile = plugin.app.vault.getAbstractFileByPath(task.path);
if (taskFile instanceof TFile) {
const projectReference = generateLink(
plugin.app,
taskFile,
task.path,
"",
"",
plugin.settings.useFrontmatterMarkdownLinks
);
plugin.openTaskCreationModal({
projects: [projectReference],
});
}
});
});
// Apply main menu icon colors after menu is built
window.setTimeout(() => {
this.updateMainMenuIconColors(task, plugin);
}, 10);
}
private addDependencyMenuItems(menu: Menu, task: TaskInfo, plugin: TaskNotesPlugin): void {
menu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.dependencies.addBlockedBy"));
subItem.setIcon("link-2");
subItem.onClick(() => {
this.menu.hide();
void this.openBlockedBySelector(task, plugin);
});
});
const blockedByEntries = task.blockedBy ?? [];
if (blockedByEntries.length > 0) {
menu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.dependencies.removeBlockedBy"));
subItem.setIcon("unlink");
const innerMenu = getSubmenu(subItem);
blockedByEntries.forEach((entry, index) => {
innerMenu.addItem((item) => {
const uid =
extractDependencyUid(entry) ||
this.t("contextMenus.task.dependencies.unknownDependency");
item.setTitle(uid);
item.onClick(async () => {
try {
const remaining = blockedByEntries.filter((_, i) => i !== index);
const updatedTask = await plugin.updateTaskProperty(
task,
"blockedBy",
remaining.length > 0 ? remaining : undefined
);
Object.assign(task, updatedTask);
new Notice(
this.t(
"contextMenus.task.dependencies.notices.blockedByRemoved"
)
);
this.options.onUpdate?.();
} catch (error) {
console.error("Failed to remove blocked-by dependency:", error);
new Notice(
this.t("contextMenus.task.dependencies.notices.updateFailed")
);
}
});
});
});
});
}
menu.addSeparator();
menu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.dependencies.addBlocking"));
subItem.setIcon("git-branch-plus");
subItem.onClick(() => {
this.menu.hide();
void this.openBlockingSelector(task, plugin);
});
});
const blockingEntries = task.blocking ?? [];
if (blockingEntries.length > 0) {
menu.addItem((subItem) => {
subItem.setTitle(this.t("contextMenus.task.dependencies.removeBlocking"));
subItem.setIcon("git-branch-minus");
const innerMenu = getSubmenu(subItem);
blockingEntries.forEach((path) => {
const file = plugin.app.vault.getAbstractFileByPath(path);
const label =
file instanceof TFile
? plugin.app.metadataCache.fileToLinktext(file, task.path, false)
: path.split("/").pop() || path;
innerMenu.addItem((item) => {
item.setTitle(label);
item.onClick(async () => {
try {
await plugin.taskService.updateBlockingRelationships(
task,
[],
[path],
{}
);
const refreshed = await plugin.cacheManager.getTaskInfo(task.path);
if (refreshed) {
Object.assign(task, refreshed);
}
new Notice(
this.t("contextMenus.task.dependencies.notices.blockingRemoved")
);
this.options.onUpdate?.();
} catch (error) {
console.error("Failed to remove blocking dependency:", error);
new Notice(
this.t("contextMenus.task.dependencies.notices.updateFailed")
);
}
});
});
});
});
}
}
private dedupeDependencyEntries(entries: Array<TaskDependency | string>): TaskDependency[] {
const seen = new Map<string, TaskDependency>();
for (const entry of entries) {
const normalized = normalizeDependencyEntry(entry);
if (!normalized) {
continue;
}
const key = this.getDependencyKey(normalized);
if (!seen.has(key)) {
seen.set(key, normalized);
}
}
return Array.from(seen.values());
}
private async openBlockedBySelector(task: TaskInfo, plugin: TaskNotesPlugin): Promise<void> {
const existingUids = new Set(
(Array.isArray(task.blockedBy) ? task.blockedBy : []).map(
(dependency) => dependency.uid
)
);
await this.openTaskDependencySelector(
plugin,
(candidate) => {
if (candidate.path === task.path) return false;
const candidateUid = formatDependencyLink(
plugin.app,
task.path,
candidate.path,
plugin.settings.useFrontmatterMarkdownLinks
);
return !existingUids.has(candidateUid);
},
async (selected) => {
await this.handleBlockedBySelection(task, plugin, selected);
}
);
}
private async openBlockingSelector(task: TaskInfo, plugin: TaskNotesPlugin): Promise<void> {
const existingPaths = new Set(task.blocking ?? []);
await this.openTaskDependencySelector(
plugin,
(candidate) => {
if (candidate.path === task.path) return false;
return !existingPaths.has(candidate.path);
},
async (selected) => {
await this.handleBlockingSelection(task, plugin, selected);
}
);
}
private async openTaskDependencySelector(
plugin: TaskNotesPlugin,
filter: (candidate: TaskInfo) => boolean,
onSelect: (selected: TaskInfo) => Promise<void>
): Promise<void> {
try {
const allTasks = await plugin.cacheManager.getAllTasks();
const candidates = allTasks.filter(filter);
if (candidates.length === 0) {
new Notice(this.t("contextMenus.task.dependencies.notices.noEligibleTasks"));
return;
}
openTaskSelector(plugin, candidates, (task) => {
if (!task) return;
void onSelect(task);
});
} catch (error) {
console.error("Failed to open task selector for dependencies:", error);
new Notice(this.t("contextMenus.task.dependencies.notices.updateFailed"));
}
}
private async handleBlockedBySelection(
task: TaskInfo,
plugin: TaskNotesPlugin,
selectedTask: TaskInfo
): Promise<void> {
if (selectedTask.path === task.path) {
return;
}
try {
const dependency: TaskDependency = {
uid: formatDependencyLink(
plugin.app,
task.path,
selectedTask.path,
plugin.settings.useFrontmatterMarkdownLinks
),
reltype: DEFAULT_DEPENDENCY_RELTYPE,
};
const existing = Array.isArray(task.blockedBy) ? task.blockedBy : [];
const combined = this.dedupeDependencyEntries([...existing, dependency]);
if (combined.length === existing.length) {
return;
}
const updatedTask = await plugin.updateTaskProperty(task, "blockedBy", combined);
Object.assign(task, updatedTask);
new Notice(
this.t("contextMenus.task.dependencies.notices.blockedByAdded", { count: 1 })
);
this.options.onUpdate?.();
} catch (error) {
console.error("Failed to add blocked-by dependency via selector:", error);
new Notice(this.t("contextMenus.task.dependencies.notices.updateFailed"));
}
}
private async handleBlockingSelection(
task: TaskInfo,
plugin: TaskNotesPlugin,
selectedTask: TaskInfo
): Promise<void> {
const blockedPath = selectedTask.path;
if (blockedPath === task.path) {
return;
}
if (task.blocking?.includes(blockedPath)) {
return;
}
try {
const rawEntry: TaskDependency = {
uid: formatDependencyLink(
plugin.app,
blockedPath,
task.path,
plugin.settings.useFrontmatterMarkdownLinks
),
reltype: DEFAULT_DEPENDENCY_RELTYPE,
};
await plugin.taskService.updateBlockingRelationships(task, [blockedPath], [], {
[blockedPath]: rawEntry,
});
const refreshed = await plugin.cacheManager.getTaskInfo(task.path);
if (refreshed) {
Object.assign(task, refreshed);
} else if (Array.isArray(task.blocking)) {
task.blocking = Array.from(new Set([...task.blocking, blockedPath]));
} else {
task.blocking = [blockedPath];
}
new Notice(
this.t("contextMenus.task.dependencies.notices.blockingAdded", { count: 1 })
);
this.options.onUpdate?.();
} catch (error) {
console.error("Failed to add blocking dependency via selector:", error);
new Notice(this.t("contextMenus.task.dependencies.notices.updateFailed"));
}
}