forked from infokiller/web-search-navigator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search_engines.js
1567 lines (1494 loc) · 49.1 KB
/
search_engines.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
/**
* This file contains search engine specific logic via search engine objects.
*
* A search engine object must provide the following:
* - {regex} urlPattern
* - {CSS selector} searchBoxSelector
* - {SearchResult[]} getSearchResults()
*
* Optional functions/properties:
* - {Array} tabs
* Default: {}
* - {int} getTopMargin: used if top results are not entirely visible
* Default: 0
* - {int} getBottomMargin: used if bottom results are not entirely visible.
* Relevant for some search engines, since Firefox and Chrome show a tooltip
* with the URL of focused links at the bottom and can hide some of the
* search result at the bottom.
* Default: getDefaultBottomMargin()
* - {Function} onChangedResults: function for registering a callback on
* changed search results. The callback gets a single boolean parameter that
* is set to true if the only change is newly appended results.
* Default: null (meaning there's no support for such events)
* - {None} changeTools(period)
*
* Every SearchResult must provide the element and highlightClass properties and
* optionally the following:
* - {Callback} anchorSelector: callback for getting the anchor
* Default: the element itself
* - {Callback} highlightedElementSelector: callback for getting the
* highlighted element
* Default: the element itself
* - {Callback} containerSelector: callback for getting the container that
* needs to be visible when an element is selected.
* Default: the element itself
*/
class SearchResult {
// We must declare the private class fields.
#element;
#anchorSelector;
#highlightedElementSelector;
#containerSelector;
/**
* @param {Element} element
* @param {function|null} anchorSelector
* @param {string} highlightClass
* @param {function|null} highlightedElementSelector
* @param {function|null} containerSelector
*/
constructor(
element,
anchorSelector,
highlightClass,
highlightedElementSelector,
containerSelector,
) {
this.#element = element;
this.#anchorSelector = anchorSelector;
this.highlightClass = highlightClass;
this.#highlightedElementSelector = highlightedElementSelector;
this.#containerSelector = containerSelector;
}
get anchor() {
if (!this.#anchorSelector) {
return this.#element;
}
return this.#anchorSelector(this.#element);
}
get container() {
if (!this.#containerSelector) {
return this.#element;
}
return this.#containerSelector(this.#element);
}
get highlightedElement() {
if (!this.#highlightedElementSelector) {
return this.#element;
}
return this.#highlightedElementSelector(this.#element);
}
}
// eslint-disable-next-line
/**
* @param {Array} includedSearchResults An array of
* tuples. Each tuple contains collection of the search results optionally
* accompanied with their container selector.
* @constructor
*/
const getSortedSearchResults = (
includedSearchResults,
excludedNodeList = [],
) => {
const excludedResultsSet = new Set();
for (const node of excludedNodeList) {
excludedResultsSet.add(node);
}
const searchResults = [];
for (const results of includedSearchResults) {
for (const node of results.nodes) {
const searchResult = new SearchResult(
node,
results.anchorSelector,
results.highlightClass,
results.highlightedElementSelector,
results.containerSelector,
);
const anchor = searchResult.anchor;
// Use offsetParent to exclude hidden elements, see:
// https://stackoverflow.com/a/21696585/1014208
if (
anchor != null &&
!excludedResultsSet.has(anchor) &&
anchor.offsetParent !== null
) {
// Prevent adding the same node multiple times.
excludedResultsSet.add(anchor);
searchResults.push(searchResult);
}
}
}
// Sort searchResults by their document position.
searchResults.sort((a, b) => {
const position = a.anchor.compareDocumentPosition(b.anchor);
if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
return -1;
} else if (position & Node.DOCUMENT_POSITION_PRECEDING) {
return 1;
} else {
return 0;
}
});
return searchResults;
};
const getFixedSearchBoxTopMargin = (searchBoxContainer, element) => {
// When scrolling down, the search box can have a fixed position and can hide
// search results, so we try to compensate for it.
if (!searchBoxContainer || searchBoxContainer.contains(element)) {
return 0;
}
return searchBoxContainer.getBoundingClientRect().height;
};
// https://stackoverflow.com/a/7000222/2870889
// eslint-disable-next-line no-unused-vars
const isFirefox = () => {
return navigator.userAgent.toLowerCase().indexOf('firefox') >= 0;
};
// eslint-disable-next-line no-unused-vars
const getDefaultBottomMargin = (element) => {
return 28;
};
const selectorElementGetter = (selector) => {
return () => {
return document.querySelector(selector);
};
};
const nParent = (element, n) => {
while (n > 0 && element) {
element = element.parentElement;
n--;
}
return element;
};
const debounce = (callback, delayMs) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
return callback(...args);
}, delayMs);
};
};
class GoogleSearch {
constructor(options) {
this.options = options;
}
get urlPattern() {
return /^https:\/\/(www\.)?google\./;
}
get searchBoxSelector() {
// Must match search engine search box
// NOTE: we used '#searchform input[name=q]' before 2020-06-05 but that
// doesn't work in the images search tab. Another option is to use
// 'input[role="combobox"]' but this doesn't work when there's also a
// dictionary search box.
// return '#searchform input[name=q]',
return 'form[role=search] [name=q]';
}
getTopMargin(element) {
return getFixedSearchBoxTopMargin(
document.querySelector('#searchform.minidiv'),
element,
);
}
getBottomMargin(element) {
return isFirefox() ? 0 : getDefaultBottomMargin();
}
onChangedResults(callback) {
if (GoogleSearch.#isImagesTab()) {
return GoogleSearch.#onImageSearchResults(callback);
}
if (this.options.googleIncludeMemex) {
return GoogleSearch.#onMemexResults(callback);
}
// https://github.com/infokiller/web-search-navigator/issues/464
const container = document.querySelector('#rcnt');
if (!container) {
return;
}
const observer = new MutationObserver(
debounce((mutationsList, observer) => {
callback(true);
}, 50),
);
observer.observe(container, {
attributes: false,
childList: true,
subtree: true,
});
}
static #isImagesTab() {
const searchParams = new URLSearchParams(window.location.search);
return searchParams.get('tbm') === 'isch';
}
static #getImagesTabResults() {
const includedElements = [
// Image links
{
nodes: document.querySelectorAll('.islrc a[data-nav="1"]'),
highlightClass: 'wsn-google-focused-image',
},
// Show more results button
{
nodes: document.querySelectorAll('#islmp [type="button"]'),
highlightClass: 'wsn-google-focused-image',
},
];
return getSortedSearchResults(includedElements, []);
}
static #regularResults() {
return [
{
nodes: document.querySelectorAll('#search .r > a:first-of-type'),
highlightClass: 'wsn-google-focused-link',
containerSelector: (n) => n.parentElement.parentElement,
},
{
nodes: document.querySelectorAll('#search .r g-link > a:first-of-type'),
highlightClass: 'wsn-google-focused-link',
containerSelector: (n) => n.parentElement.parentElement,
},
// More results button in continous loading
// https://imgur.com/a/X9zyJ24
{
nodes: document.querySelectorAll(
'#botstuff a[href^="/search"][href*="start="] h3',
),
highlightClass: 'wsn-google-focused-link',
anchorSelector: (n) => n.closest('a'),
},
// Continuously loaded results are *sometimes* in the #botstuff container
// https://imgur.com/a/s6ow0La
{
nodes: document.querySelectorAll('#botstuff a h3'),
highlightClass: 'wsn-google-focused-link',
containerSelector: (n) => nParent(n, 5),
highlightedElementSelector: (n) => nParent(n, 5),
anchorSelector: (n) => n.closest('a'),
},
// Sometimes featured snippets are not contained in #search (possibly when
// there are large images?): https://imgur.com/a/VluRKIQ
{
nodes: document.querySelectorAll('.xpdopen .g a'),
highlightClass: 'wsn-google-focused-link',
highlightedElementSelector: (n) => n.querySelector('h3'),
},
// Large YouTube video as top result: https://imgur.com/a/JIe62QV
{
nodes: document.querySelectorAll('h3 a[href*="youtube.com"]'),
highlightClass: 'wsn-google-focused-link',
highlightedElementSelector: (n) => n.closest('h3'),
},
// Sub-results: https://imgur.com/a/CJePYJM
{
nodes: document.querySelectorAll('#search h3 a:first-of-type'),
highlightClass: 'wsn-google-focused-link',
highlightedElementSelector: (n) => n.closest('h3'),
containerSelector: (n) => n.closest('tr'),
},
// Shopping results: https://imgur.com/a/wccM2iq
{
nodes: document.querySelectorAll('#rso a h4'),
anchorSelector: (n) => n.closest('a'),
highlightClass: 'wsn-google-focused-card',
highlightedElementSelector: (n) => n.closest('.sh-dgr__content'),
},
// News tab: https://imgur.com/a/MR9q31f
{
nodes: document.querySelectorAll('#search g-card a'),
highlightClass: 'wsn-google-focused-link',
},
// Jobs heading for the jobs cards section. Clicking on it takes you
// to Google's job search.
// As of 2023-05-28, the Google's jobs search URLs seem to contain two
// query string params which seem relevant:
// - ibp=htl;jobs
// - htivrt=jobs
// The first one matches the jobs heading, but also buttons in the
// jobs UI such as filtering by WFH/in-office. Therefore, we use the
// second one for specific jobs, but the first one to detect the jobs
// heading (otherwise it would be matched later in vaccines).
// eslint-disable-next-line max-len
// const jobsSelector = '#search a:is([href*="ibp=htl;jobs"], [href*="htivrt=jobs"])';
// NOTE: this must be added to the included elements before:
// - vaccines
// - vertical maps
// - books and featured snippets
// TODO: add screenshot
{
nodes: document.querySelectorAll(
// eslint-disable-next-line max-len
'#search a:is([href*="ibp=htl;jobs"],[href*="htivrt=jobs"]) [role=heading][aria-level="2"]',
),
anchorSelector: (n) => n.closest('a'),
// highlightedElementSelector: (n) => n.closest('li'),
highlightClass: 'wsn-google-focused-job-card',
},
// Same as above, but for specific job results.
// TODO: add screenshot
// Jobs cards
{
// nodes: document.querySelectorAll('#search a[href*="htivrt=jobs"]'),
// eslint-disable-next-line max-len
nodes: document.querySelectorAll('#search li a[href*="htivrt=jobs"]'),
highlightedElementSelector: (n) => n.closest('li'),
highlightClass: 'wsn-google-focused-job-card',
},
// Books tab: https://imgur.com/a/QSBIOb6
// NOTE: This is required for matching "features snippets" in the general
// search tab, and also matches other results.
{
nodes: document.querySelectorAll('#search [data-hveid] a h3'),
anchorSelector: (n) => n.closest('a'),
containerSelector: (n) => n.closest('[data-hveid]'),
highlightedElementSelector: (n) => n.closest('[data-hveid]'),
highlightClass: 'wsn-google-focused-link',
},
// Next/previous results page
{
nodes: document.querySelectorAll('#pnprev, #pnnext'),
highlightClass: 'wsn-google-card-item',
},
];
}
static #cardResults() {
const nearestChildOrSiblingOrParentAnchor = (element) => {
const childAnchor = element.querySelector('a');
if (childAnchor && childAnchor.href) {
return childAnchor;
}
const siblingAnchor = element.parentElement.querySelector('a');
if (siblingAnchor && siblingAnchor.href) {
return siblingAnchor;
}
return element.closest('a');
};
const nearestCardContainer = (element) => {
return element.closest('g-inner-card');
};
return [
// Twitter: https://imgur.com/a/fdI75JG
{
nodes: document.querySelectorAll(
'#search [data-init-vis=true] [role=heading]',
),
anchorSelector: nearestChildOrSiblingOrParentAnchor,
highlightedElementSelector: nearestCardContainer,
highlightClass: 'wsn-google-focused-card',
},
// Vertical "Top stories" results
{
nodes: document.querySelectorAll('#search [role=text] [role=heading]'),
anchorSelector: nearestChildOrSiblingOrParentAnchor,
highlightClass: 'wsn-google-focused-link',
},
// Vertical video results: https://imgur.com/a/GyKhwrx
// Vertical video results: https://imgur.com/a/8fbPnvT
{
nodes: document.querySelectorAll(
'#search video-voyager a [role=heading]',
),
anchorSelector: nearestChildOrSiblingOrParentAnchor,
containerSelector: nearestChildOrSiblingOrParentAnchor,
highlightedElementSelector: nearestChildOrSiblingOrParentAnchor,
highlightClass: 'wsn-google-focused-link',
},
// Horizontal video results: https://imgur.com/a/gRGJ7l9
// People also search for: https://imgur.com/a/QpCHKt0
{
nodes: document.querySelectorAll(
'#search g-scrolling-carousel g-inner-card a [role=heading]',
),
anchorSelector: nearestChildOrSiblingOrParentAnchor,
containerSelector: nearestCardContainer,
highlightedElementSelector: nearestCardContainer,
highlightClass: 'wsn-google-card-item',
},
// Vaccines: https://imgur.com/a/325qJzE
{
nodes: document.querySelectorAll(
'#search a.a-no-hover-decoration [role=heading]',
),
anchorSelector: nearestChildOrSiblingOrParentAnchor,
containerSelector: nearestChildOrSiblingOrParentAnchor,
highlightedElementSelector: nearestChildOrSiblingOrParentAnchor,
highlightClass: 'wsn-google-focused-link',
},
// Things to do in X: https://imgur.com/a/ibXwiuT
{
nodes: document.querySelectorAll('td a [role=heading]'),
anchorSelector: nearestChildOrSiblingOrParentAnchor,
containerSelector: (n) => n.closest('td'),
highlightedElementSelector: (n) => n.closest('td'),
highlightClass: 'wsn-google-card-item',
},
// Vertical Maps/Places: https://imgur.com/a/JXrxBCj
// Vertical recipes: https://imgur.com/a/3r7klHk
// Top stories grid: https://imgur.com/a/mY93YRF
// TODO: fix the small movements in recipes item selection.
{
nodes: document.querySelectorAll('a [role=heading]'),
anchorSelector: nearestChildOrSiblingOrParentAnchor,
containerSelector: nearestChildOrSiblingOrParentAnchor,
highlightedElementSelector: nearestChildOrSiblingOrParentAnchor,
highlightClass: 'wsn-google-card-item',
},
];
}
static #placesResults() {
const nodes = document.querySelectorAll('.vk_c a');
// The first node is usually the map image which needs to be styled
// differently.
let map;
let links = nodes;
if (nodes[0] != null && nodes[0].querySelector('img')) {
map = nodes[0];
links = Array.from(nodes).slice(1);
}
const results = [];
if (map != null) {
results.push({
nodes: [map],
highlightedElementSelector: (n) => n.parentElement,
highlightClass: 'wsn-google-focused-map',
});
}
results.push({
nodes: links,
highlightClass: 'wsn-google-focused-link',
});
return results;
}
static #memexResults() {
return [
{
nodes: document.querySelectorAll(
'#memexResults ._3d3zwUrsb4CVi1Li4H6CBw a',
),
highlightClass: 'wsn-google-focused-memex-result',
},
];
}
getSearchResults() {
if (GoogleSearch.#isImagesTab()) {
return GoogleSearch.#getImagesTabResults();
}
const includedElements = GoogleSearch.#regularResults();
if (this.options.googleIncludeCards) {
includedElements.push(...GoogleSearch.#cardResults());
}
if (this.options.googleIncludePlaces) {
includedElements.push(...GoogleSearch.#placesResults());
}
if (this.options.googleIncludeMemex) {
includedElements.push(...GoogleSearch.#memexResults());
}
const excludedElements = document.querySelectorAll(
[
// People also ask. Each one of the used selectors should be
// sufficient, but we use both to be more robust to upstream DOM
// changes.
'.related-question-pair a',
'#search .kp-blk:not(.c2xzTb) .r > a:first-of-type',
// Right hand sidebar. We exclude it because it is after all the
// results in the document order (as determined by
// Node.DOCUMENT_POSITION_FOLLOWING used in getSortedSearchResults),
// and it's confusing.
'#rhs a',
].join(', '),
);
return getSortedSearchResults(includedElements, excludedElements);
}
static #onImageSearchResults(callback) {
const container = document.querySelector('.islrc');
if (!container) {
return;
}
const observer = new MutationObserver(
debounce((mutationsList, observer) => {
callback(true);
}, 50),
);
observer.observe(container, {
attributes: false,
childList: true,
subtree: false,
});
}
static #onMemexResults(callback) {
const container = document.querySelector('#rhs');
if (!container) {
return;
}
const observer = new MutationObserver(
debounce((mutationsList, observer) => {
if (document.querySelector('#memexResults') != null) {
callback(true);
}
}, 50),
);
observer.observe(container, {
attributes: false,
childList: true,
subtree: true,
});
}
static #imageSearchTabs() {
const visibleTabs = document.querySelectorAll('.T47uwc > a');
// NOTE: The order of the tabs after the first two is dependent on the
// query. For example:
// - "cats": videos, news, maps
// - "trump": news, videos, maps
// - "california": maps, news, videos
return {
navigateSearchTab: visibleTabs[0],
navigateMapsTab: selectorElementGetter(
'.T47uwc > a[href*="maps.google."]',
),
navigateVideosTab: selectorElementGetter('.T47uwc > a[href*="&tbm=vid"]'),
navigateNewsTab: selectorElementGetter('.T47uwc > a[href*="&tbm=nws"]'),
navigateShoppingTab: selectorElementGetter(
'a[role="menuitem"][href*="&tbm=shop"]',
),
navigateBooksTab: selectorElementGetter(
'a[role="menuitem"][href*="&tbm=bks"]',
),
navigateFlightsTab: selectorElementGetter(
'a[role="menuitem"][href*="&tbm=flm"]',
),
navigateFinancialTab: selectorElementGetter(
'a[role="menuitem"][href*="/finance?"]',
),
// TODO: Disable image search's default keybindings to avoid confusing the
// user, because the default keybindings can cause an indenepdent
// navigation of the image results with another outline. The code below
// doesn't work because the key event is captured by the image search
// code, since Moustrap is bound on document, instead of a more specific
// container. The following does work, but the code needs some changes to
// support binding on a specific container per search engine:
//
// Mousetrap(document.querySelector('.islrc')).bind ...
// Mousetrap(document.querySelector('#Sva75c')).bind ...
//
// navigatePreviousResultPage: null,
// navigateNextResultPage: null,
};
}
// Array storing tuples of tabs navigation keybindings and their corresponding
// CSS selector
get previousPageButton() {
if (GoogleSearch.#isImagesTab()) {
return null;
}
return selectorElementGetter('#pnprev');
}
get nextPageButton() {
if (GoogleSearch.#isImagesTab()) {
return null;
}
return selectorElementGetter('#pnnext');
}
get tabs() {
if (GoogleSearch.#isImagesTab()) {
return GoogleSearch.#imageSearchTabs();
}
return {
navigateSearchTab: selectorElementGetter(
// eslint-disable-next-line max-len
'a[href*="/search?q="]:not([href*="&tbm="]):not([href*="maps.google."])',
),
navigateImagesTab: selectorElementGetter('a[href*="&tbm=isch"]'),
navigateVideosTab: selectorElementGetter('a[href*="&tbm=vid"]'),
navigateMapsTab: selectorElementGetter('a[href*="maps.google."]'),
navigateNewsTab: selectorElementGetter('a[href*="&tbm=nws"]'),
navigateShoppingTab: selectorElementGetter('a[href*="&tbm=shop"]'),
navigateBooksTab: selectorElementGetter('a[href*="&tbm=bks"]'),
navigateFlightsTab: selectorElementGetter('a[href*="&tbm=flm"]'),
navigateFinancialTab: selectorElementGetter('[href*="/finance?"]'),
};
}
/**
* Filter the results based on special properties
* @param {*} period, filter identifier. Accepted filter are :
* 'a' : all results
* 'h' : last hour
* 'd' : last day
* 'w' : last week
* 'm' : last month
* 'y' : last year
* 'v' : verbatim search
* null : toggle sort
*/
// TODO: Refactor this function to get enums after migrating to typescript.
changeTools(period) {
const searchParams = new URLSearchParams(window.location.search);
// Use the last value of the tbs param in case there are multiple ones,
// since the last one overrides the previous ones.
const allTbsValues = searchParams.getAll('tbs');
const lastTbsValue = allTbsValues[allTbsValues.length - 1] || '';
const match = /(qdr:.|li:1)(,sbd:.)?/.exec(lastTbsValue);
const currentPeriod = (match && match[1]) || '';
const currentSort = (match && match[2]) || '';
if (period === 'a') {
searchParams.delete('tbs');
} else if (period) {
let newTbs = '';
if (period === 'v') {
if (currentPeriod === 'li:1') {
newTbs = '';
} else {
newTbs = 'li:1';
}
} else {
newTbs = `qdr:${period}`;
}
searchParams.set('tbs', `${newTbs}${currentSort}`);
// Can't apply sort when not using period.
} else if (currentPeriod) {
searchParams.set(
'tbs',
`${currentPeriod}` + (currentSort ? '' : ',sbd:1'),
);
}
const newSearchString = '?' + searchParams.toString();
if (newSearchString !== window.location.search) {
window.location.search = newSearchString;
}
return false;
}
changeImageSize(size) {
const sizeOptions = {
LARGE: {value: 0, name: 'Large', code: 'l'},
MEDIUM: {value: 1, name: 'Medium', code: 'e'},
ICON: {value: 2, name: 'Icon', code: 'i'},
};
const openTool = document.querySelector(
'[class="PNyWAd ZXJQ7c"][jsname="I4bIT"]',
);
if (openTool != null) {
openTool.click();
}
const openSizeDropDown = document.querySelector('[aria-label="Size"]');
if (openSizeDropDown != null) {
openSizeDropDown.click();
}
const dropDownWithSize = document.querySelector(
'[class="xFo9P r9PaP Fmo8N"][jsname="wLFV5d"]',
);
const getButton = (selector) => {
let button;
if (document.querySelector(selector) != null) {
button = document.querySelector(selector);
} else {
button = null;
}
return button;
};
const setImageSize = (dropDownWithSize, buttonSelector) => {
let button = getButton(buttonSelector);
if (dropDownWithSize == null && button != null) {
button.click();
} else if (dropDownWithSize != null && button == null) {
dropDownWithSize.click();
button = getButton(buttonSelector);
button.click();
} else if (dropDownWithSize != null && button != null) {
button.click();
}
};
switch (size) {
case sizeOptions.LARGE.code:
if (
dropDownWithSize == null ||
dropDownWithSize.getAttribute('aria-label') != sizeOptions.LARGE.name
) {
setImageSize(
dropDownWithSize,
'[class="MfLWbb"][aria-label="Large"]',
);
}
break;
case sizeOptions.MEDIUM.code:
if (
dropDownWithSize == null ||
dropDownWithSize.getAttribute('aria-label') != sizeOptions.MEDIUM.name
) {
setImageSize(
dropDownWithSize,
'[class="MfLWbb"][aria-label="Medium"]',
);
}
break;
case sizeOptions.ICON.code:
if (
dropDownWithSize == null ||
dropDownWithSize.getAttribute('aria-label') != sizeOptions.ICON.name
) {
setImageSize(dropDownWithSize, '[class="MfLWbb"][aria-label="Icon"]');
}
break;
default:
break;
}
}
}
class BraveSearch {
constructor(options) {
this.options = options;
}
get urlPattern() {
return /^https:\/\/search\.brave\.com/;
}
get searchBoxSelector() {
return '.form-input, input[id=searchbox]';
}
getTopMargin(element) {
return getFixedSearchBoxTopMargin(
document.querySelector('header.navbar'),
element,
);
}
onChangedResults(callback) {
const containers = document.querySelectorAll('#results');
const observer = new MutationObserver(
debounce((mutationsList, observer) => {
callback(true);
}, 50),
);
for (const container of containers) {
observer.observe(container, {
attributes: false,
childList: true,
subtree: true,
});
}
}
static #getNewsTabResults() {
const includedElements = [
{
nodes: document.querySelectorAll('.snippet a'),
highlightClass: 'wsn-brave-search-focused-news',
containerSelector: (n) => n.parentElement,
},
];
return getSortedSearchResults(includedElements);
}
static #getVideosTabResults() {
const includedElements = [
{
nodes: document.querySelectorAll('.card a'),
highlightClass: 'wsn-brave-search-focused-card',
highlightedElementSelector: (n) => n.closest('.card'),
containerSelector: (n) => n.parentElement,
},
];
return getSortedSearchResults(includedElements);
}
getSearchResults() {
if (BraveSearch.#isTabActive(this.tabs.navigateNewsTab)) {
return BraveSearch.#getNewsTabResults();
} else if (BraveSearch.#isTabActive(this.tabs.navigateVideosTab)) {
return BraveSearch.#getVideosTabResults();
}
const includedElements = [
{
nodes: document.querySelectorAll('.snippet.fdb > a'),
highlightClass: 'wsn-brave-search-focused-link',
containerSelector: (n) => n.parentElement,
},
// News cards
{
nodes: document.querySelectorAll(
'.card[data-type="news"]:nth-child(-n+3)',
),
highlightClass: 'wsn-brave-search-focused-card',
},
// Video cards
{
nodes: document.querySelectorAll(
'.card[data-type="videos"]:nth-child(-n+3)',
),
highlightClass: 'wsn-brave-search-focused-card',
},
];
return getSortedSearchResults(includedElements);
}
static #isTabActive(tab) {
return tab && tab.parentElement.classList.contains('active');
}
get tabs() {
return {
navigateSearchTab: document.querySelector('a[href*="/search?q="]'),
navigateImagesTab: document.querySelector(
'#tab-images > a:first-of-type',
),
navigateNewsTab: document.querySelector('a[href*="/news?q="]'),
navigateVideosTab: document.querySelector(
'#tab-videos > a:first-of-type',
),
};
}
}
class StartPage {
constructor(options) {
this.options = options;
}
get urlPattern() {
return /^https:\/\/(www\.)?startpage\./;
}
get searchBoxSelector() {
return '#q';
}
getTopMargin(element) {
return getFixedSearchBoxTopMargin(
document.querySelector('div.layout-web__header'),
element,
);
}
getBottomMargin(element) {
// Startpage in Firefox has an issue where trying to scroll can result in
// window.scrollY being updated for a brief time although no scrolling is
// done, which confuses the scrollToElement function, which can lead to
// being stuck focused on a search result.
return isFirefox() ? 0 : getDefaultBottomMargin();
}
static #isSearchTab() {
return document.querySelector('div.layout-web') != null;
}
static #isImagesTab() {
return document.querySelector('div.layout-images') != null;
}
getSearchResults() {
// Don't initialize results navigation on image search, since it doesn't
// work there.
if (StartPage.#isImagesTab()) {
return [];
}
const containerSelector = (element) => {
if (StartPage.#isSearchTab()) {
return element.closest('.w-gl__result');
}
return element;
};
const includedElements = [
{
nodes: document.querySelectorAll('a.w-gl__result-url'),
highlightedElementSelector: containerSelector,
highlightClass: 'wsn-startpage-focused-link',
containerSelector: containerSelector,
},
{
nodes: document.querySelectorAll('.pagination--desktop button'),
highlightClass: 'wsn-startpage-focused-link',
},
// As of 2020-06-20, this doesn't seem to match anything.
{
nodes: document.querySelectorAll(
'.vo-sp.vo-sp--default > a.vo-sp__link',
),
highlightedElementSelector: containerSelector,
highlightClass: 'wsn-startpage-focused-link',
},
];
const excludedElements = document.querySelectorAll('button[disabled]');
return getSortedSearchResults(includedElements, excludedElements);
}
get previousPageButton() {
const menuLinks = document.querySelectorAll('.inline-nav-menu__link');
if (!menuLinks || menuLinks.length < 4) {
return null;
}
return document.querySelector(
'form.pagination__form.next-prev-form--desktop:first-of-type',
);
}
get nextPageButton() {
const menuLinks = document.querySelectorAll('.inline-nav-menu__link');
if (!menuLinks || menuLinks.length < 4) {
return null;
}
return document.querySelector(
'form.pagination__form.next-prev-form--desktop:last-of-type',
);
}
get tabs() {
const menuLinks = document.querySelectorAll('.inline-nav-menu__link');
if (!menuLinks || menuLinks.length < 4) {
return {};
}
return {
navigateSearchTab: menuLinks[0],
navigateImagesTab: menuLinks[1],
navigateVideosTab: menuLinks[2],
navigateNewsTab: menuLinks[3],
};
}
changeTools(period) {
const forms = document.forms;
let timeForm;
for (let i = 0; i < forms.length; i++) {
if (forms[i].className === 'search-filter-time__form') {
timeForm = forms[i];
}
}
switch (period) {
case 'd':
timeForm.elements['with_date'][1].click();
break;
case 'w':
timeForm.elements['with_date'][2].click();
break;
case 'm':
timeForm.elements['with_date'][3].click();
break;
case 'y':
timeForm.elements['with_date'][4].click();
break;
default:
break;
}
}
}
class YouTube {
constructor(options) {