This repository has been archived by the owner on Aug 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
75 lines (65 loc) · 2.15 KB
/
index.js
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
73
74
75
var $ = require('jquery')
var Mustache = require('mustache')
function AnnotationPoller (opts) {
this.pollInterval = opts.pollInterval || 3000
this.pkg = opts.pkg // what package should we load annotations for?
this.endpoint = '/api/v1/annotations/' + this.pkg
this.annotations = {}
this.template = '<li id="annotation-{{id}}" style="{{status}}" data-fingerprint={{fingerprint}}><span>{{description}}</span><a href="{{{external-link}}}">{{external-link-text}}</a></li>'
this.addonSelector = '#npm-addon-box'
}
AnnotationPoller.prototype.start = function (loaded) {
var _this = this
var updating = false
$(document).ready(function () {
this.interval = setInterval(function () {
if (updating) return
updating = true
_this.getAnnotations(function () {
updating = false
_this.renderAnnotations()
if (loaded) {
loaded()
loaded = null
}
})
}, this.pollInterval)
})
}
AnnotationPoller.prototype.stop = function () {
clearInterval(this.interval)
}
AnnotationPoller.prototype.getAnnotations = function (cb) {
var _this = this
$.getJSON(this.endpoint, function (data) {
$.each(data, function (i, annotation) {
_this.annotations[annotation.id] = annotation
})
return cb()
})
}
AnnotationPoller.prototype.renderAnnotations = function () {
var _this = this
var annotation = null
var annotationElement = null
var newAnnotationElement = null
var addonBox = $(this.addonSelector)
Object.keys(this.annotations).forEach(function (key) {
annotation = _this.annotations[key]
if (annotation._rendered) return
annotationElement = $('#annotation-' + annotation.id)
newAnnotationElement = Mustache.render(_this.template, annotation)
if (annotationElement.length) {
// don't render the element unless its fingerprint has changed.
if (annotationElement.data('fingerprint') !== annotation.fingerprint) {
annotationElement.replaceWith(newAnnotationElement)
}
} else {
addonBox.append(newAnnotationElement)
}
annotation._rendered = true
})
}
module.exports = function (opts) {
return new AnnotationPoller(opts)
}