A semantic search engine for source code https://bitshift.benkurtovic.com/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

427 rivejä
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, lastValue;
  11. var searchResultsPage = 1;
  12. /*
  13. * Set all page callbacks.
  14. */
  15. (function setHomePageCallbabacks(){
  16. // Enable infinite scrolling down the results page.
  17. $(window).scroll(function(){
  18. if($(window).scrollTop() + $(window).height() == $(document).height() &&
  19. resultsDiv.querySelectorAll(".result").length > 0)
  20. loadMoreResults();
  21. });
  22. // Toggle the advanced-search form's visibility.
  23. advancedSearchButton.click(function(){
  24. var searchField = $("div#search-field");
  25. if(!advancedSearchDiv.hasClass("visible")){
  26. searchField.addClass("partly-visible");
  27. advancedSearchDiv.fadeIn(500).addClass("visible");
  28. advancedSearchButton.addClass("clicked");
  29. }
  30. else {
  31. advancedSearchDiv.fadeOut(300).removeClass("visible");
  32. advancedSearchButton.removeClass("clicked");
  33. if($("div#results .result").length == 0)
  34. searchField.removeClass("partly-visible");
  35. }
  36. });
  37. // Enable capturing the `enter` key.
  38. $("form#search-bar").submit(function(event){
  39. event.preventDefault();
  40. return false;
  41. });
  42. searchBar.onkeyup = typingTimer;
  43. }());
  44. /*
  45. * Set keyboard shortcut mappings.
  46. */
  47. (function resultsHotkeys(){
  48. /*
  49. * If the currently viewed result is not the first, scroll to the previous
  50. * result.
  51. */
  52. var previousResult = function(){
  53. var currResult = $(".display-all");
  54. if(currResult.length) {
  55. currResult.removeClass('display-all');
  56. currResult = currResult.closest(".result").prev(".result");
  57. } else {
  58. currResult = $(document.querySelectorAll('.result')[0]);
  59. }
  60. currResult.addClass('display-all');
  61. currResult.each(function(){
  62. $('html,body').stop().animate({
  63. scrollTop: $(this).offset().top - (
  64. $(window).height() - $(this).outerHeight(true)) / 2
  65. }, 140);
  66. });
  67. };
  68. /*
  69. * If the currently viewed result is not the last, scroll to the next
  70. * result.
  71. */
  72. var nextResult = function(){
  73. var currResult = $(".display-all");
  74. if(currResult.length) {
  75. currResult.removeClass('display-all');
  76. currResult = currResult.closest(".result").next(".result");
  77. } else {
  78. currResult = $(document.querySelectorAll('.result')[0]);
  79. }
  80. currResult.addClass('display-all');
  81. currResult.each(function(){
  82. $('html,body').stop().animate({
  83. scrollTop: $(this).offset().top - (
  84. $(window).height() - $(this).outerHeight(true)) / 2
  85. }, 140);
  86. });
  87. };
  88. var hotkeyActions = {
  89. "k" : previousResult,
  90. "j" : nextResult,
  91. "h" : previousSymbolMatch,
  92. "l" : nextSymbolMatch
  93. };
  94. $(window).keypress(function(key){
  95. for(var hotkey in hotkeyActions){
  96. var keyChar = String.fromCharCode(key.keyCode);
  97. console.log(keyChar);
  98. if(keyChar == hotkey)
  99. hotkeyActions[keyChar]();
  100. }
  101. });
  102. }());
  103. //Obtained by parsing python file with pygments
  104. 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>'
  105. searchBar.onkeyup = typingTimer;
  106. var testCodelet = {
  107. 'url': 'https://github.com/earwig/bitshift/blob/develop/app.py',
  108. 'filename': 'app.py',
  109. 'language': 'python',
  110. 'date_created': 'May 10, 2014',
  111. 'date_modified': '2 days ago',
  112. 'origin': ['GitHub', 'https://github.com', ''],
  113. 'authors': ['sevko', 'earwig'],
  114. 'html_code': codeExample
  115. };
  116. // Enable infinite scrolling down the results page.
  117. $(window).scroll(function() {
  118. var searchField = $("div#search-field");
  119. if($(window).scrollTop() + $(window).height() == $(document).height() &&
  120. searchField.hasClass('partly-visible')){
  121. loadMoreResults();
  122. }
  123. });
  124. /*
  125. * Clear the existing timer and set a new one the the user types text into the
  126. * search bar.
  127. */
  128. function typingTimer(event){
  129. clearTimeout(typingTimer);
  130. var enterKeyCode = 13;
  131. if(event.keyCode != enterKeyCode){
  132. if(lastValue != searchBar.value)
  133. typingTimer = setTimeout(finishedTyping, FINISH_TYPING_INTERVAL);
  134. }
  135. else {
  136. event.preventDefault();
  137. finishedTyping();
  138. return false;
  139. }
  140. };
  141. /*
  142. * Callback which queries the server whenver the user stops typing.
  143. *
  144. * Whenever the user doesn't type for a `FINISH_TYPING_INTERVAL` after having
  145. * entered new text in the search bar, send the current query request to the
  146. * server.
  147. */
  148. function finishedTyping(){
  149. lastValue = searchBar.value;
  150. var searchField = $("div#search-field");
  151. clearResults();
  152. if(searchBar.value){
  153. searchField.addClass("partly-visible");
  154. populateResults();
  155. }
  156. else {
  157. searchField.removeClass("partly-visible");
  158. $("div#advanced-search").fadeOut(50);
  159. advancedSearchButton.removeClass("clicked");
  160. }
  161. }
  162. /*
  163. * Removes any child elements of `div#results`.
  164. */
  165. function clearResults(){
  166. while(resultsDiv.firstChild)
  167. resultsDiv.removeChild(resultsDiv.firstChild);
  168. }
  169. /*
  170. * Query the server with the current search string, and populate `div#results`
  171. * with its response.
  172. */
  173. function populateResults(){
  174. searchResultsPage = 1;
  175. var results = queryServer();
  176. for(var result = 0; result < results.length; result++){
  177. var newDiv = results[result];
  178. resultsDiv.appendChild(newDiv);
  179. setTimeout(
  180. (function(divReference){
  181. return function(){
  182. divReference.classList.add("cascade");
  183. };
  184. }(newDiv)), result * 20);
  185. }
  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.filename + '</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.language + '</span>';
  235. dateModified.innerHTML = 'Last modified: <span>' + codelet.date_modified + '</span>';
  236. // Needs to be changed from int to string on the server
  237. dateCreated.innerHTML = 'Created: <span>' + codelet.date_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.html_code + '</div>';
  248. //Event binding
  249. $(newDiv).hover(function(e) {
  250. $(this).addClass('display-all');
  251. });
  252. $(newDiv).on('transitionend', function(e) {
  253. $(this).on('mouseleave', function(e) {
  254. $(this).removeClass('display-all');
  255. });
  256. });
  257. $(nextMatch).click(function(e) {
  258. e.stopPropagation();
  259. e.preventDefault();
  260. nextSymbolMatch();
  261. });
  262. $(prevMatch).click(function(e) {
  263. e.stopPropagation();
  264. e.preventDefault();
  265. previousSymbolMatch();
  266. });
  267. //Finish and append elements to parent elements
  268. hiddenInfo.appendChild(dateCreated);
  269. hiddenInfo.appendChild(dateModified);
  270. hiddenInfo.appendChild(language);
  271. hiddenInfo.appendChild(authors);
  272. hiddenInfoContainer.appendChild(hiddenInfo);
  273. row.appendChild(codeElt);
  274. row.appendChild(hiddenInfoContainer);
  275. table.appendChild(row);
  276. displayInfo.appendChild(site);
  277. displayInfo.appendChild(title);
  278. cycle.appendChild(prevMatch);
  279. cycle.appendChild(nextMatch);
  280. newDiv.appendChild(displayInfo);
  281. newDiv.appendChild(table);
  282. return newDiv;
  283. }
  284. function previousSymbolMatch() {
  285. var currResult = $(".display-all"),
  286. currMatch = currResult.find(".hll.current"),
  287. matches = currResult.find(".hll"),
  288. scrollDiv = currResult.find('#tablecontainer');
  289. if (currMatch.length == 0)
  290. currMatch = matches[0];
  291. else
  292. currMatch.removeClass('current');
  293. var index = matches.index(currMatch.get(0)) - 1;
  294. index = index <= 0 ? matches.length - 1 : index;
  295. var newMatch = $(matches[index]);
  296. scrollDiv.scrollTop(scrollDiv.scrollTop()
  297. - scrollDiv.height() / 2
  298. + newMatch.position().top + newMatch.height() / 2);
  299. newMatch.effect("highlight", {}, 750)
  300. newMatch.addClass('current');
  301. };
  302. function nextSymbolMatch() {
  303. var currResult = $(".display-all"),
  304. currMatch = currResult.find(".hll.current"),
  305. matches = currResult.find(".hll"),
  306. scrollDiv = currResult.find('#tablecontainer');
  307. if (currMatch.length == 0)
  308. currMatch = $(matches[0]);
  309. else
  310. currMatch.removeClass('current');
  311. var index = matches.index(currMatch.get(0)) + 1;
  312. index = index >= matches.length ? 0 : index;
  313. var newMatch = $(matches[index]);
  314. scrollDiv.scrollTop(scrollDiv.scrollTop()
  315. - scrollDiv.height() / 2
  316. + newMatch.position().top + newMatch.height() / 2);
  317. newMatch.effect("highlight", {}, 750);
  318. newMatch.addClass('current');
  319. };
  320. /*
  321. * AJAX the current query string to the server, and return its response.
  322. *
  323. * @return {Array} The server's response in the form of `div.result` DOM
  324. * elements, to fill `div#results`.
  325. */
  326. function queryServer(){
  327. var queryUrl = document.URL + "search.json?" + $.param({
  328. "q" : searchBar.value,
  329. "p" : searchResultsPage++
  330. });
  331. console.log(queryUrl);
  332. var result = $.getJSON(queryUrl, function(result){
  333. $.each(result, function(key, value){
  334. if(key == "error")
  335. errorMessage(value);
  336. else
  337. console.log("Success.");
  338. });
  339. });
  340. // return [];
  341. var resultDivs = [];
  342. for(var result = 0; result < 20; result++){
  343. var newDiv = createResult(testCodelet);
  344. resultDivs.push(newDiv)
  345. }
  346. return resultDivs;
  347. }
  348. /*
  349. * Adds more results to `div#results`.
  350. */
  351. function loadMoreResults(){
  352. var results = queryServer();
  353. for(var result = 0; result < results.length; result++){
  354. var newDiv = results[result];
  355. resultsDiv.appendChild(newDiv);
  356. setTimeout(
  357. (function(divReference){
  358. return function(){
  359. divReference.classList.add("cascade");
  360. };
  361. }(newDiv)),
  362. result * 20);
  363. }
  364. }
  365. /*
  366. * Displays a warning message in the UI.
  367. *
  368. * @param msg (str) The message string.
  369. */
  370. function errorMessage(msg){
  371. alert(msg);
  372. }
  373. loadMoreResults();