learn.coffee 1.5 KB

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