A semantic search engine for source code https://bitshift.benkurtovic.com/
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

459 lines
18 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. searchBar.onkeyup = typingTimer;
  125. var testCodelet = {
  126. 'url': 'https://github.com/earwig/bitshift/blob/develop/app.py',
  127. 'filename': 'app.py',
  128. 'language': 'python',
  129. 'date_created': 'May 10, 2014',
  130. 'date_modified': '2 days ago',
  131. 'origin': ['GitHub', 'https://github.com', ''],
  132. 'authors': ['sevko', 'earwig'],
  133. 'html_code': codeExample
  134. };
  135. // Enable infinite scrolling down the results page.
  136. $(window).scroll(function() {
  137. var searchField = $("div#search-field");
  138. if($(window).scrollTop() + $(window).height() == $(document).height() &&
  139. searchField.hasClass('partly-visible')){
  140. loadMoreResults();
  141. }
  142. });
  143. /*
  144. * Clear the existing timer and set a new one the the user types text into the
  145. * search bar.
  146. */
  147. function typingTimer(event){
  148. clearTimeout(typingTimer);
  149. var enterKeyCode = 13;
  150. if(event.keyCode != enterKeyCode){
  151. if(lastValue != searchBar.value)
  152. typingTimer = setTimeout(finishedTyping, FINISH_TYPING_INTERVAL);
  153. }
  154. else {
  155. event.preventDefault();
  156. finishedTyping();
  157. return false;
  158. }
  159. };
  160. /*
  161. * Callback which queries the server whenver the user stops typing.
  162. *
  163. * Whenever the user doesn't type for a `FINISH_TYPING_INTERVAL` after having
  164. * entered new text in the search bar, send the current query request to the
  165. * server.
  166. */
  167. function finishedTyping(){
  168. lastValue = searchBar.value;
  169. var searchField = $("div#search-field");
  170. clearResults();
  171. if(searchBar.value){
  172. searchField.addClass("partly-visible");
  173. populateResults();
  174. }
  175. else {
  176. searchField.removeClass("partly-visible");
  177. $("div#advanced-search").fadeOut(50);
  178. advancedSearchButton.removeClass("clicked");
  179. }
  180. }
  181. /*
  182. * Removes any child elements of `div#results`.
  183. */
  184. function clearResults(){
  185. while(resultsDiv.firstChild)
  186. resultsDiv.removeChild(resultsDiv.firstChild);
  187. }
  188. /*
  189. * Query the server with the current search string, and populate `div#results`
  190. * with its response.
  191. */
  192. function populateResults(){
  193. searchResultsPage = 1;
  194. var results = queryServer();
  195. for(var result = 0; result < results.length; result++){
  196. var newDiv = results[result];
  197. resultsDiv.appendChild(newDiv);
  198. setTimeout(
  199. (function(divReference){
  200. return function(){
  201. divReference.classList.add("cascade");
  202. };
  203. }(newDiv)), result * 20);
  204. }
  205. }
  206. /*
  207. * Create a result element based upon a codelet instance.
  208. *
  209. * @return {Element} The result element.
  210. */
  211. function createResult(codelet) {
  212. //Level 1
  213. var newDiv = document.createElement("div"),
  214. table = document.createElement("table"),
  215. row = document.createElement("tr");
  216. //Level 2
  217. var displayInfo = document.createElement("div"),
  218. codeElt = document.createElement("td"),
  219. hiddenInfoContainer = document.createElement("td"),
  220. hiddenInfo = document.createElement("div"),
  221. cycle = document.createElement("div");
  222. //Level 3
  223. var title = document.createElement("span"),
  224. site = document.createElement("span"),
  225. nextMatch = document.createElement("a"),
  226. prevMatch = document.createElement("a"),
  227. dateModified = document.createElement("div"),
  228. language = document.createElement("div"),
  229. dateCreated = document.createElement("div"),
  230. authors = document.createElement("div");
  231. //Classes and ID's
  232. newDiv.classList.add('result');
  233. displayInfo.id = 'display-info';
  234. codeElt.id = 'code';
  235. hiddenInfo.id = 'hidden-info';
  236. cycle.id = 'cycle-matches'
  237. title.id = 'title';
  238. site.id = 'site';
  239. nextMatch.id = 'next-match';
  240. nextMatch.href = '#';
  241. prevMatch.id = 'prev-match';
  242. prevMatch.href = '#';
  243. dateModified.id = 'date-modified';
  244. language.id = 'language';
  245. dateCreated.id = 'date-created';
  246. authors.id = 'authors';
  247. //Add the bulk of the html
  248. title.innerHTML = ' &raquo; <a href="' + codelet.url + '">'
  249. + codelet.filename + '</a>';
  250. site.innerHTML = '<a href="' + codelet.origin[1] + '">' + codelet.origin[0] +'</a>';
  251. nextMatch.innerHTML = 'next match';
  252. prevMatch.innerHTML = 'prev match';
  253. language.innerHTML = 'Language: <span>' + codelet.language + '</span>';
  254. dateModified.innerHTML = 'Last modified: <span>' + codelet.date_modified + '</span>';
  255. // Needs to be changed from int to string on the server
  256. dateCreated.innerHTML = 'Created: <span>' + codelet.date_created + '</span>';
  257. var authorsHtml = 'Authors: <span>';
  258. codelet.authors.forEach(function(a, i) {
  259. if (i == codelet.authors.length - 1)
  260. authorsHtml += '<a href=#>' + a + ' </a>';
  261. else
  262. authorsHtml += '<a href=#>' + a + ' </a>, ';
  263. });
  264. authors.innerHTML = authorsHtml;
  265. // Needs to be processed on the server
  266. codeElt.innerHTML = '<div id=tablecontainer>' + codelet.html_code + '</div>';
  267. //Event binding
  268. $(newDiv).on('mousemove', function(e) {
  269. var holdCondition = $('.disable-hover');
  270. if(holdCondition.length == 0) {
  271. $(this).siblings().removeClass('display-all');
  272. $(this).addClass('display-all');
  273. }
  274. });
  275. $(newDiv).on('mouseleave', function(e) {
  276. var holdCondition = $('.disable-hover');
  277. if(holdCondition.length == 0)
  278. $(this).removeClass('display-all');
  279. });
  280. $(nextMatch).click(function(e) {
  281. e.stopPropagation();
  282. e.preventDefault();
  283. nextSymbolMatch();
  284. });
  285. $(prevMatch).click(function(e) {
  286. e.stopPropagation();
  287. e.preventDefault();
  288. previousSymbolMatch();
  289. });
  290. //Finish and append elements to parent elements
  291. hiddenInfo.appendChild(dateCreated);
  292. hiddenInfo.appendChild(dateModified);
  293. hiddenInfo.appendChild(language);
  294. hiddenInfo.appendChild(authors);
  295. hiddenInfoContainer.appendChild(hiddenInfo);
  296. row.appendChild(codeElt);
  297. row.appendChild(hiddenInfoContainer);
  298. table.appendChild(row);
  299. displayInfo.appendChild(site);
  300. displayInfo.appendChild(title);
  301. cycle.appendChild(prevMatch);
  302. cycle.appendChild(nextMatch);
  303. newDiv.appendChild(displayInfo);
  304. newDiv.appendChild(table);
  305. return newDiv;
  306. }
  307. function previousSymbolMatch() {
  308. var currResult = $(".display-all"),
  309. currMatch = currResult.find(".hll.current"),
  310. matches = currResult.find(".hll"),
  311. scrollDiv = currResult.find("#tablecontainer");
  312. if (currMatch.length == 0)
  313. currMatch = matches[0];
  314. else
  315. currMatch.removeClass('current');
  316. var index = matches.index(currMatch.get(0)) - 1;
  317. index = index <= 0 ? matches.length - 1 : index;
  318. var newMatch = $(matches[index]);
  319. scrollDiv.scrollTop(scrollDiv.scrollTop()
  320. - scrollDiv.height() / 2
  321. + newMatch.position().top + newMatch.height() / 2);
  322. newMatch.effect("highlight", {color: '#FFF'}, 750)
  323. newMatch.addClass('current');
  324. };
  325. function nextSymbolMatch() {
  326. var currResult = $(".display-all"),
  327. currMatch = currResult.find(".hll.current"),
  328. matches = currResult.find(".hll"),
  329. scrollDiv = currResult.find("#tablecontainer");
  330. if (currMatch.length == 0)
  331. currMatch = $(matches[0]);
  332. else
  333. currMatch.removeClass("current");
  334. var index = matches.index(currMatch.get(0)) + 1;
  335. index = index >= matches.length ? 0 : index;
  336. var newMatch = $(matches[index]);
  337. scrollDiv.scrollTop(scrollDiv.scrollTop()
  338. - scrollDiv.height() / 2
  339. + newMatch.position().top + newMatch.height() / 2);
  340. newMatch.effect("highlight", {color: "#FFF"}, 750)
  341. newMatch.addClass("current");
  342. };
  343. /*
  344. * AJAX the current query string to the server, and return its response.
  345. *
  346. * @return {Array} The server's response in the form of `div.result` DOM
  347. * elements, to fill `div#results`.
  348. */
  349. function queryServer(){
  350. var queryUrl = document.URL + "search.json?" + $.param({
  351. "q" : searchBar.value,
  352. "p" : searchResultsPage++
  353. });
  354. var resultDivs = [];
  355. $.getJSON(queryUrl, function(result){
  356. if("error" in result)
  357. insertErrorMessage(result["error"]);
  358. else
  359. for(var codelet = 0; codelet < result["results"].length; codelet++)
  360. resultDivs.push(result["results"][codelet]);
  361. });
  362. for(var result = 0; result < 20; result++){
  363. var newDiv = createResult(testCodelet);
  364. resultDivs.push(newDiv)
  365. }
  366. return resultDivs;
  367. }
  368. /*
  369. * Adds more results to `div#results`.
  370. */
  371. function loadMoreResults(){
  372. var results = queryServer();
  373. for(var result = 0; result < results.length; result++){
  374. var newDiv = results[result];
  375. resultsDiv.appendChild(newDiv);
  376. setTimeout(
  377. (function(divReference){
  378. return function(){
  379. divReference.classList.add("cascade");
  380. };
  381. }(newDiv)),
  382. result * 20);
  383. }
  384. }
  385. /*
  386. * Displays a warning message in the UI.
  387. *
  388. * @param msg (str) The message string.
  389. */
  390. function insertErrorMessage(msg){
  391. var error = $("<div id='error'><span>Error: </span></div>");
  392. error.append(msg);
  393. resultsDiv.appendChild(error[0]);
  394. }
  395. // loadMoreResults();