This repository has been archived by the owner on Jun 7, 2024. It is now read-only.
forked from speced/respec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search-specref.js
97 lines (93 loc) · 2.65 KB
/
search-specref.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
// Module ui/search-specref
// Search Specref database
"use strict";
define(["core/biblio", "core/ui"], function(biblio, ui) {
function pluralize(count, sing, plur) {
return count + " " + (count == 1 ? sing : plur);
}
function buildResults(json) {
var html = "", count = 0;
for (var k in json) {
var obj = json[k];
if (!obj.aliasOf) {
count++;
html +=
"<dt>[" +
(obj.id || k) +
"]</dt><dd><small>" +
biblio.stringifyReference(obj) +
"</small></dd>";
}
}
return { html: html, count: count };
}
function msg(query, count) {
if (count) {
return (
"We found " +
pluralize(count, "result", "results") +
" for your search for '" +
query +
"'."
);
}
return (
"Your search for '" +
query +
"' did not match any references in the Specref database.<br>Sorry. 😢"
);
}
function highlight(txt, searchString) {
var regexp = new RegExp("(<[^>]+>)|(" + searchString + ")", "gi");
return (txt || "").replace(regexp, function wrap(_, tag, txt) {
if (tag) return tag;
return (
"<strong style='font-weight: inherit; background-color: yellow'>" +
txt +
"</strong>"
);
});
}
const button = ui.addCommand(
"Search Specref DB",
"ui/search-specref",
"Ctrl+Shift+Alt+space",
"🔎"
);
return {
show: function() {
var $halp = $(
"<div><form><p><input name=q type=search> <input type=submit value=search /></p></form></div"
);
var $search = $halp.find("input[type=search]");
var $status = $("<p style='font-size: smaller'></p>");
var $results = $("<dl></dl>");
$status.appendTo($halp);
$results.appendTo($halp);
ui.freshModal("Search Specref DB", $halp, button);
$search.focus();
$halp.find("form").on("submit", function() {
$status.html("Searching…");
var query = $search.val();
$.when(
$.getJSON("https://specref.herokuapp.com/search-refs", { q: query }),
$.getJSON("https://specref.herokuapp.com/reverse-lookup", {
urls: query,
})
).done(function(search, revLookup) {
var ref;
(search = search[0]), (revLookup = revLookup[0]);
for (var k in revLookup) {
ref = revLookup[k];
search[ref.id] = ref;
}
var output = buildResults(search);
$results.html(highlight(output.html, query));
$status.html(msg(query, output.count));
$search.select();
});
return false;
});
},
};
});