-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathtodoist-shortcuts.js
5223 lines (4815 loc) · 158 KB
/
todoist-shortcuts.js
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
/* global svgs, TodoistShortcutsMousetrap */
(function() {
// Set this to true to get more log output.
const DEBUG = false;
const IS_CHROME =
/Chrom/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
const IS_SAFARI =
/Safari/.test(navigator.userAgent) && /Apple/.test(navigator.vendor);
// Cursor navigation.
const CURSOR_BINDINGS = [
[['j', 'down'], cursorDown],
[['k', 'up'], cursorUp],
[['h', 'left'], cursorLeft],
[['l', 'right'], cursorRight],
['^', cursorFirst],
['$', cursorLast],
['{', cursorUpSection],
['}', cursorDownSection],
];
// Here's where the keybindings get specified. Of course, feel free to modify
// this list, or modify this script in general.
const KEY_BINDINGS = [].concat(CURSOR_BINDINGS, [
// Navigation
['g', navigate],
['G', navigateToTask],
['`', nextLeftMenuItem],
['shift+`', prevLeftMenuItem],
// Manipulation of tasks at cursor
['enter', edit],
['shift+enter', followLink],
['shift+o', addAbove],
['o', addBelow],
['a', addTaskBottom],
['shift+a', addTaskTop],
['i', openTaskView],
['c', openComments],
['shift+r', openReminders],
['+', openAssign],
['>', openDeadline],
[['shift+j', 'shift+down'], moveDown],
[['shift+k', 'shift+up'], moveUp],
[['shift+h', 'shift+left'], moveOut],
[['shift+l', 'shift+right'], moveIn],
// Selection
['x', toggleSelect],
['* a', selectAllTasks],
['* n', deselectAllTasks],
['* o', selectAllOverdue],
['* s', selectSection],
['* 1', selectPriority('1')],
['* 2', selectPriority('2')],
['* 3', selectPriority('3')],
[['* 4', '* 0'], selectPriority('4')],
[['* h', '* left'], collapseAll],
[['* l', '* right'], expandAll],
// Manipulation of selected tasks
['t', schedule],
['shift+t', scheduleText],
['alt+t', scheduleTime],
['d', done],
[['e', '#'], deleteTasks],
['&', duplicateTasks],
['v', moveToProject],
[['y', '@'], openLabelMenu],
['1', setPriority('4')],
['2', setPriority('3')],
['3', setPriority('2')],
[['4', '0'], setPriority('1')],
['shift+c', toggleTimer],
// Projects
['shift+p', openCurrentProjectLeftNavMenu],
// Sorting
['s', sortByDate],
['p', sortByPriority],
['n', sortByName],
['r', sortByAssignee],
// Bulk reschedule / move modes were removed
['* t', notifyBulkActionsRemoved],
['* v', notifyBulkActionsRemoved],
// Other
[['u', 'z', 'ctrl+z'], undo],
['q', quickAdd],
['m', toggleLeftNav],
[['f', '/'], focusSearch],
['!', openNotifications],
['?', openHelpModal],
['ctrl+s', sync],
['ctrl+k', openCommandMenu],
['ctrl+shift+,', copyCursorOrSelectedUrls],
['ctrl+,', copyCursorOrSelectedTitles],
['ctrl+c', copyCursorOrSelectedAsMarkdown],
['ctrl+shift+/', openRandomTask],
['w', openMoreActionsMenu],
// See https://github.com/mgsloan/todoist-shortcuts/issues/30
// [???, importFromTemplate],
]);
const DEFAULT_KEYMAP = 'default';
// Build cursor movement bindings that can be used in schedule mode
const SCHEDULE_CURSOR_BINDINGS = [];
for (const binding of CURSOR_BINDINGS) {
SCHEDULE_CURSOR_BINDINGS.push([
binding[0],
sequence([closeContextMenus, binding[1], schedule]),
]);
}
// Scheduling keybindings (used when scheduler is open)
const SCHEDULE_BINDINGS = [].concat(SCHEDULE_CURSOR_BINDINGS, [
['c', scheduleToday],
['t', schedulePlusN(1)],
['w', scheduleNextWeek],
['n', scheduleNextWeekend],
['m', scheduleNextMonth],
[['s', 'p'], schedulePostpone],
['r', unschedule],
['0', scheduleToday],
['1', schedulePlusN(1)],
['2', schedulePlusN(2)],
['3', schedulePlusN(3)],
['4', schedulePlusN(4)],
['5', schedulePlusN(5)],
['6', schedulePlusN(6)],
['7', schedulePlusN(7)],
['8', schedulePlusN(8)],
['9', schedulePlusN(9)],
['alt+t', scheduleTime],
['shift+t', scheduleText],
['escape', closeContextMenus],
// See #256 for why this is no longer needed
// ['fallback', schedulerFallback],
// See #252 for why these are disabled.
[['j', 'k', 'up', 'down'], noop],
]);
const SCHEDULE_KEYMAP = 'schedule';
const TASK_VIEW_BINDINGS = [
['enter', taskViewEdit],
['d', taskViewDone],
[['i', 'escape'], taskViewClose],
['h', taskViewParent],
['j', taskViewNext],
['k', taskViewPrevious],
['c', taskViewComments],
// TODO(#94): proper bindings for o / O.
[['q', 'a', 'A', 'o', 'O'], taskViewAddSubtask],
['t', taskViewSchedule],
['shift+t', taskViewScheduleText],
['+', taskViewOpenAssign],
['v', taskViewMoveToProject],
[['y', '@'], taskViewLabel],
['1', taskViewSetPriority('1')],
['2', taskViewSetPriority('2')],
['3', taskViewSetPriority('3')],
[['4', '0'], taskViewSetPriority('4')],
['shift+r', taskViewOpenReminders],
[['e', '#'], taskViewDelete],
['shift+c', taskViewToggleTimer],
['ctrl+shift+/', () => {
taskViewClose();
openRandomTask();
}],
];
const TASK_VIEW_KEYMAP = 'task_view';
const MENU_LIST_BINDINGS = [
[['j', 'down', 'tab'], nextMenuListItem],
[['k', 'up', 'shift+tab'], prevMenuListItem],
[['enter', 'space'], selectMenuListItem],
];
const MENU_LIST_KEYMAP = 'menu_list';
// Keycode constants
const UP_ARROW_KEYCODE = 38;
const DOWN_ARROW_KEYCODE = 40;
const BACKSPACE_KEYCODE = 8;
const ENTER_KEYCODE = 13;
const ESCAPE_KEYCODE = 27;
// Navigation mode uses its own key handler.
const NAVIGATE_BINDINGS = [['fallback', handleNavigateKey]];
const NAVIGATE_KEYMAP = 'navigate';
// Keymap used when there is a floating window.
const POPUP_BINDINGS = [];
const POPUP_KEYMAP = 'popup';
// Which selection-oriented commands to apply to the cursor if there is no
// selection. A few possible values:
//
// * "none" - never apply selection oriented commands to the cursor
//
// * "most" - apply to all commands that are easy to manually undo (everything
// but done / archive / delete)
//
// * "all" (default) - apply to all selection-oriented commands
//
const WHAT_CURSOR_APPLIES_TO = 'all';
// 'navigate' (g) attempts to assign keys to items based on their names. In
// some case there might not be a concise labeling. This sets the limit on key
// sequence length for things based on prefixes.
const MAX_NAVIGATE_PREFIX = 2;
const TODOIST_SHORTCUTS_TIP = 'todoist_shortcuts_tip';
const TODOIST_SHORTCUTS_TIP_TYPED = 'todoist_shortcuts_tip_typed';
const TODOIST_SHORTCUTS_WARNING = 'todoist_shortcuts_warning';
const TODOIST_SHORTCUTS_HELP = 'todoist_shortcuts_help';
const TODOIST_SHORTCUTS_HELP_CONTAINER = 'todoist_shortcuts_help_container';
const TODOIST_SHORTCUTS_GITHUB = 'https://github.com/mgsloan/todoist-shortcuts';
// This user script will get run on iframes and other todoist pages. Should
// skip running anything if #todoist_app doesn't exist.
const todoistRootDiv = document.getElementById('todoist_app');
if (!todoistRootDiv) throw new Error('no div with id "todoist_app"');
// Set on initialization to mousetrap instance.
let mousetrap = null;
/*****************************************************************************
* Options
*/
let options = {};
function loadOptions() {
try {
const serializedOptions =
document.body.getAttribute('data-todoist-shortcuts-options');
if (!serializedOptions) throw new Error('Missing options data');
options = JSON.parse(serializedOptions);
info('Loaded options:', options);
} catch (e) {
error('ignoring error loading options (will use defaults instead):', e);
}
}
function getMouseBehaviorOption() {
const result = options['mouse-behavior'];
if (!result) {
return 'focus-follows-mouse';
}
return result;
}
function getCursorMovementOption() {
const result = options['cursor-movement'];
if (!result) {
return 'follows-task-within-section';
}
return result;
}
/*****************************************************************************
* Action combiners
*/
// Take multiple actions (functions that take no arguments), and run them in
// sequence.
// eslint-disable-next-line no-unused-vars
function sequence(actions) {
return () => {
for (let i = 0; i < actions.length; i++) {
actions[i]();
}
};
}
// If the condition is true, runs the first action, otherwise runs the second.
// eslint-disable-next-line no-unused-vars
function ifThenElse(condition, calendarAction, normalAction) {
return () => {
if (condition()) {
calendarAction();
} else {
normalAction();
}
};
}
/*****************************************************************************
* Actions
*/
// Move the cursor up and down.
function cursorDown() {
const cursorChanged = modifyCursorIndex((ix) => ix + 1);
if (!cursorChanged && isUpcomingView()) {
scrollTaskToTop(getCursor());
}
}
function cursorUp() {
const cursorChanged = modifyCursorIndex((ix) => ix - 1);
if (!cursorChanged && isUpcomingView()) {
info('scrolling task to bottom');
scrollTaskToBottom(getCursor());
}
}
// Move the cursor to first / last task.
function cursorFirst() {
disabledWithLazyLoading('Cursoring first task', () => {
setCursorToFirstTask('scroll');
});
}
function cursorLast() {
disabledWithLazyLoading('Cursoring last task', () => {
setCursorToLastTask('scroll');
});
}
function cursorUpSection() {
disabledWithLazyLoading('Moving cursor up a section', () => {
const cursor = requireCursor();
let section = getSection(cursor);
section = findParent(section, matchingTag('li')) || section;
let firstTask = getFirstTaskIn(section);
if (firstTask && !sameElement(cursor)(firstTask)) {
// Not on first task, so move the cursor.
setCursor(firstTask, 'scroll');
} else {
// If already on the first task of this section, then select
// first task of prior populated section, if any exists.
section = section.previousSibling;
for (; section; section = section.previousSibling) {
firstTask = getFirstTaskIn(section);
if (firstTask) {
setCursor(firstTask, 'scroll');
return;
}
}
}
});
}
function cursorDownSection() {
disabledWithLazyLoading('Moving cursor down a section', () => {
const cursor = requireCursor();
let startSection = getSection(cursor);
startSection =
findParent(startSection, matchingTag('li')) || startSection;
let section = startSection.nextSibling;
for (; section; section = section.nextSibling) {
debug('section = ', section);
const firstTask = getFirstTaskIn(section);
if (firstTask) {
setCursor(firstTask, 'scroll');
return;
}
}
// If execution has reached this point, then we must already be
// on the last section.
const lastTask = getLastTaskInSection(startSection);
warn('Already on last section. lastTask =', lastTask);
if (lastTask) {
setCursor(lastTask, 'scroll');
}
});
}
// Edit the task under the cursor.
function edit() {
clickTaskEdit(requireCursor());
}
// Follow the first link of the task under the cursor.
function followLink() {
const contentClass = 'task_list_item__content';
withUniqueClass(requireCursor(), contentClass, all, (content) => {
const link = getFirstTag(content, 'a');
if (link) {
if (IS_CHROME) {
const middleClick =
new MouseEvent( 'click', {'button': 1, 'which': 2});
link.dispatchEvent(middleClick);
} else {
click(link);
}
} else {
info('Didn\'t find a link to click.');
}
});
}
// Toggles selection of the task focused by the cursor.
function toggleSelect() {
toggleSelectTask(requireCursor());
}
// Selects the task focused by the cursor.
// eslint-disable-next-line no-unused-vars
function select() {
selectTask(requireCursor());
}
// Deselects the task focused by the cursor.
// eslint-disable-next-line no-unused-vars
function deselect() {
deselectTask(requireCursor());
}
// Clicks the 'schedule' link when tasks are selected. If
// WHAT_CURSOR_APPLIES_TO is 'all' or 'most', then instead applies to the
// cursor if there is no selection.
function schedule() {
const mutateCursor = getCursorToMutate();
if (mutateCursor) {
clickTaskSchedule(mutateCursor);
blurSchedulerInput();
} else {
const query = 'button[data-action-hint="multi-select-toolbar-scheduler"]';
withUnique(document, query, (button) => {
click(button);
blurSchedulerInput();
});
}
}
// Edits the task under the cursor and focuses the textual representation of
// when the task is scheduled. Only works for the cursor, not for the
// selection.
function scheduleText() {
const scheduler = findScheduler();
if (scheduler) {
withTag(scheduler, 'input', (el) => el.focus() );
return;
}
const mutateCursor = getCursorToMutate();
if (mutateCursor) {
clickTaskSchedule(mutateCursor);
} else {
withUnique(
document,
'button[data-action-hint="multi-select-toolbar-scheduler"]',
click,
);
}
}
function scheduleTime() {
if (!findScheduler()) {
scheduleText();
}
setTimeout(() => {
// TODO: less fragile way to find the "Time" button than relying
// on no other buttons having this attribute.
const success = withUnique(document, '.scheduler button[aria-controls]',
(button) => {
click(button);
return true;
});
// Fallback on english text matching if the above doesn't work.
if (!success) {
withUniqueTag(findScheduler(), 'button', matchingText('Time'), click);
}
focusTimeInput();
}, 50);
}
function openDeadline() {
const mutateCursor = getCursorToMutate();
if (mutateCursor) {
clickTaskEdit(mutateCursor);
withQuery(document, '[aria-label="Set deadline"]', click);
// Todoist seems to put back the focus, so try a few times to blur.
blurSchedulerInput();
setTimeout(blurSchedulerInput, 20);
setTimeout(blurSchedulerInput, 50);
setTimeout(blurSchedulerInput, 100);
}
}
// Click 'today' in schedule. Only does anything if schedule is open.
function scheduleToday() {
withScheduler(
'scheduleToday',
(scheduler) => {
withUniqueTag(
scheduler,
'button',
matchingAttr('data-track', 'scheduler|date_shortcut_today'),
click,
);
});
}
// Click 'next week' in schedule. Only does anything if schedule is open.
function scheduleNextWeek() {
const date = new Date();
const day = date.getDay();
if (day === 0) {
schedulePlusN(1)();
} else if (day > 0) {
schedulePlusN(8 - day)();
}
}
// Click 'next weekend' in schedule. Only does anything if schedule is open.
function scheduleNextWeekend() {
withScheduler(
'scheduleNextWeekend',
(scheduler) => {
withUniqueTag(
scheduler,
'button',
matchingAttr('data-track', 'scheduler|date_shortcut_nextweekend'),
click,
);
});
}
// Click 'next month' in schedule. Only does anything if schedule is open.
function scheduleNextMonth() {
withScheduler(
'scheduleNextMonth',
(scheduler) => {
withUniqueTag(
scheduler,
'button',
matchingAttr('data-track', 'scheduler|date_shortcut_nextmonth'),
click,
);
});
}
// Clicks 'postpone' in scheduler.
function schedulePostpone() {
withScheduler(
'schedulePostpone',
(scheduler) => {
withUniqueTag(
scheduler,
'button',
matchingAttr('data-track',
'scheduler|date_shortcut_postpone'),
click,
);
});
}
// Clicks date on scheduler 1-9 days in the future
function schedulePlusN(n) {
return () => {
const date = new Date();
date.setDate(date.getDate() + n);
buttonAriaLabel = dateToIsoFormatUsingCurrentTimezone(date);
withScheduler(
'schedulePlusN',
(scheduler) => {
withUniqueTag(
scheduler,
'button',
matchingAttr('aria-label', buttonAriaLabel),
click,
);
});
};
}
// Click 'no due date' in schedule. Only does anything if schedule is open.
function unschedule() {
withScheduler(
'unschedule',
(scheduler) => {
withUniqueTag(
scheduler,
'button',
matchingAttr('data-track', 'scheduler|date_shortcut_nodate'),
click,
);
});
}
// Clicks 'Move to project' for the selection. If WHAT_CURSOR_APPLIES_TO is
// 'all' or 'most', then instead applies to the cursor if there is no
// selection.
function moveToProject() {
const mutateCursor = getCursorToMutate();
if (mutateCursor) {
// TODO: Didn't dig into it too much but this seems to be
// inscrutably broken.For now instead just selecting a task
// and then using the multi-task move which works.
//
// clickTaskMenu(
// mutateCursor,
// 'task-overflow-menu-move-to-project',
// false);
selectTask(mutateCursor);
}
withUnique(
document,
'button[data-action-hint="multi-select-toolbar-project-picker"]',
click,
);
}
// Clicks 'Move to project' for the selection, and moves to the
// named project.
// eslint-disable-next-line no-unused-vars
function moveToProjectNamed(projectName) {
return () => {
const mutateCursor = getCursorToMutate();
if (mutateCursor) {
clickTaskMenu(
mutateCursor,
'task-overflow-menu-move-to-project',
false);
withUniqueClass(
document,
'popper',
hasChild('[aria-label="'+projectName+'"]'),
(menu) => {
withUniqueTag(
menu,
'li',
matchingAttr('aria-label', projectName),
click);
});
} else {
withUnique(
document,
'button[data-action-hint="multi-select-toolbar-project-picker"]',
(menu) => {
click(menu);
withUniqueClass(
document,
'popper',
hasChild('[aria-label="'+projectName+'"]'),
(menu) => {
withUniqueTag(
menu,
'li',
matchingAttr('aria-label', projectName),
click);
});
},
);
}
};
}
// Sets the priority of the selected tasks to the specified level. If
// WHAT_CURSOR_APPLIES_TO is 'all' or 'most', then instead applies to the
// cursor if there is no selection.
//
// NOTE: this returns a function so that it can be used conveniently in the
// keybindings.
function setPriority(level) {
return () => {
const mutateCursor = getCursorToMutate();
if (mutateCursor) {
clickTaskEdit(mutateCursor);
withQuery(document,
'[data-action-hint="task-actions-priority-picker"]',
click);
withUniqueClass(document, 'priority_picker', all, (menu) => {
clickPriorityMenu(menu, level);
});
// Click save button.
withUnique(
document,
'div[data-testid="task-editor-action-buttons"] ' +
'button[type="submit"]',
click,
);
} else {
withUnique(
document,
'button[data-action-hint="multi-select-toolbar-priority-picker"]',
click,
);
withUniqueClass(document, 'priority_picker', all, (menu) => {
clickPriorityMenu(menu, level);
});
}
};
}
// Adds tasks matching the specified priority level to the current selection,
// even if they are hidden by collapsing.
//
// NOTE: this returns a function so that it can be used conveniently in the
// keybindings.
function selectPriority(level) {
return () => {
const actualLevel = invertPriorityLevel(level);
const allTasks = getTasks('include-collapsed');
const selected = getSelectedTaskKeys();
let modified = false;
for (const task of allTasks) {
if (getTaskPriority(task) === actualLevel) {
selected[getTaskKey(task)] = true;
modified = true;
}
}
if (modified) {
setSelections(selected);
}
};
}
// Mark all the tasks as completed. If WHAT_CURSOR_APPLIES_TO is 'all', then
// instead applies to the cursor if there is no selection.
function done() {
const mutateCursor = getCursorToMutate('dangerous');
if (mutateCursor) {
clickTaskDone(mutateCursor);
} else {
withUnique(
openMoreMenu(),
'[data-action-hint="multi-select-toolbar-overflow-menu-complete"]',
click,
);
}
}
// Delete selected tasks. Todoist will prompt for deletion. Since
// todoist prompts, this is not treated as a 'dangerous' action. As
// such, if WHAT_CURSOR_APPLIES_TO is 'all' or 'most', then instead
// applies to the cursor if there is no selection.
function deleteTasks() {
const mutateCursor = getCursorToMutate();
if (mutateCursor) {
clickTaskMenu(mutateCursor, 'task-overflow-menu-delete', false);
} else {
withUnique(
openMoreMenu(),
'[data-action-hint="multi-select-toolbar-overflow-menu-delete"]',
click,
);
}
}
function duplicateTasks() {
const mutateCursor = getCursorToMutate();
if (mutateCursor) {
clickTaskMenu(mutateCursor, 'task-overflow-menu-duplicate', false);
} else {
withUnique(
openMoreMenu(),
'[data-action-hint="multi-select-toolbar-overflow-menu-duplicate"]',
click,
);
}
}
// Opens the label toggling menu.
function openLabelMenu() {
if (isEmptyMap(getSelectedTaskKeys())) {
select();
}
withUniqueClass(document, 'multi_select_toolbar', all, (toolbar) => {
withUniqueTag(
toolbar,
'button',
matchingAction('multi-select-toolbar-label-picker'),
click,
);
});
}
const TIMER_CLASSES = [
'toggl-button',
'clockify-button-inactive',
'clockify-button-active',
];
// If toggl-button or clockify extension is in use, clicks the
// button element in the task.
function toggleTimer() {
withUniqueClass(requireCursor(), TIMER_CLASSES, all, click);
}
// Toggles collapse / expand of a task, if it has children.
function toggleCollapse(task) {
withUnique(
task ? task : requireCursor(),
'[data-action-hint=task-toggle-collapse]',
click);
}
// Collapse cursor. If it is already collapsed, select and collapse parent.
function cursorLeft() {
if (checkTaskExpanded(requireCursor())) {
toggleCollapse();
} else {
selectAndCollapseParent();
}
}
// Expand cursor and move down.
function cursorRight() {
if (checkTaskCollapsed(requireCursor())) {
toggleCollapse();
cursorDown();
}
}
// Collapses or expands task under the cursor, that have children. Does
// nothing if it's already in the desired state.
function collapse(task0) {
const task = task0 ? task0 : requireCursor();
if (checkTaskExpanded(task)) {
toggleCollapse(task);
}
}
// eslint-disable-next-line no-unused-vars
function expand(task0) {
const task = task0 ? task0 : requireCursor();
if (checkTaskCollapsed(task)) {
toggleCollapse(task);
}
}
// Move selection to parent project.
function selectAndCollapseParent() {
const cursor = requireCursor();
const tasks = getTasks();
for (let i = 0; i < tasks.length; i++) {
let task = tasks[i];
if (task === cursor) {
for (let j = i; j >= 0; j--) {
task = tasks[j];
if (getUniqueClass(task, 'down')) {
setCursor(task, 'scroll');
toggleCollapse(task);
break;
}
// If we hit the top level, then stop looking for a parent.
if (getIndentClass(task) === 'indent_1') {
break;
}
}
break;
}
}
}
// Collapses or expands all tasks.
function collapseAll() {
repeatedlyClickArrows('down');
}
function expandAll() {
repeatedlyClickArrows('right');
}
// Clears all selections.
function deselectAllTasks() {
click(document.body);
}
// Selects all tasks, even those hidden by collapsing.
function selectAllTasks() {
const allTasks = getTasks('include-collapsed');
for (let i = 0; i < allTasks.length; i++) {
setTimeout(() => selectTask(allTasks[i]));
}
}
// Selects all overdue tasks.
function selectAllOverdue() {
for (const task of getTasks()) {
if (getUniqueClass(task, 'date_overdue')) {
setTimeout(() => selectTask(task));
}
}
}
function selectSection() {
const cursor = getCursor();
if (!cursor) {
return;
}
const section = getSection(cursor);
for (const task of getTasks()) {
if (getSection(task) === section) {
setTimeout(() => selectTask(task));
}
}
}
function addTaskBottom() {
addToSectionContaining(getCursor());
}
function addTaskTop() {
if (viewMode === 'agenda') {
quickAdd();
} else {
const tasks = getTasks();
if (tasks.length > 0) {
addAboveTask(tasks[0]);
} else {
quickAdd();
}
}
}
function scrollTaskEditorIntoView() {
withUniqueClass(document, 'task_editor', all, (editor) => {
verticalScrollIntoView(editor, 0, true, 0.6);
});
}
// Add a task above / below cursor. Unfortunately these options do not exist
// in agenda mode, so in that case, instead it is added to the current
// section.
function addAbove() {
addAboveTask(getCursor());
}
function addBelow() {
addBelowTask(getCursor());
}
// Open comments sidepane
function openComments() {
openTaskView();
taskViewComments();
}
// Open reminders dialog
function openReminders() {
clickTaskMenu(requireCursor(), 'task-overflow-menu-reminders');
}
// Open assign dialog
function openAssign() {
const mutateCursor = getCursorToMutate();
if (mutateCursor) {
withTaskHovered(mutateCursor, () => {
const assignButton =
getUniqueClass(mutateCursor, 'task_list_item__person_picker');
if (assignButton) {
click(assignButton);
} else {
info('Could not find assign button, maybe project not shared?');
}
});
} else {
withUnique(
openMoreMenu(),
'[data-action-hint="multi-select-toolbar-overflow-menu-asssign"]',
click,
);
}
}
// Open the task view sidepane.
function openTaskView() {
withUniqueClass(
requireCursor(),
['content', 'task_list_item__body'],
all,
click,
);
}
// Click somewhere on the page that shouldn't do anything in particular except
// closing context menus. Also clicks 'Cancel' on any task adding.
function closeContextMenus() {
for (let i = 0; i < 100; i++) {
const popperOverlay = getLastClass(document, 'popper__overlay');
if (popperOverlay) {
popperOverlay.click();
} else {
break;
}
if (i == 99) {
warn('Tried a lot to close poppers.');
notifyUser('Closing popups is currently broken. Hopefully fixed soon!');
}
}
click(document.body);
withClass(document, 'manager', (manager) => {
const cancelBtn = getUniqueClass(manager, 'cancel');
if (cancelBtn) {
click(cancelBtn);
}
});
// Close windows with close buttons, particularly move-to-project
//