forked from livegrep/livegrep
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodesearch_ui.js
More file actions
1169 lines (1054 loc) · 36.5 KB
/
codesearch_ui.js
File metadata and controls
1169 lines (1054 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var html = require('html');
var Backbone = require('backbone');
var Cookies = require('js-cookie');
var Codesearch = require('codesearch/codesearch.js').Codesearch;
var RepoSelector = require('codesearch/repo_selector.js');
var highlight = require('codesearch/highlight.js');
var KeyCodes = {
SLASH_OR_QUESTION_MARK: 191
};
function getSelectedText() {
return window.getSelection ? window.getSelection().toString() : null;
}
function init(initData) {
"use strict";
var h = new html.HTMLFactory();
var last_url_update = 0;
var PRISM_THEMES_CDN = 'https://cdnjs.cloudflare.com/ajax/libs/prism-themes/1.9.0/';
// NOTE: keep in sync with the early-load script in layout.html (mode + css only)
var syntaxThemes = [
{key:'dracula', label:'Dracula', mode:'dark', css:'prism-dracula.min.css'},
{key:'one-dark', label:'One Dark', mode:'dark', css:'prism-one-dark.min.css'},
{key:'nord', label:'Nord', mode:'dark', css:'prism-nord.min.css'},
{key:'solarized-dark', label:'Solarized Dark', mode:'dark', css:'prism-solarized-dark-atom.min.css'},
{key:'material-dark', label:'Material Dark', mode:'dark', css:'prism-material-dark.min.css'},
{key:'gruvbox-dark', label:'Gruvbox Dark', mode:'dark', css:'prism-gruvbox-dark.min.css'},
{key:'vsc-dark', label:'VS Code Dark', mode:'dark', css:'prism-vsc-dark-plus.min.css'},
{key:'one-light', label:'One Light', mode:'light', css:'prism-one-light.min.css'},
{key:'material-light', label:'Material Light', mode:'light', css:'prism-material-light.min.css'},
{key:'gruvbox-light', label:'Gruvbox Light', mode:'light', css:'prism-gruvbox-light.min.css'}
];
var syntaxThemeMap = {};
syntaxThemes.forEach(function(t) { syntaxThemeMap[t.key] = t; });
function applyPageMode(mode) {
if (mode === 'light' || mode === 'dark') {
document.documentElement.setAttribute('data-theme', mode);
} else {
document.documentElement.removeAttribute('data-theme');
}
}
function applySyntaxTheme(themeName) {
var existing = document.getElementById('syntax-theme-css');
var theme = syntaxThemeMap[themeName];
if (theme) {
applyPageMode(theme.mode);
if (existing) {
existing.href = PRISM_THEMES_CDN + theme.css;
} else {
var link = document.createElement('link');
link.id = 'syntax-theme-css';
link.rel = 'stylesheet';
link.href = PRISM_THEMES_CDN + theme.css;
document.head.appendChild(link);
}
} else {
applyPageMode('auto');
if (existing) existing.remove();
}
}
function vercmp(a, b) {
var re = /^([0-9]*)([^0-9]*)(.*)$/;
var abits, bbits;
var anum, bnum;
while (a.length && b.length) {
abits = re.exec(a);
bbits = re.exec(b);
if ((abits[1] === '') != (bbits[1] === '')) {
return abits[1] ? -1 : 1;
}
if (abits[1] !== '') {
anum = parseInt(abits[1]);
bnum = parseInt(bbits[1])
if (anum !== bnum)
return anum - bnum;
}
if (abits[2] !== bbits[2]) {
return abits[2] < bbits[2] ? -1 : 1
}
a = abits[3];
b = bbits[3];
}
return a.length - b.length;
}
function shorten(ref) {
var match = /^refs\/(tags|branches)\/(.*)/.exec(ref);
if (match)
return match[2];
match = /^([0-9a-f]{12})[0-9a-f]+$/.exec(ref);
if (match)
return match[1];
// If reference is origin/foo, assume that foo is
// the branch name.
match = /^origin\/(.*)/.exec(ref);
if (match) {
return match[1];
}
return ref;
}
function url(tree, version, path, lno) {
if (tree in CodesearchUI.internalViewRepos) {
return internalUrl(tree, path, lno);
} else {
return externalRepoUrl(tree, version, path, lno);
}
}
function internalUrl(tree, path, lno) {
path = path.replace(/^\/+/, ''); // Trim any leading slashes
var url = "/view/" + tree + "/" + path;
if (lno !== undefined) {
url += "#L" + lno;
}
return url;
}
function externalRepoUrl(tree, version, path, lno) {
var backend = Codesearch.in_flight.backend;
var repo_map = CodesearchUI.repo_urls[backend];
if (!repo_map) {
return null;
}
if (!repo_map[tree]) {
return null;
}
return externalUrl(repo_map[tree], tree, version, path, lno);
}
function externalUrl(url, tree, version, path, lno) {
if (lno === undefined) {
lno = 1;
}
// If {path} already has a slash in front of it, trim extra leading
// slashes from `path` to avoid a double-slash in the URL.
if (url.indexOf('/{path}') !== -1) {
path = path.replace(/^\/+/, '');
}
// the order of these replacements is used to minimize conflicts
url = url.replace(/{lno}/g, lno);
url = url.replace(/{version}/g, shorten(version));
url = url.replace(/{name}/g, tree);
url = url.replace(/{basename}/g, tree.split("/")[1]); // E.g. "foo" in "username/foo"
url = url.replace(/{path}/g, path);
return url;
}
function renderLinkConfigs(linkConfigs, tree, version, path, lno) {
linkConfigs = linkConfigs.filter(function(linkConfig) {
return !linkConfig.whitelist_pattern ||
linkConfig.whitelist_pattern.test(tree + ':' + version + ':' + path);
});
var links = linkConfigs.map(
function(linkConfig) {
var attrs = {
cls: "file-action-link",
href: externalUrl(
linkConfig.url_template,
tree,
version,
path,
lno
),
};
if (linkConfig.target) {
attrs.target = linkConfig.target;
}
return h.a(
attrs,
[linkConfig.label]
);
}
);
var out = [];
for (var i = 0; i < links.length; i++) {
if (i > 0) {
out.push(h.span({cls: "file-action-link-separator",}, ["\u00B7"]));
}
out.push(links[i]);
}
return out;
}
var MatchView = Backbone.View.extend({
tagName: 'div',
initialize: function() {
this.model.on('change', this.render, this);
},
render: function() {
var div = this._render();
this.setElement(div);
return this;
},
_renderLno: function(n, isMatch) {
var lnoStr = n.toString() + (isMatch ? ":" : "-");
var classes = ['lno-link'];
if (isMatch) classes.push('matchlno');
return h.a({cls: classes.join(' '), href: this.model.url(n)}, [
h.span({cls: 'lno', 'aria-label': lnoStr}, [])
]);
},
_render: function() {
var i;
var ctx_before = [], ctx_after = [];
var lno = this.model.get('lno');
var ctxBefore = this.model.get('context_before'), clip_before = this.model.get('clip_before');
var ctxAfter = this.model.get('context_after'), clip_after = this.model.get('clip_after');
var language = this.options.language;
var lines_to_display_before = Math.max(0, ctxBefore.length - (clip_before || 0));
for (i = 0; i < lines_to_display_before; i ++) {
var ctxTextBefore = this.model.get('context_before')[i];
var ctxNodesBefore = highlight.highlightContext(ctxTextBefore, language);
ctx_before.unshift(
this._renderLno(lno - i - 1, false),
ctxNodesBefore ? h.span(ctxNodesBefore) : h.span([ctxTextBefore]),
h.span({}, [])
);
}
var lines_to_display_after = Math.max(0, ctxAfter.length - (clip_after || 0));
for (i = 0; i < lines_to_display_after; i ++) {
var ctxTextAfter = this.model.get('context_after')[i];
var ctxNodesAfter = highlight.highlightContext(ctxTextAfter, language);
ctx_after.push(
this._renderLno(lno + i + 1, false),
ctxNodesAfter ? h.span(ctxNodesAfter) : h.span([ctxTextAfter]),
h.span({}, [])
);
}
var line = this.model.get('line');
var bounds = this.model.get('bounds');
var pieces = [line.substring(0, bounds[0]),
line.substring(bounds[0], bounds[1]),
line.substring(bounds[1])];
var highlightedNodes = highlight.highlightLine(line, language, bounds);
var matchLineContent;
if (highlightedNodes) {
matchLineContent = h.span({cls: 'matchline'}, highlightedNodes);
} else {
matchLineContent = h.span({cls: 'matchline'}, [pieces[0], h.span({cls: 'matchstr'}, [pieces[1]]), pieces[2]]);
}
var classes = ['match'];
if(clip_before !== undefined) classes.push('clip-before');
if(clip_after !== undefined) classes.push('clip-after');
var links = renderLinkConfigs(
CodesearchUI.linkConfigs.filter(function(linkConfig) {
return linkConfig.url_template.includes('{lno}');
}),
this.model.get('tree'),
this.model.get('version'),
this.model.get('path'),
lno
);
var matchElement = h.div({cls: classes.join(' ')}, [
h.div({cls: 'contents'}, [].concat(
ctx_before,
[
this._renderLno(lno, true),
matchLineContent,
h.span({cls: 'matchlinks'}, links)
],
ctx_after
))
]);
return matchElement;
}
});
/**
* A Match represents a single match in the code base.
*
* This model wraps the JSON response from the Codesearch backend for an individual match.
*/
var Match = Backbone.Model.extend({
path_info: function() {
var tree = this.get('tree');
var version = this.get('version');
var path = this.get('path');
return {
id: tree + ':' + version + ':' + path,
tree: tree,
version: version,
path: path
}
},
url: function(lno) {
if (lno === undefined) {
lno = this.get('lno');
}
return url(this.get('tree'), this.get('version'), this.get('path'), lno);
},
});
/** A set of Matches at a single path. */
var FileGroup = Backbone.Model.extend({
initialize: function(path_info) {
// The id attribute is used by collections to fetch models
this.id = path_info.id;
this.path_info = path_info;
this.matches = [];
},
add_match: function(match) {
this.matches.push(match);
},
/** Prepare the matches for rendering by clipping the context of matches to avoid duplicate
* lines being displayed in the search results.
*
* This function operates under these assumptions:
* - The matches are all for the same file
* - Two matches cannot have the same line number
*/
process_context_overlaps: function() {
if(!(this.matches) || this.matches.length < 2) {
return; // We don't have overlaps unless we have at least two things
}
// NOTE: The logic below requires matches to be sorted by line number.
this.matches.sort(function(a, b) {
return a.get('lno') - b.get('lno');
});
for(var i = 1, len = this.matches.length; i < len; i++) {
var previous_match = this.matches[i - 1], this_match = this.matches[i];
var last_line_of_prev_context = previous_match.get('lno') + previous_match.get('context_after').length;
var first_line_of_this_context = this_match.get('lno') - this_match.get('context_before').length;
var num_intersecting_lines = (last_line_of_prev_context - first_line_of_this_context) + 1;
if(num_intersecting_lines >= 0) {
// The matches are intersecting or share a boundary.
// Try to split the context between the previous match and this one.
// Uneven splits should leave the latter element with the larger piece.
// split_at will be the first line number grouped with the latter element.
var split_at = parseInt(Math.ceil((previous_match.get('lno') + this_match.get('lno')) / 2.0), 10);
if (split_at < first_line_of_this_context) {
split_at = first_line_of_this_context;
} else if (last_line_of_prev_context + 1 < split_at) {
split_at = last_line_of_prev_context + 1;
}
var clip_for_previous = last_line_of_prev_context - (split_at - 1);
var clip_for_this = split_at - first_line_of_this_context;
previous_match.set('clip_after', clip_for_previous);
this_match.set('clip_before', clip_for_this);
} else {
previous_match.unset('clip_after');
this_match.unset('clip_before');
}
}
}
});
/** A set of matches that are automatically grouped by path. */
var SearchResultSet = Backbone.Collection.extend({
add_match: function(match) {
var path_info = match.path_info();
var file_group = this.get(path_info.id);
if(!file_group) {
file_group = new FileGroup(path_info);
this.add(file_group);
}
file_group.add_match(match);
},
num_matches: function() {
return this.reduce(function(memo, file_group) {
return memo + file_group.matches.length;
}, 0);
}
});
/**
* A FileMatch represents a single filename match in the code base.
*
* This model wraps the JSON response from the Codesearch backend for an individual match.
*
* XXX almost identical to Match
*/
var FileMatch = Backbone.Model.extend({
path_info: function() {
var tree = this.get('tree');
var version = this.get('version');
var path = this.get('path');
return {
id: tree + ':' + version + ':' + path,
tree: tree,
version: version,
path: path,
bounds: this.get('bounds')
}
},
url: function() {
return url(this.get('tree'), this.get('version'), this.get('path'));
},
});
var FileMatchView = Backbone.View.extend({
tagName: 'div',
render: function() {
var path_info = this.model.path_info();
var pieces = [
path_info.path.substring(0, path_info.bounds[0]),
path_info.path.substring(path_info.bounds[0], path_info.bounds[1]),
path_info.path.substring(path_info.bounds[1])
];
var repoLabel = [
h.span({cls: "repo"}, [path_info.tree, ':']),
h.span({cls: "version"}, [shorten(path_info.version), ':']),
pieces[0],
h.span({cls: "matchstr"}, [pieces[1]]),
pieces[2]
];
var el = this.$el;
el.empty();
el.addClass('filename-match');
el.append(h.a({cls: 'label header result-path', href: this.model.url()}, repoLabel));
return this;
}
});
var SearchState = Backbone.Model.extend({
defaults: function() {
return {
context: true,
displaying: null,
error: null,
search_type: "",
time: null,
why: null
};
},
initialize: function() {
this.search_map = {};
this.search_results = new SearchResultSet();
this.file_search_results = new Backbone.Collection();
this.search_id = 0;
this.on('change:displaying', this.new_search, this);
},
new_search: function() {
this.set({
error: null,
time: null,
why: null
});
this.search_results.reset();
this.file_search_results.reset();
for (var k in this.search_map) {
if (parseInt(k) < this.get('displaying'))
delete this.search_map[k];
}
},
next_id: function() {
return ++this.search_id;
},
dispatch: function (search) {
var cur = this.search_map[this.get('displaying')];
if (cur &&
cur.q === search.q &&
cur.fold_case === search.fold_case &&
cur.regex === search.regex &&
cur.backend === search.backend &&
_.isEqual(cur.repo, search.repo)) {
return false;
}
var id = this.next_id();
search.id = id;
this.search_map[id] = {
q: search.q,
fold_case: search.fold_case,
regex: search.regex,
backend: search.backend,
repo: search.repo
};
if (!search.q.length) {
this.set('displaying', id);
return false;
}
return true;
},
url: function() {
var q = {};
var current = this.search_map[this.get('displaying')];
if (!current)
return '/search';
var base = '/search';
if (current.repo && current.repo.length) {
q.repo = current.repo;
}
if (current.q !== "") {
q.q = current.q;
q.fold_case = current.fold_case;
q.regex = current.regex;
q.context = this.get('context');
}
if (current.backend) {
base += "/" + current.backend
} else if (CodesearchUI.input_backend) {
base += "/" + CodesearchUI.input_backend.val();
}
var qs = $.param(q);
return base + (qs ? "?" + qs : "");
},
title: function() {
var current = this.search_map[this.get('displaying')];
if (!current || !current.q)
return "code search";
return current.q + " ⋅ search";
},
handle_error: function (search, error) {
if (search === this.search_id) {
this.set('displaying', search);
this.set('error', error);
}
},
handle_match: function (search, match) {
if (search < this.get('displaying'))
return false;
this.set('displaying', search);
var m = _.clone(match);
m.backend = this.search_map[search].backend;
this.search_results.add_match(new Match(m));
},
handle_file_match: function (search, file_match) {
if (search < this.get('displaying'))
return false;
this.set('displaying', search);
var fm = _.clone(file_match);
fm.backend = this.search_map[search].backend;
this.file_search_results.add(new FileMatch(fm));
},
handle_done: function (search, time, search_type, why) {
if (search < this.get('displaying'))
return false;
this.set('displaying', search);
this.set({time: time, search_type: search_type, why: why});
this.search_results.trigger('search-complete');
}
});
var FileGroupView = Backbone.View.extend({
tagName: 'div',
render_header: function(tree, version, path) {
var basename, dirname;
var indexOfLastPathSep = path.lastIndexOf('/');
if(indexOfLastPathSep !== -1) {
basename = path.substring(indexOfLastPathSep + 1, path.length);
dirname = path.substring(0, indexOfLastPathSep + 1);
} else {
basename = path; // path doesn't contain any dir parts, only the basename
dirname = '';
}
var first_match = this.model.matches[0];
var headerChildren = [
h.span(
{cls: 'header-path'},
[
h.a(
{cls: 'result-path', href: first_match.url()},
[
h.span({cls: "repo"}, [tree, ':']),
h.span({cls: "version"}, [shorten(version), ':']),
dirname,
h.span({cls: "filename"}, [basename]),
]
),
]
),
h.div(
{cls: 'header-links'},
renderLinkConfigs(CodesearchUI.linkConfigs, tree, version, path, first_match.get('lno'))
),
];
return h.div({cls: 'header'}, headerChildren);
},
render: function() {
var matches = this.model.matches;
var el = this.$el;
var self = this;
el.empty();
el.append(this.render_header(this.model.path_info.tree, this.model.path_info.version, this.model.path_info.path));
var language = highlight.detectLanguage(this.model.path_info.path);
matches.forEach(function(match) {
el.append(
new MatchView({model:match, language: language}).render().el
);
});
el.addClass('file-group');
if (language && typeof Prism !== 'undefined' && !Prism.languages[language] &&
Prism.plugins && Prism.plugins.autoloader && !self._loadingLanguage) {
self._loadingLanguage = true;
Prism.plugins.autoloader.loadLanguages([language], function() {
self._loadingLanguage = false;
if (Prism.languages[language]) {
self.render();
}
}, function() {
self._loadingLanguage = false;
});
}
return this;
}
});
var MatchesView = Backbone.View.extend({
el: $('#results'),
events: {
'click .file-extension': '_limitExtension',
'keydown': '_handleKey',
},
initialize: function() {
this.model.search_results.on('search-complete', this.render, this);
this.model.search_results.on('rerender', this.render, this);
},
render: function() {
this.$el.empty();
// Collate which file extensions (.py, .go, etc) are most common.
// countExtension() is called for file_search_results and search_results
var extension_map = {};
var countExtension = function(path) {
var r = /[^\/](\.[a-z.]{1,6})$/i;
var match = path.match(r);
if (match) {
var ext = match[1];
extension_map[ext] = extension_map[ext] ? extension_map[ext] + 1 : 1;
}
}
var pathResults = h.div({'cls': 'path-results'});
var count = 0;
this.model.file_search_results.each(function(file) {
if (this.model.get('search_type') == 'filename_only' || count < 10) {
var view = new FileMatchView({model: file});
pathResults.append(view.render().el);
}
countExtension(file.attributes.path);
count += 1;
}, this);
this.$el.append(pathResults);
this.model.search_results.each(function(file_group) {
file_group.process_context_overlaps();
var view = new FileGroupView({model: file_group});
this.$el.append(view.render().el);
countExtension(file_group.path_info.path);
}, this);
var i = this.model.search_id;
var query = this.model.search_map[i].q;
var already_file_limited = /\bfile:/.test(query);
if (!already_file_limited)
this._render_extension_buttons(extension_map);
return this;
},
_render_extension_buttons: function(extension_map) {
// Display a series of buttons for the most common file extensions
// among the current search results, that each narrow the search to
// files matching that extension.
var extension_array = [];
for (var ext in extension_map)
extension_array.push([extension_map[ext], ext]);
if (extension_array.length < 2)
return;
extension_array.sort(function(a, b) {return b[0] - a[0];})
var popular_extensions = []
var end = Math.min(extension_array.length, 5);
for (var i=0; i < end; i++)
popular_extensions.push(extension_array[i][1]);
popular_extensions.sort();
var help = 'Narrow to:';
var fileExtensions = h.div({'cls': 'file-extensions'}, [help]);
for (var i=0; i < popular_extensions.length; i++) {
var ext = popular_extensions[i];
fileExtensions.append(h.button({'cls': 'file-extension'}, [ext]));
}
this.$el.prepend(fileExtensions);
},
_limitExtension: function(e) {
var ext = e.target.textContent;
var q = CodesearchUI.input.val();
if (CodesearchUI.input_regex.is(':checked'))
q = 'file:\\' + ext + '$ ' + q;
else
q = 'file:' + ext + ' ' + q;
CodesearchUI.input.val(q);
CodesearchUI.newsearch();
},
_handleKey: function(e) {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
return;
var which = event.which;
if (which === KeyCodes.SLASH_OR_QUESTION_MARK) {
var t = getSelectedText();
if (!t)
return;
event.preventDefault();
if (CodesearchUI.input_regex.is(':checked'))
t = t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // from mozilla docs
// Make sure that the search results the user is looking at, in
// which they've selected text, get persisted in their browser
// history so that they can come back to them.
last_url_update = 0;
CodesearchUI.input.val(t);
CodesearchUI.newsearch();
}
}
});
var ResultView = Backbone.View.extend({
el: $('#resultarea'),
initialize: function() {
this.matches_view = new MatchesView({model: this.model});
this.results = this.$('#numresults');
this.errorbox = $('#regex-error');
this.time = this.$('#searchtime');
this.last_url = null;
this.last_title = null;
this.model.on('all', this.render, this);
this.model.search_results.on('all', this.render, this);
},
render: function() {
if (this.model.get('displaying') === null) {
return;
}
if (this.model.get('error')) {
this.errorbox.find('#errortext').text(this.model.get('error'));
this.errorbox.show();
} else {
this.errorbox.hide()
}
var url = this.model.url();
if (this.last_url !== url ) {
if (history.pushState) {
var browser_url = window.location.pathname + window.location.search;
if (browser_url !== url) {
// If the user is typing quickly, just keep replacing the
// current URL. But after they've paused, enroll the URL they
// paused at into their browser history.
var now = Date.now();
var two_seconds = 2000;
if (this.last_url === null) {
// If this.last_url is null, that means this is the initial
// navigation. We should never pushState here, otherwise the
// user will need to backspace twice to go back to the
// previous page.
history.replaceState(null, '', url);
} else if (now - last_url_update > two_seconds) {
history.pushState(null, '', url);
} else {
history.replaceState(null, '', url);
}
last_url_update = now;
}
}
this.last_url = url;
}
var title = this.model.title();
if (this.last_title !== title) {
document.title = title;
this.last_title = title;
}
if (this.model.search_map[this.model.get('displaying')].q === '' ||
this.model.get('error')) {
this.$el.hide();
$('#helparea').show();
return this;
}
$('#results').toggleClass('no-context', !this.model.get('context'));
this.$el.show();
$('#helparea').hide();
if (this.model.get('time')) {
this.$('#searchtimebox').show();
var time = this.model.get('time');
this.time.text((time/1000) + "s")
} else {
this.$('#searchtimebox').hide();
}
var results;
if (this.model.get('search_type') == 'filename_only') {
results = '' + this.model.file_search_results.length;
} else {
results = '' + this.model.search_results.num_matches();
}
if (this.model.get('why') !== 'NONE')
results = results + '+';
this.results.text(results);
return this;
}
});
var CodesearchUI = function() {
return {
state: new SearchState(),
view: null,
onload: function() {
if (CodesearchUI.input)
return;
CodesearchUI.view = new ResultView({model: CodesearchUI.state});
CodesearchUI.input = $('#searchbox');
CodesearchUI.input_repos = $('#repos');
CodesearchUI.input_backend = $('#backend');
if (CodesearchUI.input_backend.length == 0)
CodesearchUI.input_backend = null;
CodesearchUI.inputs_case = $('input[name=fold_case]');
CodesearchUI.input_regex = $('input[name=regex]');
CodesearchUI.input_context = $('input[name=context]');
CodesearchUI.input_syntax_theme = $('#syntax-theme');
if (CodesearchUI.input_syntax_theme.length) {
CodesearchUI.input_syntax_theme.append($('<option>').val('default').text('Default'));
syntaxThemes.forEach(function(t) {
CodesearchUI.input_syntax_theme.append($('<option>').val(t.key).text(t.label));
});
}
if (CodesearchUI.inputs_case.filter(':checked').length == 0) {
CodesearchUI.inputs_case.filter('[value=auto]').attr('checked', true);
}
CodesearchUI.input.keydown(CodesearchUI.keypress);
CodesearchUI.input.bind('paste', CodesearchUI.keypress);
CodesearchUI.input.focus();
if (CodesearchUI.input_backend)
CodesearchUI.input_backend.change(CodesearchUI.select_backend);
CodesearchUI.inputs_case.change(CodesearchUI.keypress);
CodesearchUI.input_regex.change(CodesearchUI.keypress);
CodesearchUI.input_repos.change(CodesearchUI.keypress);
CodesearchUI.input_context.change(CodesearchUI.toggle_context);
CodesearchUI.input_regex.change(function(){
CodesearchUI.set_pref('regex', CodesearchUI.input_regex.prop('checked'));
});
CodesearchUI.input_repos.change(function(){
CodesearchUI.set_pref('repos', CodesearchUI.input_repos.val());
});
CodesearchUI.input_context.change(function(){
CodesearchUI.set_pref('context', CodesearchUI.input_context.prop('checked'));
});
CodesearchUI.input_syntax_theme.change(function(){
var theme = CodesearchUI.input_syntax_theme.val();
applySyntaxTheme(theme);
CodesearchUI.set_pref('syntaxTheme', theme);
});
CodesearchUI.toggle_context();
// Defer heavy repo dropdown initialization so the page can paint first.
// RepoSelector.init() creates the bootstrap-select widget (expensive with many repos).
setTimeout(function() {
RepoSelector.init();
CodesearchUI.update_repo_options();
CodesearchUI.render_repo_presets();
CodesearchUI.init_query();
}, 0);
Codesearch.connect(CodesearchUI);
$('.query-hint code').click(function(e) {
var ext = e.target.textContent;
var q = CodesearchUI.input.val();
if( !q.includes(ext)
&& ((ext.indexOf('-') == 0 && !q.includes(ext.substring(1)))
|| (ext.indexOf('-') != 0 && !q.includes('-' + ext.substring)))
) {
q = q + ' ' + ext;
}
CodesearchUI.input.val(q);
CodesearchUI.input.focus();
})
// Update the search when the user hits Forward or Back.
window.onpopstate = function(event) {
var parms = CodesearchUI.parse_query_params();
CodesearchUI.init_query_from_parms(parms);
CodesearchUI.newsearch();
}
},
toggle_context: function(){
CodesearchUI.state.set('context', CodesearchUI.input_context.prop('checked'));
},
// Initialize query from URL or user's saved preferences
init_query: function() {
var parms = CodesearchUI.parse_query_params();
var hasParms = false;
for (var p in parms) {
hasParms = true;
break;
}
if (hasParms) {
CodesearchUI.init_query_from_parms(parms);
} else {
CodesearchUI.init_controls_from_prefs();
}
setTimeout(CodesearchUI.keypress, 0);
},
init_query_from_parms: function(parms) {
var q = [];
if (parms.q)
q.push(parms.q[0]);
if (parms.file)
q.push("file:" + parms.file[0]);
CodesearchUI.input.val(q.join(' '));
if (parms.fold_case) {
CodesearchUI.inputs_case.filter('[value='+parms.fold_case[0]+']').attr('checked', true);
}
if (parms.regex) {
CodesearchUI.input_regex.prop('checked', parms.regex[0] === "true");
}
if (parms.context) {
CodesearchUI.input_context.prop('checked', parms.context[0] === 'true');
}
var backend = null;
if (parms.backend)
backend = parms.backend;
var m;
if (m = (new RegExp("/search/([^\/]+)/?").exec(window.location.pathname))) {
backend = m[1];
}
if (backend && CodesearchUI.input_backend) {
var old_backend = CodesearchUI.input_backend.val();
CodesearchUI.input_backend.val(backend);
// Something (bootstrap-select?) messes with the behaviour of val() on
// normal select elements, so that trying to set an invalid value sets
// null, rather than leaving the value unchanged. We manually check and
// roll back if that happens (e.g. because someone navigated to a URL
// like "/search/bogus?q=foo").
if (CodesearchUI.input_backend.val() === null) {
CodesearchUI.input_backend.val(old_backend);
}
}