A semantic search engine for source code https://bitshift.benkurtovic.com/
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

446 rader
17 KiB

  1. /*
  2. * @file Manages all library initialization, jQuery callbacks, query entry
  3. * callbacks, server querying, and results diplay for `index.html`.
  4. */
  5. var advancedSearchDiv = $("div#advanced-search");
  6. var advancedSearchButton = $("button#advanced-search");
  7. FINISH_TYPING_INTERVAL = 650;
  8. var searchBar = $("form#search-bar input[type='text']")[0];
  9. var resultsDiv = $("div#results")[0];
  10. var typingTimer, scrollTimer, lastValue;
  11. var searchResultsPage = 1;
  12. /*
  13. * Set all page callbacks.
  14. */
  15. (function setHomePageCallbabacks(){
  16. var results = $('#results').get(0);
  17. // Enable infinite scrolling down the results page.
  18. $(window).scroll(function(){
  19. if($(window).scrollTop() + $(window).height() == $(document).height() &&
  20. resultsDiv.querySelectorAll(".result").length > 0)
  21. loadMoreResults();
  22. clearTimeout(scrollTimer);
  23. if (!results.classList.contains('disable-hover'))
  24. results.classList.add('disable-hover')
  25. scrollTimer = setTimeout(function(){
  26. if (results.classList.contains('disable-hover'))
  27. results.classList.remove('disable-hover');
  28. }, 200);
  29. });
  30. // Toggle the advanced-search form's visibility.
  31. advancedSearchButton.click(function(){
  32. var searchField = $("div#search-field");
  33. if(!advancedSearchDiv.hasClass("visible")){
  34. searchField.addClass("partly-visible");
  35. advancedSearchDiv.fadeIn(500).addClass("visible");
  36. advancedSearchButton.addClass("clicked");
  37. }
  38. else {
  39. advancedSearchDiv.fadeOut(300).removeClass("visible");
  40. advancedSearchButton.removeClass("clicked");
  41. if($("div#results .result").length == 0)
  42. searchField.removeClass("partly-visible");
  43. }
  44. });
  45. // Enable capturing the `enter` key.
  46. $("form#search-bar").submit(function(event){
  47. event.preventDefault();
  48. return false;
  49. });
  50. searchBar.onkeyup = typingTimer;
  51. }());
  52. /*
  53. * Set keyboard shortcut mappings.
  54. */
  55. (function resultsHotkeys(){
  56. /*
  57. * If the currently viewed result is not the first, scroll to the previous
  58. * result.
  59. */
  60. var previousResult = function(){
  61. var currResult = $(".display-all");
  62. if(currResult.length) {
  63. currResult.removeClass("display-all");
  64. currResult = currResult.closest(".result").prev(".result");
  65. } else {
  66. currResult = $(document.querySelectorAll(".result")[0]);
  67. }
  68. currResult.addClass("display-all");
  69. currResult.each(function(){
  70. $('html,body').stop().animate({
  71. scrollTop: $(this).offset().top - (
  72. $(window).height() - $(this).outerHeight(true)) / 2
  73. }, 140);
  74. });
  75. };
  76. /*
  77. * If the currently viewed result is not the last, scroll to the next
  78. * result.
  79. */
  80. var nextResult = function(){
  81. var currResult = $(".display-all");
  82. if(currResult.length) {
  83. currResult.removeClass("display-all");
  84. currResult = currResult.closest(".result").next(".result");
  85. } else {
  86. currResult = $(document.querySelectorAll(".result")[0]);
  87. }
  88. currResult.addClass('display-all');
  89. currResult.each(function(){
  90. $('html,body').stop().animate({
  91. scrollTop: $(this).offset().top - (
  92. $(window).height() - $(this).outerHeight(true)) / 2
  93. }, 140);
  94. });
  95. };
  96. var displayHotkeyHelp = function(){
  97. var help = $("div#hotkey-help");
  98. console.log("H");
  99. if(help.hasClass("hidden"))
  100. help.fadeIn(420);
  101. else
  102. help.fadeOut(420);
  103. $("div#body").toggleClass("faded");
  104. help.toggleClass("hidden");
  105. }
  106. var hotkeyActions = {
  107. "k" : previousResult,
  108. "j" : nextResult,
  109. "h" : previousSymbolMatch,
  110. "l" : nextSymbolMatch,
  111. "?" : displayHotkeyHelp
  112. };
  113. $(window).keypress(function(key){
  114. for(var hotkey in hotkeyActions){
  115. var keyChar = String.fromCharCode(key.keyCode);
  116. if(keyChar == hotkey &&
  117. !($(key.target).is("textarea") || $(key.target).is("input")))
  118. hotkeyActions[keyChar]();
  119. }
  120. });
  121. }());
  122. //Obtained by parsing python file with pygments
  123. var codeExample = '<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40</pre></div></td><td class="code"><div class="highlight"><pre><span class="sd">&quot;&quot;&quot;</span>\n<span class="sd">Module to contain all the project&#39;s Flask server plumbing.</span>\n<span class="sd">&quot;&quot;&quot;</span>\n\n<span class="kn">from</span> <span class="nn">flask</span> <span class="kn">import</span> <span class="n">Flask</span>\n<span class="kn">from</span> <span class="nn">flask</span> <span class="kn">import</span> <span class="n">render_template</span><span class="p">,</span> <span class="n">session</span>\n\n<span class="kn">from</span> <span class="nn">bitshift</span> <span class="kn">import</span> <span class="n">assets</span>\n<span class="c"># from bitshift.database import Database</span>\n<span class="c"># from bitshift.query import parse_query</span>\n\n<span class="hll"><span class="n">app</span> <span class="o">=</span> <span class="n">Flask</span><span class="p">(</span><span class="n">__name__</span><span class="p">)</span>\n</span><span class="hll"><span class="n">app</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">from_object</span><span class="p">(</span><span class="s">&quot;bitshift.config&quot;</span><span class="p">)</span>\n</span>\n<span class="hll"><span class="n">app_env</span> <span class="o">=</span> <span class="n">app</span><span class="o">.</span><span class="n">jinja_env</span>\n</span><span class="hll"><span class="n">app_env</span><span class="o">.</span><span class="n">line_statement_prefix</span> <span class="o">=</span> <span class="s">&quot;=&quot;</span>\n</span><span class="hll"><span class="n">app_env</span><span class="o">.</span><span class="n">globals</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">assets</span><span class="o">=</span><span class="n">assets</span><span class="p">)</span>\n</span>\n<span class="c"># database = Database()</span>\n\n<span class="hll"><span class="nd">@app.route</span><span class="p">(</span><span class="s">&quot;/&quot;</span><span class="p">)</span>\n</span><span class="k">def</span> <span class="nf">index</span><span class="p">():</span>\n <span class="k">return</span> <span class="n">render_template</span><span class="p">(</span><span class="s">&quot;index.html&quot;</span><span class="p">)</span>\n\n<span class="hll"><span class="nd">@app.route</span><span class="p">(</span><span class="s">&quot;/search/&lt;query&gt;&quot;</span><span class="p">)</span>\n</span><span class="k">def</span> <span class="nf">search</span><span class="p">(</span><span class="n">query</span><span class="p">):</span>\n <span class="c"># tree = parse_query(query)</span>\n <span class="c"># database.search(tree)</span>\n <span class="k">pass</span>\n\n<span class="hll"><span class="nd">@app.route</span><span class="p">(</span><span class="s">&quot;/about&quot;</span><span class="p">)</span>\n</span><span class="k">def</span> <span class="nf">about</span><span class="p">():</span>\n <span class="k">return</span> <span class="n">render_template</span><span class="p">(</span><span class="s">&quot;about.html&quot;</span><span class="p">)</span>\n\n<span class="hll"><span class="nd">@app.route</span><span class="p">(</span><span class="s">&quot;/developers&quot;</span><span class="p">)</span>\n</span><span class="k">def</span> <span class="nf">developers</span><span class="p">():</span>\n <span class="k">return</span> <span class="n">render_template</span><span class="p">(</span><span class="s">&quot;developers.html&quot;</span><span class="p">)</span>\n\n<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&quot;__main__&quot;</span><span class="p">:</span>\n<span class="hll"> <span class="n">app</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">debug</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>\n</span></pre></div>\n</td></tr></table>'
  124. var testCodelet = {
  125. 'url': 'https://github.com/earwig/bitshift/blob/develop/app.py',
  126. 'name': 'app.py',
  127. 'language': 'python',
  128. 'date_created': 'May 10, 2014',
  129. 'date_modified': '2 days ago',
  130. 'origin': ['GitHub', 'https://github.com', ''],
  131. 'authors': ['sevko', 'earwig'],
  132. 'code': codeExample
  133. };
  134. // Enable infinite scrolling down the results page.
  135. $(window).scroll(function() {
  136. var searchField = $("div#search-field");
  137. if($(window).scrollTop() + $(window).height() == $(document).height() &&
  138. searchField.hasClass('partly-visible')){
  139. loadMoreResults();
  140. }
  141. });
  142. /*
  143. * Clear the existing timer and set a new one the the user types text into the
  144. * search bar.
  145. */
  146. function typingTimer(event){
  147. clearTimeout(typingTimer);
  148. var enterKeyCode = 13;
  149. if(event.keyCode != enterKeyCode){
  150. if(lastValue != searchBar.value)
  151. typingTimer = setTimeout(finishedTyping, FINISH_TYPING_INTERVAL);
  152. }
  153. else {
  154. event.preventDefault();
  155. finishedTyping();
  156. return false;
  157. }
  158. };
  159. /*
  160. * Callback which queries the server whenver the user stops typing.
  161. *
  162. * Whenever the user doesn't type for a `FINISH_TYPING_INTERVAL` after having
  163. * entered new text in the search bar, send the current query request to the
  164. * server.
  165. */
  166. function finishedTyping(){
  167. lastValue = searchBar.value;
  168. var searchField = $("div#search-field");
  169. clearResults();
  170. if(searchBar.value){
  171. searchField.addClass("partly-visible");
  172. populateResults();
  173. }
  174. else {
  175. searchField.removeClass("partly-visible");
  176. $("div#advanced-search").fadeOut(50);
  177. advancedSearchButton.removeClass("clicked");
  178. }
  179. }
  180. /*
  181. * Removes any child elements of `div#results`.
  182. */
  183. function clearResults(){
  184. while(resultsDiv.firstChild)
  185. resultsDiv.removeChild(resultsDiv.firstChild);
  186. }
  187. /*
  188. * Create a result element based upon a codelet instance.
  189. *
  190. * @return {Element} The result element.
  191. */
  192. function createResult(codelet) {
  193. //Level 1
  194. var newDiv = document.createElement("div"),
  195. table = document.createElement("table"),
  196. row = document.createElement("tr");
  197. //Level 2
  198. var displayInfo = document.createElement("div"),
  199. codeElt = document.createElement("td"),
  200. hiddenInfoContainer = document.createElement("td"),
  201. hiddenInfo = document.createElement("div"),
  202. cycle = document.createElement("div");
  203. //Level 3
  204. var title = document.createElement("span"),
  205. site = document.createElement("span"),
  206. nextMatch = document.createElement("a"),
  207. prevMatch = document.createElement("a"),
  208. dateModified = document.createElement("div"),
  209. language = document.createElement("div"),
  210. dateCreated = document.createElement("div"),
  211. authors = document.createElement("div");
  212. //Classes and ID's
  213. newDiv.classList.add('result');
  214. displayInfo.id = 'display-info';
  215. codeElt.id = 'code';
  216. hiddenInfo.id = 'hidden-info';
  217. cycle.id = 'cycle-matches'
  218. title.id = 'title';
  219. site.id = 'site';
  220. nextMatch.id = 'next-match';
  221. nextMatch.href = '#';
  222. prevMatch.id = 'prev-match';
  223. prevMatch.href = '#';
  224. dateModified.id = 'date-modified';
  225. language.id = 'language';
  226. dateCreated.id = 'date-created';
  227. authors.id = 'authors';
  228. //Add the bulk of the html
  229. title.innerHTML = ' &raquo; <a href="' + codelet.url + '">'
  230. + codelet.name + '</a>';
  231. site.innerHTML = '<a href="' + codelet.origin[1] + '">' + codelet.origin[0] +'</a>';
  232. nextMatch.innerHTML = 'next match';
  233. prevMatch.innerHTML = 'prev match';
  234. language.innerHTML = 'Language: <span>' + codelet.lang + '</span>';
  235. dateModified.innerHTML = 'Last modified: <span>' + codelet.modified + '</span>';
  236. // Needs to be changed from int to string on the server
  237. dateCreated.innerHTML = 'Created: <span>' + codelet.created + '</span>';
  238. var authorsHtml = 'Authors: <span>';
  239. codelet.authors.forEach(function(a, i) {
  240. if (i == codelet.authors.length - 1)
  241. authorsHtml += '<a href=#>' + a + ' </a>';
  242. else
  243. authorsHtml += '<a href=#>' + a + ' </a>, ';
  244. });
  245. authors.innerHTML = authorsHtml;
  246. // Needs to be processed on the server
  247. codeElt.innerHTML = '<div id=tablecontainer>' + codelet.code + '</div>';
  248. //Event binding
  249. $(newDiv).on('mousemove', function(e) {
  250. var holdCondition = $('.disable-hover');
  251. if(holdCondition.length == 0) {
  252. $(this).siblings().removeClass('display-all');
  253. $(this).addClass('display-all');
  254. }
  255. });
  256. $(newDiv).on('mouseleave', function(e) {
  257. var holdCondition = $('.disable-hover');
  258. if(holdCondition.length == 0)
  259. $(this).removeClass('display-all');
  260. });
  261. $(nextMatch).click(function(e) {
  262. e.stopPropagation();
  263. e.preventDefault();
  264. nextSymbolMatch();
  265. });
  266. $(prevMatch).click(function(e) {
  267. e.stopPropagation();
  268. e.preventDefault();
  269. previousSymbolMatch();
  270. });
  271. //Finish and append elements to parent elements
  272. hiddenInfo.appendChild(dateCreated);
  273. hiddenInfo.appendChild(dateModified);
  274. hiddenInfo.appendChild(language);
  275. hiddenInfo.appendChild(authors);
  276. hiddenInfoContainer.appendChild(hiddenInfo);
  277. row.appendChild(codeElt);
  278. row.appendChild(hiddenInfoContainer);
  279. table.appendChild(row);
  280. displayInfo.appendChild(site);
  281. displayInfo.appendChild(title);
  282. cycle.appendChild(prevMatch);
  283. cycle.appendChild(nextMatch);
  284. newDiv.appendChild(displayInfo);
  285. newDiv.appendChild(table);
  286. return newDiv;
  287. }
  288. function previousSymbolMatch() {
  289. var currResult = $(".display-all"),
  290. currMatch = currResult.find(".hll.current"),
  291. matches = currResult.find(".hll"),
  292. scrollDiv = currResult.find("#tablecontainer");
  293. if (currMatch.length == 0)
  294. currMatch = matches[0];
  295. else
  296. currMatch.removeClass('current');
  297. var index = matches.index(currMatch.get(0)) - 1;
  298. index = index <= 0 ? matches.length - 1 : index;
  299. var newMatch = $(matches[index]);
  300. scrollDiv.scrollTop(scrollDiv.scrollTop()
  301. - scrollDiv.height() / 2
  302. + newMatch.position().top + newMatch.height() / 2);
  303. newMatch.effect("highlight", {color: '#FFF'}, 750)
  304. newMatch.addClass('current');
  305. };
  306. function nextSymbolMatch() {
  307. var currResult = $(".display-all"),
  308. currMatch = currResult.find(".hll.current"),
  309. matches = currResult.find(".hll"),
  310. scrollDiv = currResult.find("#tablecontainer");
  311. if (currMatch.length == 0)
  312. currMatch = $(matches[0]);
  313. else
  314. currMatch.removeClass("current");
  315. var index = matches.index(currMatch.get(0)) + 1;
  316. index = index >= matches.length ? 0 : index;
  317. var newMatch = $(matches[index]);
  318. scrollDiv.scrollTop(scrollDiv.scrollTop()
  319. - scrollDiv.height() / 2
  320. + newMatch.position().top + newMatch.height() / 2);
  321. newMatch.effect("highlight", {color: "#FFF"}, 750)
  322. newMatch.addClass("current");
  323. };
  324. /*
  325. * AJAX the current query string to the server, and return its response.
  326. *
  327. * @return {Array} The server's response in the form of `div.result` DOM
  328. * elements, to fill `div#results`.
  329. */
  330. function queryServer(){
  331. var queryUrl = document.URL + "search.json?" + $.param({
  332. "q" : searchBar.value,
  333. "p" : searchResultsPage++
  334. });
  335. var results = $.Deferred();
  336. $.getJSON(queryUrl, function(result){
  337. var resultDivs = [];
  338. if("error" in result)
  339. insertErrorMessage(result["error"]);
  340. else
  341. for(var codelet = 0; codelet < result["results"].length; codelet++){
  342. resultDivs.push(createResult(result["results"][codelet]));
  343. console.log(result["results"][codelet]);
  344. }
  345. results.resolve(resultDivs);
  346. });
  347. return results;
  348. }
  349. /*
  350. * Query the server with the current search string, and populate `div#results`
  351. * with its response.
  352. */
  353. function populateResults(){
  354. searchResultsPage = 1;
  355. loadMoreResults();
  356. }
  357. /*
  358. * Query the server for the next results page, and add its codelets to
  359. * `div#results`.
  360. */
  361. function loadMoreResults(){
  362. queryServer().done(function(results){
  363. for(var result = 0; result < results.length; result++){
  364. var newDiv = results[result];
  365. resultsDiv.appendChild(newDiv);
  366. setTimeout(
  367. (function(divReference){
  368. return function(){
  369. divReference.classList.add("cascade");
  370. };
  371. }(newDiv)),
  372. result * 20);
  373. }
  374. });
  375. }
  376. /*
  377. * Displays a warning message in the UI.
  378. *
  379. * @param msg (str) The message string.
  380. */
  381. function insertErrorMessage(msg){
  382. var error = $("<div id='error'><span>Error: </span></div>");
  383. error.append(msg);
  384. resultsDiv.appendChild(error[0]);
  385. }