learn.coffee 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. define [
  2. "base"
  3. "directives/mathjax"
  4. "services/algolia-search"
  5. ], (App) ->
  6. App.controller "SearchWikiController", ($scope, algoliaSearch, _, $modal) ->
  7. $scope.hits = []
  8. $scope.clearSearchText = ->
  9. $scope.searchQueryText = ""
  10. updateHits []
  11. $scope.safeApply = (fn)->
  12. phase = $scope.$root.$$phase
  13. if(phase == '$apply' || phase == '$digest')
  14. $scope.$eval(fn)
  15. else
  16. $scope.$apply(fn)
  17. buildHitViewModel = (hit)->
  18. page_underscored = hit.pageName.replace(/\s/g,'_')
  19. section_underscored = hit.sectionName.replace(/\s/g,'_')
  20. content = hit._highlightResult.content.value
  21. # Replace many new lines
  22. content = content.replace(/\n\n+/g, "\n\n")
  23. lines = content.split("\n")
  24. # Only show the lines that have a highlighted match
  25. matching_lines = []
  26. for line in lines
  27. if !line.match(/^\[edit\]/)
  28. content += line + "\n"
  29. if line.match(/<em>/)
  30. matching_lines.push line
  31. content = matching_lines.join("\n...\n")
  32. result =
  33. name : hit._highlightResult.pageName.value + " - " + hit._highlightResult.sectionName.value
  34. url :"/learn/#{page_underscored}##{section_underscored}"
  35. content: content
  36. return result
  37. updateHits = (hits)->
  38. $scope.safeApply ->
  39. $scope.hits = hits
  40. $scope.search = ->
  41. query = $scope.searchQueryText
  42. if !query? or query.length == 0
  43. updateHits []
  44. return
  45. algoliaSearch.searchWiki query, (err, response)->
  46. if response.hits.length == 0
  47. updateHits []
  48. else
  49. hits = _.map response.hits, buildHitViewModel
  50. updateHits hits
  51. App.controller "LearnController", () ->