search.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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': 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(target) {
  108. // Asynchronously load the index data
  109. {
  110. var url = state.basePath + "/assets/search_plus_index.json";
  111. $.getJSON(url).then(function(data) {
  112. INDEX_DATA = data;
  113. handleUpdate();
  114. });
  115. }
  116. // Bind DOM
  117. var $body = $('body');
  118. // Launch query based on input content
  119. function handleUpdate() {
  120. var $searchInput = $(target);
  121. var keyword = $searchInput.val();
  122. if (keyword === undefined || keyword.length == 0) {
  123. closeSearch();
  124. } else {
  125. launchSearch(keyword);
  126. }
  127. }
  128. $body.on('keyup', target, function(e) {
  129. if (e.keyCode === 13) {
  130. if (usePushState) {
  131. var uri = updateQueryString('q', $(this).val());
  132. history.pushState({
  133. path: uri
  134. }, null, uri);
  135. }
  136. }
  137. handleUpdate();
  138. });
  139. $body.on('click', target, function(e) {
  140. if (Object.keys(INDEX_DATA).length === 0) {
  141. var url = state.basePath + "/assets/search_plus_index.json";
  142. $.getJSON(url).then(function(data) {
  143. INDEX_DATA = data;
  144. handleUpdate();
  145. });
  146. }
  147. });
  148. // Push to history on blur
  149. $body.on('blur', target, function(e) {
  150. // Update history state
  151. if (usePushState) {
  152. var uri = updateQueryString('q', $(this).val());
  153. history.pushState({
  154. path: uri
  155. }, null, uri);
  156. }
  157. });
  158. }
  159. gitbook.events.on('start', function() {
  160. bindSearch('#book-search-input input');
  161. bindSearch('#book-search-input-inside input');
  162. showResult();
  163. closeSearch();
  164. });
  165. // 高亮文本
  166. var highLightPageInner = function(keyword) {
  167. $('.page-inner').mark(keyword, {
  168. 'ignoreJoiners': true,
  169. 'acrossElements': true,
  170. 'separateWordSearch': false
  171. });
  172. setTimeout(function() {
  173. var mark = $('mark[data-markjs="true"]');
  174. if (mark.length) {
  175. mark[0].scrollIntoView();
  176. }
  177. }, 100);
  178. };
  179. function showResult() {
  180. var keyword, type;
  181. if (/\b(q|h)=([^&]+)/.test(location.search)) {
  182. type = RegExp.$1;
  183. keyword = decodeURIComponent(RegExp.$2);
  184. if (type === 'q') {
  185. launchSearch(keyword);
  186. } else {
  187. highLightPageInner(keyword);
  188. }
  189. $('#book-search-input input').val(keyword);
  190. $('#book-search-input-inside input').val(keyword);
  191. }
  192. }
  193. gitbook.events.on('page.change', showResult);
  194. function getParameterByName(name) {
  195. var url = window.location.href;
  196. name = name.replace(/[\[\]]/g, '\\$&');
  197. var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)', 'i'),
  198. results = regex.exec(url);
  199. if (!results) return null;
  200. if (!results[2]) return '';
  201. return decodeURIComponent(results[2].replace(/\+/g, ' '));
  202. }
  203. function updateQueryString(key, value) {
  204. value = encodeURIComponent(value);
  205. var url = window.location.href.replace(/([?&])(?:q|h)=([^&]+)(&|$)/, function(all, pre, value, end) {
  206. if (end === '&') {
  207. return pre;
  208. }
  209. return '';
  210. });
  211. var re = new RegExp('([?&])' + key + '=.*?(&|#|$)(.*)', 'gi'),
  212. hash;
  213. if (re.test(url)) {
  214. if (typeof value !== 'undefined' && value !== null)
  215. return url.replace(re, '$1' + key + '=' + value + '$2$3');
  216. else {
  217. hash = url.split('#');
  218. url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
  219. if (typeof hash[1] !== 'undefined' && hash[1] !== null)
  220. url += '#' + hash[1];
  221. return url;
  222. }
  223. } else {
  224. if (typeof value !== 'undefined' && value !== null) {
  225. var separator = url.indexOf('?') !== -1 ? '&' : '?';
  226. hash = url.split('#');
  227. url = hash[0] + separator + key + '=' + value;
  228. if (typeof hash[1] !== 'undefined' && hash[1] !== null)
  229. url += '#' + hash[1];
  230. return url;
  231. } else
  232. return url;
  233. }
  234. }
  235. window.addEventListener('click', function(e) {
  236. if (e.target.tagName === 'A' && e.target.getAttribute('data-need-reload')) {
  237. setTimeout(function() {
  238. location.reload();
  239. }, 100);
  240. }
  241. }, true);
  242. });