search.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. require([
  2. 'gitbook',
  3. 'jquery'
  4. ], function(gitbook, $) {
  5. var MAX_DESCRIPTION_SIZE = 500;
  6. var state = gitbook.state;
  7. var INDEX_DATA = {};
  8. var usePushState = (typeof history.pushState !== 'undefined');
  9. // DOM Elements
  10. var $body = $('body');
  11. var $bookSearchResults;
  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,
  21. args = arguments;
  22. if (!timeout) {
  23. timeout = setTimeout(function() {
  24. timeout = null;
  25. fn.apply(ctx, args);
  26. }, wait);
  27. }
  28. };
  29. }
  30. function displayResults(res) {
  31. $bookSearchResults = $('#book-search-results');
  32. $searchList = $bookSearchResults.find('.search-results-list');
  33. $searchTitle = $bookSearchResults.find('.search-results-title');
  34. $searchResultsCount = $searchTitle.find('.search-results-count');
  35. $searchQuery = $searchTitle.find('.search-query');
  36. $bookSearchResults.addClass('open');
  37. var noResults = res.count == 0;
  38. $bookSearchResults.toggleClass('no-results', noResults);
  39. // Clear old results
  40. $searchList.empty();
  41. // Display title for research
  42. $searchResultsCount.text(res.count);
  43. $searchQuery.text(res.query);
  44. // Create an <li> element for each result
  45. res.results.forEach(function(item) {
  46. var $li = $('<li>', {
  47. 'class': 'search-results-item'
  48. });
  49. var $title = $('<h3>');
  50. var $link = $('<a>', {
  51. 'href': gitbook.state.basePath + '/' + item.url + '?h=' + encodeURIComponent(res.query),
  52. 'text': item.title,
  53. 'data-is-search': 1
  54. });
  55. if ($link[0].href.split('?')[0] === location.href.split('?')[0]) {
  56. $link[0].setAttribute('data-need-reload', 1);
  57. }
  58. var content = item.body.trim();
  59. if (content.length > MAX_DESCRIPTION_SIZE) {
  60. content = content + '...';
  61. }
  62. var $content = $('<p>').html(content);
  63. $link.appendTo($title);
  64. $title.appendTo($li);
  65. $content.appendTo($li);
  66. $li.appendTo($searchList);
  67. });
  68. $('.body-inner').scrollTop(0);
  69. }
  70. function escapeReg(keyword) {
  71. //escape regexp prevserve word
  72. return String(keyword).replace(/([\*\.\?\+\$\^\[\]\(\)\{\}\|\/\\])/g, '\\$1');
  73. }
  74. function query(keyword) {
  75. if (keyword == null || keyword.trim() === '') return;
  76. var results = [],
  77. index = -1;
  78. for (var page in INDEX_DATA) {
  79. if ((index = INDEX_DATA[page].body.toLowerCase().indexOf(keyword.toLowerCase())) !== -1) {
  80. results.push({
  81. url: page,
  82. title: INDEX_DATA[page].title,
  83. body: INDEX_DATA[page].body.substr(Math.max(0, index - 50), MAX_DESCRIPTION_SIZE).replace(new RegExp('(' + escapeReg(keyword) + ')', 'gi'), '<span class="search-highlight-keyword">$1</span>')
  84. });
  85. }
  86. }
  87. displayResults({
  88. count: results.length,
  89. query: keyword,
  90. results: results
  91. });
  92. }
  93. function launchSearch(keyword) {
  94. // Add class for loading
  95. $body.addClass('with-search');
  96. $body.addClass('search-loading');
  97. function doSearch() {
  98. query(keyword);
  99. $body.removeClass('search-loading');
  100. }
  101. throttle(doSearch)();
  102. }
  103. function closeSearch() {
  104. $body.removeClass('with-search');
  105. $('#book-search-results').removeClass('open');
  106. }
  107. function bindSearch() {
  108. // Bind DOM
  109. var $body = $('body');
  110. // Launch query based on input content
  111. function handleUpdate() {
  112. var $searchInput = $('#book-search-input input');
  113. var keyword = $searchInput.val();
  114. if (keyword.length == 0) {
  115. closeSearch();
  116. } else {
  117. launchSearch(keyword);
  118. }
  119. }
  120. $body.on('keyup', '#book-search-input input', function(e) {
  121. if (e.keyCode === 13) {
  122. if (usePushState) {
  123. var uri = updateQueryString('q', $(this).val());
  124. history.pushState({
  125. path: uri
  126. }, null, uri);
  127. }
  128. }
  129. handleUpdate();
  130. });
  131. // Push to history on blur
  132. $body.on('blur', '#book-search-input input', function(e) {
  133. // Update history state
  134. if (usePushState) {
  135. var uri = updateQueryString('q', $(this).val());
  136. history.pushState({
  137. path: uri
  138. }, null, uri);
  139. }
  140. });
  141. }
  142. gitbook.events.on('start', function() {
  143. bindSearch();
  144. $.getJSON(state.basePath + "/search_plus_index.json").then(function(data) {
  145. INDEX_DATA = data;
  146. showResult();
  147. closeSearch();
  148. });
  149. });
  150. // 高亮文本
  151. var highLightPageInner = function(keyword) {
  152. $('.page-inner').mark(keyword, {
  153. 'ignoreJoiners': true,
  154. 'acrossElements': true,
  155. 'separateWordSearch': false
  156. });
  157. setTimeout(function() {
  158. var mark = $('mark[data-markjs="true"]');
  159. if (mark.length) {
  160. mark[0].scrollIntoView();
  161. }
  162. }, 100);
  163. };
  164. function showResult() {
  165. var keyword, type;
  166. if (/\b(q|h)=([^&]+)/.test(location.search)) {
  167. type = RegExp.$1;
  168. keyword = decodeURIComponent(RegExp.$2);
  169. if (type === 'q') {
  170. launchSearch(keyword);
  171. } else {
  172. highLightPageInner(keyword);
  173. }
  174. $('#book-search-input input').val(keyword);
  175. }
  176. }
  177. gitbook.events.on('page.change', showResult);
  178. function getParameterByName(name) {
  179. var url = window.location.href;
  180. name = name.replace(/[\[\]]/g, '\\$&');
  181. var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)', 'i'),
  182. results = regex.exec(url);
  183. if (!results) return null;
  184. if (!results[2]) return '';
  185. return decodeURIComponent(results[2].replace(/\+/g, ' '));
  186. }
  187. function updateQueryString(key, value) {
  188. value = encodeURIComponent(value);
  189. var url = window.location.href.replace(/([?&])(?:q|h)=([^&]+)(&|$)/, function(all, pre, value, end) {
  190. if (end === '&') {
  191. return pre;
  192. }
  193. return '';
  194. });
  195. var re = new RegExp('([?&])' + key + '=.*?(&|#|$)(.*)', 'gi'),
  196. hash;
  197. if (re.test(url)) {
  198. if (typeof value !== 'undefined' && value !== null)
  199. return url.replace(re, '$1' + key + '=' + value + '$2$3');
  200. else {
  201. hash = url.split('#');
  202. url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
  203. if (typeof hash[1] !== 'undefined' && hash[1] !== null)
  204. url += '#' + hash[1];
  205. return url;
  206. }
  207. } else {
  208. if (typeof value !== 'undefined' && value !== null) {
  209. var separator = url.indexOf('?') !== -1 ? '&' : '?';
  210. hash = url.split('#');
  211. url = hash[0] + separator + key + '=' + value;
  212. if (typeof hash[1] !== 'undefined' && hash[1] !== null)
  213. url += '#' + hash[1];
  214. return url;
  215. } else
  216. return url;
  217. }
  218. }
  219. window.addEventListener('click', function(e) {
  220. if (e.target.tagName === 'A' && e.target.getAttribute('data-need-reload')) {
  221. setTimeout(function() {
  222. location.reload();
  223. }, 100);
  224. }
  225. }, true);
  226. });