learn.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import _ from 'lodash'
  2. import App from '../base'
  3. import '../directives/mathjax'
  4. import '../services/algolia-search'
  5. App.controller(
  6. 'SearchWikiController',
  7. function ($scope, algoliaSearch, $modal) {
  8. $scope.hits = []
  9. $scope.hits_total = 0
  10. $scope.config_hits_per_page = 20
  11. $scope.processingSearch = false
  12. $scope.clearSearchText = function () {
  13. $scope.searchQueryText = ''
  14. updateHits([])
  15. }
  16. $scope.safeApply = function (fn) {
  17. const phase = $scope.$root.$$phase
  18. if (phase === '$apply' || phase === '$digest') {
  19. $scope.$eval(fn)
  20. } else {
  21. $scope.$apply(fn)
  22. }
  23. }
  24. const buildHitViewModel = function (hit) {
  25. const pagePath = hit.kb ? 'how-to/' : 'latex/'
  26. const pageSlug = encodeURIComponent(hit.pageName.replace(/\s/g, '_'))
  27. let sectionUnderscored = ''
  28. if (hit.sectionName && hit.sectionName !== '') {
  29. sectionUnderscored = '#' + hit.sectionName.replace(/\s/g, '_')
  30. }
  31. const section = hit._highlightResult.sectionName
  32. let pageName = hit._highlightResult.pageName.value
  33. if (section && section.value && section !== '') {
  34. pageName += ' - ' + section.value
  35. }
  36. let content = hit._highlightResult.content.value
  37. // Replace many new lines
  38. content = content.replace(/\n\n+/g, '\n\n')
  39. const lines = content.split('\n')
  40. // Only show the lines that have a highlighted match
  41. const matchingLines = []
  42. for (const line of lines) {
  43. if (!/^\[edit\]/.test(line)) {
  44. content += line + '\n'
  45. if (/<em>/.test(line)) {
  46. matchingLines.push(line)
  47. }
  48. }
  49. }
  50. content = matchingLines.join('\n...\n')
  51. const result = {
  52. name: pageName,
  53. url: `/learn/${pagePath}${pageSlug}${sectionUnderscored}`,
  54. content,
  55. }
  56. return result
  57. }
  58. var updateHits = (hits, hitsTotal = 0) => {
  59. $scope.safeApply(() => {
  60. $scope.hits = hits
  61. $scope.hits_total = hitsTotal
  62. })
  63. }
  64. $scope.search = function () {
  65. $scope.processingSearch = true
  66. const query = $scope.searchQueryText
  67. if (!query || query.length === 0) {
  68. updateHits([])
  69. return
  70. }
  71. algoliaSearch.searchWiki(
  72. query,
  73. {
  74. hitsPerPage: $scope.config_hits_per_page,
  75. },
  76. function (err, response) {
  77. $scope.processingSearch = false
  78. if (response.hits.length === 0) {
  79. updateHits([])
  80. } else {
  81. const hits = _.map(response.hits, buildHitViewModel)
  82. updateHits(hits, response.nbHits)
  83. }
  84. }
  85. )
  86. }
  87. }
  88. )
  89. export default App.controller('LearnController', function () {})