search.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. require([
  2. 'gitbook',
  3. 'jquery'
  4. ], function(gitbook, $) {
  5. var MAX_RESULTS = 15;
  6. var MAX_DESCRIPTION_SIZE = 500;
  7. var usePushState = (typeof history.pushState !== 'undefined');
  8. // DOM Elements
  9. var $body = $('body');
  10. var $bookSearchResults;
  11. var $searchInput;
  12. var $searchList;
  13. var $searchTitle;
  14. var $searchResultsCount;
  15. var $searchQuery;
  16. // Throttle search
  17. function throttle(fn, wait) {
  18. var timeout;
  19. return function() {
  20. var ctx = this, args = arguments;
  21. if (!timeout) {
  22. timeout = setTimeout(function() {
  23. timeout = null;
  24. fn.apply(ctx, args);
  25. }, wait);
  26. }
  27. };
  28. }
  29. function displayResults(res) {
  30. $bookSearchResults.addClass('open');
  31. var noResults = res.count == 0;
  32. $bookSearchResults.toggleClass('no-results', noResults);
  33. // Clear old results
  34. $searchList.empty();
  35. // Display title for research
  36. $searchResultsCount.text(res.count);
  37. $searchQuery.text(res.query);
  38. // Create an <li> element for each result
  39. res.results.forEach(function(res) {
  40. var $li = $('<li>', {
  41. 'class': 'search-results-item'
  42. });
  43. var $title = $('<h3>');
  44. var $link = $('<a>', {
  45. 'href': gitbook.state.basePath + '/' + res.url,
  46. 'text': res.title
  47. });
  48. var content = res.body.trim();
  49. if (content.length > MAX_DESCRIPTION_SIZE) {
  50. content = content.slice(0, MAX_DESCRIPTION_SIZE).trim()+'...';
  51. }
  52. var $content = $('<p>').html(content);
  53. $link.appendTo($title);
  54. $title.appendTo($li);
  55. $content.appendTo($li);
  56. $li.appendTo($searchList);
  57. });
  58. }
  59. function launchSearch(q) {
  60. // Add class for loading
  61. $body.addClass('with-search');
  62. $body.addClass('search-loading');
  63. // Launch search query
  64. throttle(gitbook.search.query(q, 0, MAX_RESULTS)
  65. .then(function(results) {
  66. displayResults(results);
  67. })
  68. .always(function() {
  69. $body.removeClass('search-loading');
  70. }), 1000);
  71. }
  72. function closeSearch() {
  73. $body.removeClass('with-search');
  74. $bookSearchResults.removeClass('open');
  75. }
  76. function launchSearchFromQueryString() {
  77. var q = getParameterByName('q');
  78. if (q && q.length > 0) {
  79. // Update search input
  80. $searchInput.val(q);
  81. // Launch search
  82. launchSearch(q);
  83. }
  84. }
  85. function bindSearch() {
  86. // Bind DOM
  87. $searchInput = $('#book-search-input input');
  88. $bookSearchResults = $('#book-search-results');
  89. $searchList = $bookSearchResults.find('.search-results-list');
  90. $searchTitle = $bookSearchResults.find('.search-results-title');
  91. $searchResultsCount = $searchTitle.find('.search-results-count');
  92. $searchQuery = $searchTitle.find('.search-query');
  93. // Launch query based on input content
  94. function handleUpdate() {
  95. var q = $searchInput.val();
  96. if (q.length == 0) {
  97. closeSearch();
  98. }
  99. else {
  100. launchSearch(q);
  101. }
  102. }
  103. // Detect true content change in search input
  104. // Workaround for IE < 9
  105. var propertyChangeUnbound = false;
  106. $searchInput.on('propertychange', function(e) {
  107. if (e.originalEvent.propertyName == 'value') {
  108. handleUpdate();
  109. }
  110. });
  111. // HTML5 (IE9 & others)
  112. $searchInput.on('input', function(e) {
  113. // Unbind propertychange event for IE9+
  114. if (!propertyChangeUnbound) {
  115. $(this).unbind('propertychange');
  116. propertyChangeUnbound = true;
  117. }
  118. handleUpdate();
  119. });
  120. // Push to history on blur
  121. $searchInput.on('blur', function(e) {
  122. // Update history state
  123. if (usePushState) {
  124. var uri = updateQueryString('q', $(this).val());
  125. history.pushState({ path: uri }, null, uri);
  126. }
  127. });
  128. }
  129. gitbook.events.on('page.change', function() {
  130. bindSearch();
  131. closeSearch();
  132. // Launch search based on query parameter
  133. if (gitbook.search.isInitialized()) {
  134. launchSearchFromQueryString();
  135. }
  136. });
  137. gitbook.events.on('search.ready', function() {
  138. bindSearch();
  139. // Launch search from query param at start
  140. launchSearchFromQueryString();
  141. });
  142. function getParameterByName(name) {
  143. var url = window.location.href;
  144. name = name.replace(/[\[\]]/g, '\\$&');
  145. var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)', 'i'),
  146. results = regex.exec(url);
  147. if (!results) return null;
  148. if (!results[2]) return '';
  149. return decodeURIComponent(results[2].replace(/\+/g, ' '));
  150. }
  151. function updateQueryString(key, value) {
  152. value = encodeURIComponent(value);
  153. var url = window.location.href;
  154. var re = new RegExp('([?&])' + key + '=.*?(&|#|$)(.*)', 'gi'),
  155. hash;
  156. if (re.test(url)) {
  157. if (typeof value !== 'undefined' && value !== null)
  158. return url.replace(re, '$1' + key + '=' + value + '$2$3');
  159. else {
  160. hash = url.split('#');
  161. url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
  162. if (typeof hash[1] !== 'undefined' && hash[1] !== null)
  163. url += '#' + hash[1];
  164. return url;
  165. }
  166. }
  167. else {
  168. if (typeof value !== 'undefined' && value !== null) {
  169. var separator = url.indexOf('?') !== -1 ? '&' : '?';
  170. hash = url.split('#');
  171. url = hash[0] + separator + key + '=' + value;
  172. if (typeof hash[1] !== 'undefined' && hash[1] !== null)
  173. url += '#' + hash[1];
  174. return url;
  175. }
  176. else
  177. return url;
  178. }
  179. }
  180. });