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.

преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
преди 10 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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.hide().removeClass("visible");
  40. advancedSearchButton.removeClass("clicked");
  41. if($("div#results .result").length == 0)
  42. searchField.removeClass("partly-visible");
  43. clearResults();
  44. }
  45. });
  46. // Enable capturing the `enter` key.
  47. $("form#search-bar").submit(function(event){
  48. event.preventDefault();
  49. return false;
  50. });
  51. searchBar.onkeyup = typingTimer;
  52. }());
  53. /*
  54. * Set keyboard shortcut mappings.
  55. */
  56. (function resultsHotkeys(){
  57. /*
  58. * If the currently viewed result is not the first, scroll to the previous
  59. * result.
  60. */
  61. var previousResult = function(){
  62. var currResult = $(".display-all");
  63. if(currResult.length) {
  64. currResult.removeClass("display-all");
  65. currResult = currResult.closest(".result").prev(".result");
  66. } else {
  67. currResult = $(document.querySelectorAll(".result")[0]);
  68. }
  69. currResult.addClass("display-all");
  70. currResult.each(function(){
  71. $('html,body').stop().animate({
  72. scrollTop: $(this).offset().top - (
  73. $(window).height() - $(this).outerHeight(true)) / 2
  74. }, 140);
  75. });
  76. };
  77. /*
  78. * If the currently viewed result is not the last, scroll to the next
  79. * result.
  80. */
  81. var nextResult = function(){
  82. var currResult = $(".display-all");
  83. if(currResult.length) {
  84. currResult.removeClass("display-all");
  85. currResult = currResult.closest(".result").next(".result");
  86. } else {
  87. currResult = $(document.querySelectorAll(".result")[0]);
  88. }
  89. currResult.addClass('display-all');
  90. currResult.each(function(){
  91. $('html,body').stop().animate({
  92. scrollTop: $(this).offset().top - (
  93. $(window).height() - $(this).outerHeight(true)) / 2
  94. }, 140);
  95. });
  96. };
  97. var displayHotkeyHelp = function(){
  98. var help = $("div#hotkey-help");
  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">deaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabug</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. 'lang': 'python',
  128. 'created': 'May 10, 2014 aaaaaaaaaa',
  129. 'modified': '2 days ago',
  130. 'origin': ['GitHub', 'https://github.com', ''],
  131. 'authors': ['sevko', 'earwig', 'another author', 'a'],
  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. clearResults();
  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. * Create a result element based upon a codelet instance.
  190. *
  191. * @return {Element} The result element.
  192. */
  193. function createResult(codelet) {
  194. var maxAttributeLength = 20;
  195. //Level 1
  196. var newDiv = document.createElement("div"),
  197. table = document.createElement("table"),
  198. row = document.createElement("tr");
  199. //Level 2
  200. var displayInfo = document.createElement("div"),
  201. codeElt = document.createElement("td"),
  202. hiddenInfoContainer = document.createElement("td"),
  203. hiddenInfo = document.createElement("div"),
  204. cycle = document.createElement("div");
  205. //Level 3
  206. var title = document.createElement("span"),
  207. site = document.createElement("span"),
  208. nextMatch = document.createElement("a"),
  209. prevMatch = document.createElement("a"),
  210. dateModified = document.createElement("div"),
  211. language = document.createElement("div"),
  212. dateCreated = document.createElement("div"),
  213. authors = document.createElement("div");
  214. //Classes and ID's
  215. newDiv.classList.add('result');
  216. displayInfo.id = 'display-info';
  217. codeElt.id = 'code';
  218. hiddenInfo.id = 'hidden-info';
  219. cycle.id = 'cycle-matches'
  220. title.id = 'title';
  221. site.id = 'site';
  222. nextMatch.id = 'next-match';
  223. nextMatch.href = '#';
  224. prevMatch.id = 'prev-match';
  225. prevMatch.href = '#';
  226. dateModified.id = 'date-modified';
  227. language.id = 'language';
  228. dateCreated.id = 'date-created';
  229. authors.id = 'authors';
  230. //Add the bulk of the html
  231. title.innerHTML = ' &raquo; <a href="' + codelet.url + '">'
  232. + codelet.name + '</a>';
  233. site.innerHTML = '<a href="' + codelet.origin[1] + '">' +
  234. codelet.origin[0] +'</a>';
  235. nextMatch.innerHTML = 'next match';
  236. prevMatch.innerHTML = 'prev match';
  237. language.innerHTML = 'Language: <span>' + codelet.lang + '</span>';
  238. dateModified.innerHTML = 'Last modified: <span>' + codelet.modified +
  239. '</span>';
  240. // Needs to be changed from int to string on the server
  241. dateCreated.innerHTML = 'Created: <span>' +
  242. codelet.created.substring(0, maxAttributeLength) + '</span>';
  243. var authorsHtml = 'Authors: <span>';
  244. var currLength = 0;
  245. var authorsList = [];
  246. for(var auth = 0; auth < codelet.authors.length; auth++){
  247. currLength += codelet.authors[auth].length;
  248. if(maxAttributeLength < currLength){
  249. authorsList.push("...");
  250. break;
  251. }
  252. else
  253. authorsList.push('<a href=#>' + codelet.authors[auth] + '</a>');
  254. }
  255. authors.innerHTML = "Authors: <span>" + authorsList.join(", ") + "</span>";
  256. // Needs to be processed on the server
  257. codeElt.innerHTML = '<div id=tablecontainer>' + codelet.code + '</div>';
  258. //Event binding
  259. $(newDiv).on('mousemove', function(e) {
  260. var holdCondition = $('.disable-hover');
  261. if(holdCondition.length == 0) {
  262. $(this).siblings().removeClass('display-all');
  263. $(this).addClass('display-all');
  264. }
  265. });
  266. $(newDiv).on('mouseleave', function(e) {
  267. var holdCondition = $('.disable-hover');
  268. if(holdCondition.length == 0)
  269. $(this).removeClass('display-all');
  270. });
  271. $(nextMatch).click(function(e) {
  272. e.stopPropagation();
  273. e.preventDefault();
  274. nextSymbolMatch();
  275. });
  276. $(prevMatch).click(function(e) {
  277. e.stopPropagation();
  278. e.preventDefault();
  279. previousSymbolMatch();
  280. });
  281. //Finish and append elements to parent elements
  282. hiddenInfo.appendChild(dateCreated);
  283. hiddenInfo.appendChild(dateModified);
  284. hiddenInfo.appendChild(language);
  285. hiddenInfo.appendChild(authors);
  286. hiddenInfoContainer.appendChild(hiddenInfo);
  287. row.appendChild(codeElt);
  288. row.appendChild(hiddenInfoContainer);
  289. table.appendChild(row);
  290. displayInfo.appendChild(site);
  291. displayInfo.appendChild(title);
  292. cycle.appendChild(prevMatch);
  293. cycle.appendChild(nextMatch);
  294. newDiv.appendChild(displayInfo);
  295. newDiv.appendChild(table);
  296. return newDiv;
  297. }
  298. function previousSymbolMatch() {
  299. var currResult = $(".display-all"),
  300. currMatch = currResult.find(".hll.current"),
  301. matches = currResult.find(".hll"),
  302. scrollDiv = currResult.find("#tablecontainer");
  303. if (currMatch.length == 0)
  304. currMatch = matches[0];
  305. else
  306. currMatch.removeClass('current');
  307. var index = matches.index(currMatch.get(0)) - 1;
  308. index = index <= 0 ? matches.length - 1 : index;
  309. var newMatch = $(matches[index]);
  310. scrollDiv.scrollTop(scrollDiv.scrollTop()
  311. - scrollDiv.height() / 2
  312. + newMatch.position().top + newMatch.height() / 2);
  313. newMatch.effect("highlight", {color: '#FFF'}, 750)
  314. newMatch.addClass('current');
  315. };
  316. function nextSymbolMatch() {
  317. var currResult = $(".display-all"),
  318. currMatch = currResult.find(".hll.current"),
  319. matches = currResult.find(".hll"),
  320. scrollDiv = currResult.find("#tablecontainer");
  321. if (currMatch.length == 0)
  322. currMatch = $(matches[0]);
  323. else
  324. currMatch.removeClass("current");
  325. var index = matches.index(currMatch.get(0)) + 1;
  326. index = index >= matches.length ? 0 : index;
  327. var newMatch = $(matches[index]);
  328. scrollDiv.scrollTop(scrollDiv.scrollTop()
  329. - scrollDiv.height() / 2
  330. + newMatch.position().top + newMatch.height() / 2);
  331. newMatch.effect("highlight", {color: "#FFF"}, 750)
  332. newMatch.addClass("current");
  333. };
  334. /*
  335. * AJAX the current query string to the server, and return its response.
  336. *
  337. * @return {Array} The server's response in the form of `div.result` DOM
  338. * elements, to fill `div#results`.
  339. */
  340. function queryServer(){
  341. var queryUrl = document.URL + "search.json?" + $.param({
  342. "q" : searchBar.value,
  343. "p" : searchResultsPage++
  344. });
  345. var results = $.Deferred();
  346. $.getJSON(queryUrl, function(result){
  347. var resultDivs = [];
  348. if("error" in result)
  349. insertErrorMessage(result["error"]);
  350. else if(result["results"].length == 0 && searchResultsPage == 1)
  351. insertErrorMessage("No search results.");
  352. else
  353. for(var codelet = 0; codelet < result["results"].length; codelet++)
  354. resultDivs.push(createResult(result["results"][codelet]));
  355. results.resolve(resultDivs);
  356. });
  357. return results;
  358. }
  359. /*
  360. * Query the server with the current search string, and populate `div#results`
  361. * with its response.
  362. */
  363. function populateResults(){
  364. searchResultsPage = 1;
  365. loadMoreResults();
  366. }
  367. /*
  368. * Query the server for the next results page, and add its codelets to
  369. * `div#results`.
  370. */
  371. function loadMoreResults(){
  372. queryServer().done(function(results){
  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. /*
  387. * Displays a warning message in the UI.
  388. *
  389. * @param msg (str) The message string.
  390. */
  391. function insertErrorMessage(msg){
  392. var error = $(
  393. [
  394. "<div id='error'><span id='s1'>Error</span> ",
  395. "<span id='s2'>&raquo;</span> </div>"
  396. ].join(""));
  397. error.append(msg);
  398. resultsDiv.appendChild(error[0]);
  399. }