Skip to content

Commit 7a1b2d9

Browse files
author
Andy Hanson
committed
Port PR microsoft#3 changes from js to ts
1 parent 64a80cc commit 7a1b2d9

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

assets/script/search.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ interface MinifiedSearchRecord {
2323
d: number;
2424
}
2525

26+
interface Bloodhound<T> {
27+
local: T[];
28+
}
29+
2630
function typeSearch(el: HTMLInputElement) {
2731
const jqueryEl = $(el);
2832
const opts: Twitter.Typeahead.Options = {
@@ -62,6 +66,11 @@ function typeSearch(el: HTMLInputElement) {
6266
if (ai) {
6367
ai.trackEvent('navigate', { target: value });
6468
}
69+
// Navigate only if the selected string is a valid package, else return.
70+
const result = source.local.some((e: MinifiedSearchRecord) => e.t === value);
71+
if (!result) {
72+
return;
73+
}
6574
window.location.href = `https://www.npmjs.org/package/@types/${value}`;
6675
}
6776

@@ -83,7 +92,8 @@ function typeSearch(el: HTMLInputElement) {
8392
}
8493
}
8594

86-
function createDataSource() {
95+
function createDataSource(): Bloodhound<MinifiedSearchRecord> {
96+
let query = "";
8797
const local = JSON.parse(window.localStorage.getItem(localStorageDataKey)) || undefined;
8898

8999
const bh = new Bloodhound({
@@ -92,6 +102,7 @@ function typeSearch(el: HTMLInputElement) {
92102
return [entry.l, entry.p, entry.t].concat(entry.g).concat(entry.m);
93103
},
94104
queryTokenizer: (input: string) => {
105+
query = input;
95106
return [input];
96107
},
97108
identify: (e: MinifiedSearchRecord) => <any>e.t,
@@ -101,7 +112,16 @@ function typeSearch(el: HTMLInputElement) {
101112
},
102113
sorter: (x: MinifiedSearchRecord, y: MinifiedSearchRecord) => {
103114
// TODO: Include edit distance as additional weighting factor
104-
return y.d - x.d;
115+
// Direct matches should be ranked higher, else rank on basis of download count
116+
if (x.t === query || x.t === (query + "js") || x.t === (query + ".js") || x.t === (query + "-js")) {
117+
return -1;
118+
}
119+
else if (y.t === query || y.t === (query + "js") || y.t === (query + ".js") || y.t === (query + "-js")) {
120+
return 1;
121+
}
122+
else {
123+
return y.d - x.d;
124+
}
105125
},
106126
local
107127
});

0 commit comments

Comments
 (0)