-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjumpflowy.user.js
4265 lines (3949 loc) · 149 KB
/
jumpflowy.user.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
// ==UserScript==
// @name JumpFlowy
// @namespace https://github.com/mbhutton/jumpflowy
// @version 0.1.8.20
// @description WorkFlowy user script for search and navigation
// @author Matt Hutton
// @match https://workflowy.com/*
// @match https://beta.workflowy.com/*
// @match https://dev.workflowy.com/*
// @grant none
// @run-at document-end
// @downloadURL https://github.com/mbhutton/jumpflowy/raw/master/jumpflowy.user.js
// ==/UserScript==
// ESLint globals from WorkFlowy:
/*
global WF:false
*/
// Enable TypeScript checking
// @ts-check
/// <reference path="index.d.ts" />
/// <reference path="types/workflowy-api.d.ts" />
(function() {
"use strict";
/**
* Applies the given function to the given item
* and each of its descendants, as a depth first search.
* @param {function} functionToApply The function to apply to each item.
* @param {Item} searchRoot The root item of the search.
* @returns {void}
*/
function applyToEachItem(functionToApply, searchRoot) {
// Apply the function
functionToApply(searchRoot);
// Recurse
for (let child of searchRoot.getChildren()) {
applyToEachItem(functionToApply, child);
}
}
/**
* @param {function} itemPredicate A function (Item -> boolean) which
* returns whether or not an item is a match.
* @param {Item} searchRoot The root item of the search.
* @returns {Array<Item>} The matching items, in order of appearance.
*/
function findMatchingItems(itemPredicate, searchRoot) {
const matches = Array();
function addIfMatch(item) {
if (itemPredicate(item)) {
matches.push(item);
}
}
applyToEachItem(addIfMatch, searchRoot);
return matches;
}
/**
* @template K
* @template V
* @param {function} itemFunction A function of type (Item -> Array<K>).
* Can return null or empty array.
* @param {Item} searchRoot The root item of the search.
* @returns {Map<K, Array<Item>>} A map of keys to arrays of items.
*/
function toItemMultimapWithMultipleKeys(itemFunction, searchRoot) {
/** @type Map<K, Array<Item>> */
const itemMultimap = new Map();
/**
* @param {Item} item The item
* @returns {void}
*/
function visitorFunction(item) {
const keysForItem = itemFunction(item);
if (keysForItem && keysForItem.length) {
for (let key of keysForItem) {
addToMultimap(key, item, itemMultimap);
}
}
}
applyToEachItem(visitorFunction, searchRoot);
return itemMultimap;
}
/**
* @template K
* @template V
* @param {function} itemFunction A function of type (Item -> K).
* Can return null.
* @param {Item} searchRoot The root item of the search.
* @returns {Map<K, Array<Item>>} A map of keys to arrays of items.
*/
function toItemMultimapWithSingleKeys(itemFunction, searchRoot) {
/**
* @param {Item} item The item
* @returns {Array<K> | null} The returned result (if any) as an array.
*/
function wrappedFunction(item) {
const key = itemFunction(item);
return (key && [key]) || null;
}
return toItemMultimapWithMultipleKeys(wrappedFunction, searchRoot);
}
/**
* @template K
* @template V
* @param {K} key The key.
* @param {V} value Value to append to the array associated with the key.
* @param {Map<K, Array<V>>} multimap A map of keys to arrays of values.
* @returns {void}
*/
function addToMultimap(key, value, multimap) {
if (multimap.has(key)) {
multimap.get(key).push(value);
} else {
multimap.set(key, [value]);
}
}
/**
* @template K
* @template V
* @param {function} keyFilter The filter to apply to keys in the map.
* @param {Map<K, V>} map The map to filter.
* @returns {Map<K, V>} map The filtered map.
*/
function filterMapByKeys(keyFilter, map) {
/** @type {Map<K, V>} */
const filteredMap = new Map();
map.forEach((v, k) => {
if (keyFilter(k)) {
filteredMap.set(k, v);
}
});
return filteredMap;
}
/**
* @template K
* @template V
* @param {function} valueFilter The filter to apply to values in the map.
* @param {Map<K, V>} map The map to filter.
* @returns {Map<K, V>} map The filtered map.
*/
function filterMapByValues(valueFilter, map) {
/** @type {Map<K, V>} */
const filteredMap = new Map();
map.forEach((v, k) => {
if (valueFilter(v)) {
filteredMap.set(k, v);
}
});
return filteredMap;
}
/**
* @param {Item} searchRoot The root item of the search.
* @returns {Map<string, Array<Item>>} Items with the same text, keyed by that
* text.
*/
function findItemsWithSameText(searchRoot) {
const allItemsByText = toItemMultimapWithSingleKeys(itemToCombinedPlainText, searchRoot);
return filterMapByValues(items => items.length > 1, allItemsByText);
}
/**
* Returns the tags found in the given item.
* Returns the empty set if none are found.
*
* Note: Tags containing punctuation may produce unexpected results.
* Suggested best practice: freely use '-' and '_' and ':'
* as part of tags, being careful to avoid ':' as a suffix.
*
* @param {Item} item The item to query.
* @returns {Array<string>} An array of tags found in the item.
*/
function itemToTags(item) {
const tagsForName = WF.getItemNameTags(item);
const tagsForNote = WF.getItemNoteTags(item);
const allTags = tagsForName.concat(tagsForNote);
return allTags.map(x => x.tag);
}
/**
* @param {function} itemPredicate A function (Item -> boolean) which
* returns whether or not to include an item.
* @param {Item} searchRoot The root item of the search.
* @returns {Set<string>} All tags under the given search root.
*/
function getTagsForFilteredItems(itemPredicate, searchRoot) {
const allTags = new Set();
/**
* @param {Item} item The item.
* @returns {void}
*/
function appendTags(item) {
if (!itemPredicate || itemPredicate(item)) {
itemToTags(item).forEach(tag => allTags.add(tag));
}
}
applyToEachItem(appendTags, searchRoot);
return allTags;
}
/**
* @param {string} tagToMatch The tag to match.
* @param {Item} item The item to test.
* @returns {boolean} True if and only if the given item has the
* exact given tag, ignoring case. Otherwise false.
* @see {@link itemToTags} For notes, caveats regarding tag handling.
*/
function doesItemHaveTag(tagToMatch, item) {
if (!item || !tagToMatch) {
return false;
}
// Optimisation: check for first character of tag in the raw rich text
// before converting to plain text, for both the name and the note.
const firstTagChar = tagToMatch[0];
return (
(item.getName().includes(firstTagChar) && doesStringHaveTag(tagToMatch, item.getNameInPlainText())) ||
(item.getNote().includes(firstTagChar) && doesStringHaveTag(tagToMatch, item.getNoteInPlainText()))
);
}
/**
* @param {Item} item The item
* @returns {string} The plain text version of the item's name,
* or the empty string if it is the root item.
*/
function itemToPlainTextName(item) {
return item.getNameInPlainText() || "";
}
/**
* @param {Item} item The item
* @returns {string} The plain text version of the item's note,
* or the empty string if it is the root item.
*/
function itemToPlainTextNote(item) {
return item.getNoteInPlainText() || "";
}
/**
* WARNING: The fastest way to get plain text name/note from an Item is
* to use the built-in methods for doing so. Only use this method when
* needing to convert to plain text after doing some processing of rich text.
*
* This function converts the given rich text to plain text, removing any tags
* (preserving their inner text), and un-escaping the required characters.
*
* Note that richTextToPlainText(Item.getName()) should always return the same
* result as Item.getNameInPlainText(), and a failure to do so would be a bug,
* and the same applies for getNote() and getNoteInPlainText().
*
* @param {string} richText The rich text to convert, e.g. from Item.getName()
* @returns {string} The plain text equivalent
*/
function richTextToPlainText(richText) {
return richText
.replace(/<[^>]*>/g, "")
.replace(/>/g, ">")
.replace(/</g, "<")
.replace(/&/g, "&");
}
/**
* @param {Item} item The item.
* @returns {string} The item's name and note, concatenated. When the note is
* present, it is preceded by a newline character.
*/
function itemToCombinedPlainText(item) {
const name = itemToPlainTextName(item);
const note = itemToPlainTextNote(item);
const combinedText = note.length === 0 ? name : `${name}\n${note}`;
return combinedText;
}
/**
* Marks the focused item and all its descendants as not complete.
* @returns {void}
*/
function markFocusedAndDescendantsNotComplete() {
const focusedItem = WF.focusedItem();
if (focusedItem === null) {
return;
}
WF.editGroup(() => {
applyToEachItem(item => {
if (item.isCompleted()) {
WF.completeItem(item);
}
}, focusedItem);
});
}
/**
* @param {function} textPredicate The predicate to apply to each string.
* The predicate should handle null values,
* as the root item has a null name and note.
* @param {Item} item The item to test.
* @returns {boolean} Whether textPredicate returns true for either the item's
* name or note.
*/
function doesItemNameOrNoteMatch(textPredicate, item) {
return textPredicate(itemToPlainTextName(item)) || textPredicate(itemToPlainTextNote(item));
}
/**
* @returns {number} The current clock time in seconds since Unix epoch.
*/
function getCurrentTimeSec() {
return dateToSecondsSinceEpoch(new Date());
}
/**
* @param {Date} date The given date.
* @returns {number} Seconds from epoch to the given date, rounding down.
*/
function dateToSecondsSinceEpoch(date) {
return Math.floor(date.getTime() / 1000);
}
/**
* @param {Item} item The item to query.
* @returns {number} When the item was last modified, in seconds since
* unix epoch. For the root item, returns zero.
*/
function itemToLastModifiedSec(item) {
return isRootItem(item) ? 0 : dateToSecondsSinceEpoch(item.getLastModifiedDate());
}
// Clean up any previous instance of JumpFlowy
if (
typeof window.jumpflowy !== "undefined" &&
typeof window.jumpflowy !== "undefined" &&
typeof window.jumpflowy.cleanUp !== "undefined"
) {
window.jumpflowy.cleanUp();
}
// Global state
/** @type {Map<string, Target>} */
const canonicalKeyCodesToTargets = new Map();
/** @type {Map<string, function | string>} */
const builtInExpansionsMap = new Map();
/** @type {Map<string, function | string>} */
let customExpansions = new Map();
/** @type {Map<string, function | string>} */
let abbrevsFromTags = new Map();
/** @type {Map<string, Target>} */
let kbShortcutsFromTags = new Map();
/** @type {Map<string, FunctionTarget>} */
const builtInFunctionTargetsByName = new Map();
/** @type {Map<string, ItemTarget>} */
let bookmarksToItemTargets = new Map();
/** @type {Map<string, Item>} */
let bookmarksToSourceItems = new Map();
/** @type {Map<string, string>} */
let itemIdsToFirstBookmarks = new Map();
/** @type {Map<string, string>} */
const hashSegmentsToIds = new Map();
/** @type {Set<string>} */
const unknownHashSegments = new Set();
/** @type {Map<string, string>} */
let bannedBookmarkSearchPrefixesToSuggestions = new Map();
// DEPRECATED TAGS START
const bookmarkTag = "#bm";
const abbrevTag = "#abbrev";
const shortcutTag = "#shortcut";
// DEPRECATED TAGS END
const SCATTER_TAG = "#scatter";
const SCHEDULE_TAG = "#scheduleFor";
const searchQueryToMatchNoItems = "META:NO_MATCHING_ITEMS_" + new Date().getTime();
let lastRegexString = null;
let isCleanedUp = false;
/** @type {Item} */
let configurationRootItem = null;
const CONFIGURATION_ROOT_NAME = "jumpflowyConfiguration";
const CONFIG_SECTION_EXPANSIONS = "textExpansions";
const CONFIG_SECTION_BOOKMARKS = "bookmarks";
const CONFIG_SECTION_KB_SHORTCUTS = "keyboardShortcuts";
const CONFIG_SECTION_BANNED_BOOKMARK_SEARCH_PREFIXES = "bannedBookmarkSearchPrefixes";
// Global event listener data
const gelData = [0, 0, 0, 0];
const GEL_CALLBACKS_FIRED = 0;
const GEL_CALLBACKS_RECEIVED = 1;
const GEL_CALLBACKS_TOTAL_MS = 2;
const GEL_CALLBACKS_MAX_MS = 3;
const IS_DEBUG_GEL_TIMING = false;
const isBetaDomain = location.origin === "https://beta.workflowy.com";
const isDevDomain = location.origin === "https://dev.workflowy.com";
const originalWindowOpenFn = window.open;
class AbortActionError extends Error {
constructor(message) {
super(message);
this.name = "AbortActionError";
}
}
/**
* Calls the given no-args function, catching any AbortActionError
* and showing its message.
* @param {function} f The function to call.
* @returns {void}
*/
function callWithErrorHandling(f) {
try {
f();
} catch (err) {
if (err instanceof AbortActionError) {
WF.showMessage(`Action failed: ${err.message}`, true);
} else {
throw err;
}
}
}
/**
* @param {boolean} condition Whether to throw the AbortActionError.
* @param {string | function} message The message to include in the error.
* If a function, must return a string.
* @throws {AbortActionError} If the condition is true.
* @returns {void}
*/
function failIf(condition, message) {
if (condition) {
throw new AbortActionError(message);
}
}
/**
* @param {Item} item The item to check.
* @returns {void}
* @throws {AbortActionError} If the item is embedded.
*/
function validateItemIsLocalOrFail(item) {
failIf(
item && item.isEmbedded(),
() => `${formatItem(item)} is embedded from another document. Was expecting local items only.`
);
}
function openHere(url) {
open(url, "_self");
}
/**
* Note: pop-ups must be allowed from https://workflowy.com for this to work.
* @param {string} url The URL to open.
* @returns {void}
*/
function openInNewTab(url) {
open(url, "_blank");
}
/**
* An alternative to window.open which rewrites the URL as
* necessary to avoid crossing between the various workflowy.com subdomains.
* Intended primarily for use on the dev/beta domains but also usable in prod.
* @param {string} url The URL to open.
* @param {string} targetWindow (See documentation for window.open)
* @param {string} features (See documentation for window.open)
* @param {boolean} replace (See documentation for window.open)
* @returns {Window} (See documentation for window.open)
*/
function _openWithoutChangingWfDomain(url, targetWindow, features, replace) {
if (isWorkFlowyUrl(url)) {
url = location.origin + url.substring(new URL(url).origin.length);
}
targetWindow = targetWindow || (isWorkFlowyUrl(url) ? "_self" : "_blank");
return originalWindowOpenFn(url, targetWindow, features, replace);
}
function zoomToAndSearch(item, searchQuery) {
if (searchQuery) {
// This is much faster than zooming and searching in two steps.
openHere(itemAndSearchToWorkFlowyUrl("current", item, searchQuery));
} else {
WF.zoomTo(item);
}
}
/**
* Prompt for a search query, then perform a normal WorkFlowy search.
* @returns {void}
*/
function promptToNormalLocalSearch() {
const previousQuery = WF.currentSearchQuery();
const newQuery = prompt("WorkFlowy search: ", previousQuery || "");
if (newQuery !== null) {
WF.search(newQuery);
}
}
/**
* Prompts for X, then performs a local WorkFlowy search for last-changed:X
* @returns {void}
*/
function promptToFindByLastChanged() {
const timePeriod = prompt("last-changed=");
if (timePeriod) {
WF.search(`last-changed:${timePeriod.trim()}`);
}
}
/**
* @returns {void} Dismisses a notification from the WorkFlowy UI, e.g. after
* deleting a large tree of items.
*/
function dismissNotification() {
WF.hideMessage();
}
function createItemAtTopOfCurrent() {
let item = null;
// Workaround: Use edit group to avoid WF.createItem() returning undefined
WF.editGroup(() => {
item = WF.createItem(WF.currentItem(), 0);
});
if (item) {
WF.editItemName(item);
}
}
/**
* @param {string} tagToMatch The tag to match.
* @param {string} s The string to test.
* @returns {boolean} True if and only if the given string has the
* exact given tag, ignoring case. Otherwise false.
* @see {@link itemToTags} For notes, caveats regarding tag handling.
*/
function doesStringHaveTag(tagToMatch, s) {
if (s === null || tagToMatch === null) {
return false;
}
// Ignore case
tagToMatch = tagToMatch.toLowerCase();
s = s.toLowerCase();
let nextStart = 0;
let matched = false;
for (;;) {
const tagIndex = s.indexOf(tagToMatch, nextStart);
if (tagIndex === -1) {
break; // Non-match: tag not found
}
if (tagToMatch.match(/^[@#]/) === null) {
break; // Non-match: invalid tagToMatch
}
const afterTag = tagIndex + tagToMatch.length;
nextStart = afterTag;
if (s.substring(afterTag).match(/^[:]?[a-z0-9-_]/)) {
continue; // This is a longer tag than tagToMatch, so keep looking
} else {
matched = true;
break;
}
}
return matched;
}
/**
* An 'argument passing' mechanism, where '#foo(bar, baz)'
* is considered as 'passing' the string "bar, baz" to #foo.
* It's very rudimentary/naive: e.g. "#foo('bar)', baz')"
* would lead to an args string of "'bar".
*
* @param {string} tagToMatch The tag to match.
* E.g. "#foo".
* @param {string} s The string to extract the args text from.
* E.g. "#foo(bar, baz)".
* @returns {string} The trimmed arguments string, or null if no call found.
* E.g. "bar, baz".
*/
function stringToTagArgsText(tagToMatch, s) {
if (s === null || s === "") {
return null;
}
let start = 0;
for (;;) {
const tagIndex = s.indexOf(tagToMatch, start);
if (tagIndex === -1) {
return null;
}
const afterTag = tagIndex + tagToMatch.length;
const callOpenIndex = s.indexOf("(", afterTag);
if (callOpenIndex === -1) {
return null;
}
const callCloseIndex = s.indexOf(")", callOpenIndex + 1);
if (callCloseIndex === -1) {
return null;
}
const fullCall = s.substring(afterTag, callCloseIndex + 1);
if (_stringToTagArgsText_CallRegExp.test(fullCall)) {
return s.substring(callOpenIndex + 1, callCloseIndex).trim();
}
start = afterTag;
}
}
const _stringToTagArgsText_CallRegExp = RegExp("^ *\\([^\\(\\)]*\\) *$");
/**
* Finds and returns the items whose "combined plain text" matches the
* given regular expression. Here, the "combined plain text" is the item's
* name as plain text, plus the item's note as plain text, with a
* newline separating the two only when the note is non-empty.
*
* @param {RegExp} regExp The compiled regular expression to match.
* @param {Item} searchRoot The root item of the search.
* @returns {Array<Item>} The matching items, in order of appearance.
*/
function findItemsMatchingRegex(regExp, searchRoot) {
if (typeof regExp !== "object" || regExp.constructor.name !== "RegExp") {
throw "regExp must be a compiled RegExp object. regExp: " + regExp;
}
function itemPredicate(item) {
const combinedText = itemToCombinedPlainText(item);
return regExp.test(combinedText);
}
return findMatchingItems(itemPredicate, searchRoot);
}
/**
* Prompts the user for a regular expression string (case insensitive, and
* defaulting to the last chosen regex), the searches for items under the
* currently zoomed item which match it, then prompts the user to choose which
* of the matching items to go to.
* @see findItemsMatchingRegex For how the regex is matched against the item.
* @returns {void}
*/
function promptToFindLocalRegexMatchThenZoom() {
const defaultSearch = lastRegexString || ".*";
const promptString = "Search for regular expression (case insensitive):";
const regExpString = prompt(promptString, defaultSearch);
if (!regExpString) {
return;
}
lastRegexString = regExpString;
let regExp;
try {
regExp = RegExp(regExpString, "i");
} catch (er) {
alert(er);
return;
}
const startTime = new Date();
const matchingItems = findItemsMatchingRegex(regExp, getZoomedItem());
const message = `Found ${matchingItems.length} matches for ${regExp}`;
logElapsedTime(startTime, message);
if (matchingItems.length === 0) {
alert(`No items under current location match '${regExpString}'.`);
} else {
const chosenItem = promptToChooseItem(matchingItems, null);
if (chosenItem) {
zoomToAndSearch(chosenItem, null);
}
}
}
/**
* @param {string} tagToMatch The tag to match.
* @param {Item} item The item to extract the args text from.
* @returns {string} The trimmed arguments string, or null if no call found.
* @see {@link stringToTagArgsText} For semantics.
*/
function itemToTagArgsText(tagToMatch, item) {
const resultForName = stringToTagArgsText(tagToMatch, itemToPlainTextName(item));
if (resultForName !== null) {
return resultForName;
}
return stringToTagArgsText(tagToMatch, itemToPlainTextNote(item));
}
/**
* @param {Item} item The item to query
* @returns {boolean} Whether the given item is the root item
*/
function isRootItem(item) {
return item.getId() === "None";
}
/**
* @returns {string} The long (non-truncated) ID of the
* item which is currently zoomed into.
*/
function getZoomedItemAsLongId() {
return WF.currentItem().getId();
}
/**
* @returns {Item} The item which is currently zoomed into.
*/
function getZoomedItem() {
const zoomedItemId = getZoomedItemAsLongId();
return WF.getItemById(zoomedItemId);
}
/**
* @param {Item} item The item whose path to get
* @returns {Array<Item>} An array starting with the root and ending
* with the item.
*/
function itemToPathAsItems(item) {
return item
.getAncestors() // parent ... root
.slice()
.reverse() // root ... parent
.concat(item); // root ... parent, item
}
/**
* @param {Item} itemToMove The item to be moved.
* @param {Item} targetItem The target item being moved to.
* @returns {boolean} Whether it's safe to move the item to the target.
*/
function isSafeToMoveItemToTarget(itemToMove, targetItem) {
// Both must be specified
if (!itemToMove || !targetItem) {
return false;
}
// Can't be the same item
if (itemToMove.getId() === targetItem.getId()) {
return false;
}
// Neither can be read-only
if (itemToMove.isReadOnly() || targetItem.isReadOnly()) {
return false;
}
// Can't move an ancestor to a descendant
if (isAAncestorOfB(itemToMove, targetItem)) {
return false;
}
return true;
}
/**
* @param {Item} a Item A.
* @param {Item} b Item B.
* @returns {boolean} Whether item A is an ancestor of item B.
*/
function isAAncestorOfB(a, b) {
if (!a || !b) {
return false;
}
let ancestorOfB = b.getParent();
while (ancestorOfB) {
if (a.getId() === ancestorOfB.getId()) {
return true;
}
ancestorOfB = ancestorOfB.getParent();
}
return false;
}
/**
* @param {Item} itemA Some item
* @param {Item} itemB Another item
* @returns {Item} The closest common ancestor of both items, inclusive.
*/
function findClosestCommonAncestor(itemA, itemB) {
const pathA = itemToPathAsItems(itemA);
const pathB = itemToPathAsItems(itemB);
const minLength = Math.min(pathA.length, pathB.length);
let i;
for (i = 0; i < minLength; i++) {
if (pathA[i].getId() !== pathB[i].getId()) {
break;
}
}
if (i === 0) {
throw "Items shared no common root";
}
return pathA[i - 1];
}
/**
* @param {'prod' | 'beta' | 'dev' | 'current'} domainType Domain to use.
* @returns {string} The base WorkFlowy URL for the given domain type.
*/
function getWorkFlowyBaseUrlForDomainType(domainType) {
switch (domainType) {
case "current":
return location.origin;
case "prod":
return "https://workflowy.com";
case "beta":
return "https://beta.workflowy.com";
case "dev":
return "https://dev.workflowy.com";
default:
throw "Unrecognized domain type: " + domainType;
}
}
/**
* @param {'prod' | 'beta' | 'dev' | 'current'} domainType Domain to use.
* @param {Item} item The item to create a WorkFlowy URL for.
* @param {string} searchQuery (Optional) search query string.
* @returns {string} The WorkFlowy URL pointing to the item.
*/
function itemAndSearchToWorkFlowyUrl(domainType, item, searchQuery) {
const baseUrl = getWorkFlowyBaseUrlForDomainType(domainType);
const searchSuffix = searchQuery ? `?q=${encodeURIComponent(searchQuery)}` : "";
return `${baseUrl}/${itemToHashSegment(item)}${searchSuffix}`;
}
/**
* @returns {boolean} True if and only if the given string is a WorkFlowy URL.
* @param {string} s The string to test.
*/
function isWorkFlowyUrl(s) {
return s && s.match("^https://(dev\\.|beta\\.)?workflowy\\.com(/.*)?$") !== null;
}
/**
* @param {string} fullUrl The full WorkFlowy URL.
* @returns {[string, string]} The hash segment, of the form returned by
* itemToHashSegment(), and search query or null.
*/
function workFlowyUrlToHashSegmentAndSearchQuery(fullUrl) {
const urlObject = new URL(fullUrl);
let [hash, rawSearchQuery] = urlObject.hash.split("?q=");
if (hash.length <= 2) {
// '#/' or '#' or ''
hash = "#";
}
let searchQuery = null;
if (rawSearchQuery) {
searchQuery = decodeURIComponent(rawSearchQuery);
}
return [hash, searchQuery];
}
/**
* @param {Item} item The item.
* @returns {string} '#' for the root item, or e.g. '#/80cbd123abe1'.
*/
function itemToHashSegment(item) {
let hash = item.getUrl();
hash = hash.startsWith("/") ? hash.substring(1) : hash;
return hash === "" ? "#" : hash;
}
/**
* Walks the entire tree, (re-)populating the hashSegmentsToIds map.
* @returns {void}
*/
function populateHashSegmentsForFullTree() {
function populateHash(item) {
const hashSegment = itemToHashSegment(item);
if (!hashSegmentsToIds.has(hashSegment)) {
hashSegmentsToIds.set(hashSegment, item.getId());
}
}
applyToEachItem(populateHash, WF.rootItem());
}
/**
* @param {string} hashSegment The hash segment part of a WorkFlowy URL.
* @returns {string | null} The ID of the item if found, otherwise null.
*/
function findItemIdForHashSegment(hashSegment) {
const existingEntry = hashSegmentsToIds.get(hashSegment);
if (existingEntry) {
return existingEntry;
}
if (unknownHashSegments.has(hashSegment)) {
return null;
}
// First request for this hash segment. Re-index the entire tree.
populateHashSegmentsForFullTree();
// Re-check the map, blacklisting the hash segment if not found
if (hashSegmentsToIds.has(hashSegment)) {
return hashSegmentsToIds.get(hashSegment);
} else {
unknownHashSegments.add(hashSegment);
return null;
}
}
/**
* @param {string} fullUrl The WorkFlowy URL.
* @returns {[string, string]} ID of the item in the URL, and search query.
*/
function findItemIdAndSearchQueryForWorkFlowyUrl(fullUrl) {
const [hashSegment, searchQuery] = workFlowyUrlToHashSegmentAndSearchQuery(fullUrl);
const itemId = findItemIdForHashSegment(hashSegment);
return [itemId, searchQuery];
}
/**
* @param {string} fullUrl The WorkFlowy URL.
* @returns {[Item, string]} The ID of the item in the URL, and search query.
*/
function findItemAndSearchQueryForWorkFlowyUrl(fullUrl) {
const [id, query] = findItemIdAndSearchQueryForWorkFlowyUrl(fullUrl);
let item = null;
if (id) {
item = WF.getItemById(id);
}
return [item, query];
}
const validRootUrls = [];
for (let subdomainPrefix of ["", "beta.", "dev."]) {
for (let suffix of ["", "/", "/#", "/#/"]) {
validRootUrls.push(`https://${subdomainPrefix}workflowy.com${suffix}`);
}
}
/**
* @param {Array<Item>} items The items to build the search query for.
* @returns {string} The search query to use for finding the
* items, or an unmatchable query if items is empty.
*/
function itemsToVolatileSearchQuery(items) {
if (items.length === 0) {
// Return a search query which matches no items
return searchQueryToMatchNoItems;
}
const searches = items.map(n => itemToVolatileSearchQuery(n));
return searches.join(" OR ");
}
/**
* @param {Item} item The item to build the search query for.
* @returns {string} The search query to use for finding the item, or
* an unmatchable query for the root item.
*/
function itemToVolatileSearchQuery(item) {
if (isRootItem(item)) {
// Return a search query which matches no items
return searchQueryToMatchNoItems;
}
const currentTimeSec = getCurrentTimeSec();
const itemLastModifiedSec = itemToLastModifiedSec(item);
const modifiedHowLongAgoSec = currentTimeSec - itemLastModifiedSec;
const modifiedHowLongAgoMinutes = Math.ceil(modifiedHowLongAgoSec / 60);
const timeClause = `last-changed:${modifiedHowLongAgoMinutes + 1} -last-changed:${modifiedHowLongAgoMinutes - 1} `;
const nameClause = splitStringToSearchTerms(itemToPlainTextName(item));
return timeClause + nameClause;
}
function splitStringToSearchTerms(s) {
const lines = s.match(/[^\r\n]+/g);
if (lines === null || lines.length === 0) {
return "";
}
let result = "";
for (let line of lines) {
for (let segment of line.split('"')) {
if (segment.trim() !== "") {
// Use 2 spaces here, to work around a WorkFlowy bug
// where "a" "b c" works, but "a" "b c" does not.
result += ` "${segment}"`;
}
}
}
return result;
}
/**
* @param {string} tag The tag to find, e.g. "#foo".
* @param {Item} searchRoot The root item of the search.
* @returns {Array<Item>} The matching items, in order of appearance.
*/
function findItemsWithTag(tag, searchRoot) {
return findMatchingItems(n => doesItemHaveTag(tag, n), searchRoot);
}
/**
* @template T
* @param {function} doesABeatB A function which return whether A beats B.
* @param {Array<T>} results The current results array, ordered
* [null, null, ..., 2nd best, best].
* @param {T} candidate The candidate item.
* @returns {void}
* Note: optimised for large numbers of calls, with small results sizes.
*/
function insertIntoSortedResults(doesABeatB, results, candidate) {
if (candidate === undefined || candidate === null) {
return;