Skip to content

Commit 069fbf6

Browse files
authored
Search automatically on ?q= URL query parameter (#1396)
Fixes #1319 (I wanted this for exactly that reason 😅) Automatically start searching when ?q= parameter is given in the URL, selecting and visiting the first match if available. If not available, the query will be filled into the search box but we won't navigate away. This should enable configuring a generated rdoc page as a search engine in one's web browser, or as a bang command in a search engine. For reference Rails' sdoc (which I think rdoc's search is originally based on) does this: https://api.rubyonrails.org/?q=changed%3F
1 parent cff3877 commit 069fbf6

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

lib/rdoc/generator/template/darkfish/js/darkfish.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,30 @@ function hookSearch() {
7272
}
7373

7474
search.select = function(result) {
75-
window.location.href = result.firstChild.firstChild.href;
75+
var href = result.firstChild.firstChild.href;
76+
var query = this.input.value;
77+
if (query) {
78+
var url = new URL(href, window.location.origin);
79+
url.searchParams.set('q', query);
80+
url.searchParams.set('nav', '0');
81+
href = url.toString();
82+
}
83+
window.location.href = href;
7684
}
7785

7886
search.scrollIntoView = search.scrollInWindow;
87+
88+
// Check for ?q= URL parameter and trigger search automatically
89+
if (typeof URLSearchParams !== 'undefined') {
90+
var urlParams = new URLSearchParams(window.location.search);
91+
var queryParam = urlParams.get('q');
92+
if (queryParam) {
93+
var navParam = urlParams.get('nav');
94+
var autoSelect = navParam !== '0';
95+
input.value = queryParam;
96+
search.search(queryParam, autoSelect);
97+
}
98+
}
7999
};
80100

81101
function hookFocus() {

lib/rdoc/generator/template/darkfish/js/search.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ Search.prototype = Object.assign({}, Navigation, new function() {
3434
}
3535

3636
this.search = function(value, selectFirstMatch) {
37+
this.selectFirstMatch = selectFirstMatch;
38+
3739
value = value.trim().toLowerCase();
3840
if (value) {
3941
this.setNavigationActive(true);
@@ -76,7 +78,15 @@ Search.prototype = Object.assign({}, Navigation, new function() {
7678
//TODO: ECMAScript
7779
//if (jQuery.browser.msie) this.$element[0].className += '';
7880

79-
if (isLast) this.result.setAttribute('aria-busy', 'false');
81+
if (this.selectFirstMatch && this.current) {
82+
this.selectFirstMatch = false;
83+
this.select(this.current);
84+
}
85+
86+
if (isLast) {
87+
this.selectFirstMatch = false;
88+
this.result.setAttribute('aria-busy', 'false');
89+
}
8090
}
8191

8292
this.move = function(isDown) {

0 commit comments

Comments
 (0)