Skip to content

Commit be54d05

Browse files
author
Orta Therox
authored
Merge pull request microsoft#38 from JoshuaKGoldberg/url-search
Hooked up search inputs to URL 'search' query param
2 parents d83398a + 29453f2 commit be54d05

File tree

2 files changed

+33
-9
lines changed

2 files changed

+33
-9
lines changed

assets/script/search.ts

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@ interface Bloodhound<T> {
1919
local: T[];
2020
}
2121

22-
function typeSearch(el: HTMLInputElement) {
23-
const jqueryEl = $(el);
22+
function typeSearch(jqueryEl: JQuery, search?: string) {
2423
const opts: Twitter.Typeahead.Options = {
2524
highlight: true,
2625
minLength: 0
@@ -47,13 +46,30 @@ function typeSearch(el: HTMLInputElement) {
4746
if (k.keyCode === 13) { // Enter key
4847
const selectables = jqueryEl.siblings(".tt-menu").find(".tt-selectable");
4948
$(selectables[0]).trigger("click");
49+
} else {
50+
updateSearch(jqueryEl.val());
5051
}
5152
});
5253

54+
if (search) {
55+
jqueryEl.typeahead('val', search).typeahead('open');
56+
}
57+
5358
function navigate(record: MinifiedSearchRecord) {
5459
window.location.href = `https://www.npmjs.org/package/@types/${record.t}`;
5560
}
5661

62+
function updateSearch(newValue: string) {
63+
if (!URLSearchParams) {
64+
return;
65+
}
66+
67+
const params = new URLSearchParams(window.location.search);
68+
params.set('search', newValue);
69+
70+
history.pushState(null, '', `${window.location.pathname}?${params}`);
71+
}
72+
5773
function createDataSource(): Bloodhound<MinifiedSearchRecord> {
5874
let query = "";
5975
return new Bloodhound<MinifiedSearchRecord>({
@@ -83,3 +99,18 @@ function typeSearch(el: HTMLInputElement) {
8399
});
84100
}
85101
}
102+
103+
$(() => {
104+
const params = window.location.search
105+
.substring(1)
106+
.split('&')
107+
.reduce<Record<string, string>>((params, pair) => {
108+
const [key, value] = pair.split('=');
109+
params[key] = value;
110+
return params;
111+
}, {});
112+
const jqueryEl = $("#demo");
113+
114+
typeSearch(jqueryEl, params.search);
115+
jqueryEl.focus();
116+
});

assets/static/index.html

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,6 @@
88
<script src="lib/jquery.min.js"></script>
99
<script src="lib/typeahead.bundle.min.js"></script>
1010
<script src="script/search.js"></script>
11-
<script>
12-
$(function() {
13-
var el = document.getElementById('demo');
14-
typeSearch(el);
15-
$(el).focus();
16-
});
17-
</script>
1811
</head>
1912
<body>
2013
<h1><span class="typescript"><span class="bold">Type</span>Search</span></h1>

0 commit comments

Comments
 (0)