search.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 window.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. var 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] === window.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 escapeRegExp (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. keyword = keyword.toLowerCase()
  77. var results = []
  78. var index = -1
  79. for (var page in INDEX_DATA) {
  80. var store = INDEX_DATA[page]
  81. if (
  82. ~store.keywords.toLowerCase().indexOf(keyword) ||
  83. ~(index = store.body.toLowerCase().indexOf(keyword))
  84. ) {
  85. results.push({
  86. url: page,
  87. title: store.title,
  88. body: store.body.substr(Math.max(0, index - 50), MAX_DESCRIPTION_SIZE)
  89. .replace(/^[^\s,.]+./, '').replace(/(..*)[\s,.].*/, '$1') // prevent break word
  90. .replace(new RegExp('(' + escapeRegExp(keyword) + ')', 'gi'), '<span class="search-highlight-keyword">$1</span>')
  91. })
  92. }
  93. }
  94. displayResults({
  95. count: results.length,
  96. query: keyword,
  97. results: results
  98. })
  99. }
  100. function launchSearch (keyword) {
  101. // Add class for loading
  102. $body.addClass('with-search')
  103. $body.addClass('search-loading')
  104. function doSearch () {
  105. query(keyword)
  106. $body.removeClass('search-loading')
  107. }
  108. throttle(doSearch)()
  109. }
  110. function closeSearch () {
  111. $body.removeClass('with-search')
  112. $('#book-search-results').removeClass('open')
  113. }
  114. function bindSearch () {
  115. // Bind DOM
  116. var $body = $('body')
  117. // Launch query based on input content
  118. function handleUpdate () {
  119. var $searchInput = $('#book-search-input input')
  120. var keyword = $searchInput.val()
  121. if (keyword.length === 0) {
  122. closeSearch()
  123. } else {
  124. launchSearch(keyword)
  125. }
  126. }
  127. $body.on('keyup', '#book-search-input input', function (e) {
  128. if (e.keyCode === 13) {
  129. if (usePushState) {
  130. var uri = updateQueryString('q', $(this).val())
  131. window.history.pushState({
  132. path: uri
  133. }, null, uri)
  134. }
  135. }
  136. handleUpdate()
  137. })
  138. // Push to history on blur
  139. $body.on('blur', '#book-search-input input', function (e) {
  140. // Update history state
  141. if (usePushState) {
  142. var uri = updateQueryString('q', $(this).val())
  143. window.history.pushState({
  144. path: uri
  145. }, null, uri)
  146. }
  147. })
  148. }
  149. gitbook.events.on('start', function () {
  150. bindSearch()
  151. $.getJSON(state.basePath + '/search_plus_index.json').then(function (data) {
  152. INDEX_DATA = data
  153. showResult()
  154. closeSearch()
  155. })
  156. })
  157. // highlight
  158. var highLightPageInner = function (keyword) {
  159. $('.page-inner').mark(keyword, {
  160. 'ignoreJoiners': true,
  161. 'acrossElements': true,
  162. 'separateWordSearch': false
  163. })
  164. setTimeout(function () {
  165. var mark = $('mark[data-markjs="true"]')
  166. if (mark.length) {
  167. mark[0].scrollIntoView()
  168. }
  169. }, 100)
  170. }
  171. function showResult () {
  172. var keyword, type
  173. if (/\b(q|h)=([^&]+)/.test(window.location.search)) {
  174. type = RegExp.$1
  175. keyword = decodeURIComponent(RegExp.$2)
  176. if (type === 'q') {
  177. launchSearch(keyword)
  178. } else {
  179. highLightPageInner(keyword)
  180. }
  181. $('#book-search-input input').val(keyword)
  182. }
  183. }
  184. gitbook.events.on('page.change', showResult)
  185. function updateQueryString (key, value) {
  186. value = encodeURIComponent(value)
  187. var url = window.location.href.replace(/([?&])(?:q|h)=([^&]+)(&|$)/, function (all, pre, value, end) {
  188. if (end === '&') {
  189. return pre
  190. }
  191. return ''
  192. })
  193. var re = new RegExp('([?&])' + key + '=.*?(&|#|$)(.*)', 'gi')
  194. var hash
  195. if (re.test(url)) {
  196. if (typeof value !== 'undefined' && value !== null) { return url.replace(re, '$1' + key + '=' + value + '$2$3') } else {
  197. hash = url.split('#')
  198. url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '')
  199. if (typeof hash[1] !== 'undefined' && hash[1] !== null) { url += '#' + hash[1] }
  200. return url
  201. }
  202. } else {
  203. if (typeof value !== 'undefined' && value !== null) {
  204. var separator = url.indexOf('?') !== -1 ? '&' : '?'
  205. hash = url.split('#')
  206. url = hash[0] + separator + key + '=' + value
  207. if (typeof hash[1] !== 'undefined' && hash[1] !== null) { url += '#' + hash[1] }
  208. return url
  209. } else { return url }
  210. }
  211. }
  212. window.addEventListener('click', function (e) {
  213. if (e.target.tagName === 'A' && e.target.getAttribute('data-need-reload')) {
  214. setTimeout(function () {
  215. window.location.reload()
  216. }, 100)
  217. }
  218. }, true)
  219. })