summaryrefslogtreecommitdiff
path: root/public/assets/js/lib/views/search/results.js
blob: d01db969fc6615833e6bf5071f576a99758a8bbc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var SearchResults = View.extend({

  el: "#search",
  template: $("#search .template").html(),
  
  events: {
  },
  
  action: "/api/search",
  
  initialize: function(opt){
  },
  
  load: function(){
    var query = window.location.search.substr(1)
    if (! query || ! query.length) {
      $("#search").hide()
      return
    }
    $.get(this.action, query, this.populate.bind(this))
  },
  
  populate: function(res){
    var query = sanitize(res.meta.query)
    var terms = res.meta.terms
    console.log(res)
    $("[name=query]").val(query)
    this.$(".query").html(query)
    this.$(".total").html(parseInt(res.meta.total))
    var next_page = {
      query: res.meta.terms.join("+"),
      start: res.meta.start + res.meta.limit,
      limit: res.meta.limit,
    }
    this.$(".next_page").toggle(res.meta.start + res.meta.limit > res.meta.count)
    this.$(".next_page").attr("href", querystring(next_page))
    res.results.forEach((result) => {
      var image
      if (result.file && is_image(result.file.filename)) {
        image = result.file
      }
      else if (result.thread.flagged && is_image(result.thread.flagged.filename)) {
        image = result.thread.flagged
      }
      var image_path = image ? '/data/' + result.thread.id + '/' + sanitize(image.filename) : ''
      var file_tag = result.file ? '<a href="' + make_link(result.file) + '">' + bold_terms(sanitize(result.file.filename), terms) + '</a>' : ''
      var t = this.template
        .replace(/{{thread_id}}/g, sanitize("" + result.thread.id))
        .replace(/{{meta}}/, metadata(result.thread))
        .replace(/{{image}}/, image_path)
        .replace(/{{title}}/, bold_terms(sanitize(result.thread.title), terms))
        .replace(/{{comment}}/, result.comment ? bold_terms(sanitize(result.comment.comment), terms) : '')
        .replace(/{{file}}/, file_tag)
      this.$("#results").append(t)
    })
    $("body").removeClass('loading')
  },

})

function bold_terms (s, terms) {
  s = sanitize(s)
  terms.forEach( (term) => {
    s = s.replace(new RegExp(term, "ig"), "<b>" + term + "</b>")
  })
  return s
}
function querystring(opt){
  var s = Object.keys(opt).map((key) => {
    return encodeURIComponent(key) + "=" + encodeURIComponent(opt[key])
  }).join("&")
}