-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (61 loc) · 1.85 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
var nanoid = require("nanoid")
function defaultTemplate(notifyOpts) {
return (
'<div class="apicase-notify-title">' +
notifyOpts.title +
"</div>" +
'<div class="apicase-notify-body">' +
notifyOpts.body +
"</div>"
)
}
function createNotify(pluginOpts, notifyOpts) {
if (!document || !document.querySelector) return
var elem = document.createElement("div")
elem.id = nanoid(5)
elem.classList.add("apicase-notify")
elem.innerHTML = (pluginOpts.template || defaultTemplate)(notifyOpts)
elem.dataset["closeDelay"] = pluginOpts.closeDelay || 0
document.querySelector(pluginOpts.el || "#apicase-notifies").appendChild(elem)
return elem.id
}
function withNotify(notifyType, cb) {
return function(ctx) {
if (!ctx.meta.notify || !ctx.meta.notify.pending)
return ctx.next(ctx.payload)
var notifyData = ctx.meta.notify[notifyType](ctx)
var notifyId = createNotify(opts, {
type: notifyType,
title: notifyData.title,
body: notifyData.body
})
return cb(ctx, notifyId, notifyData)
}
}
module.exports = function notifyPlugin(opts) {
return function(service) {
return service.extend({
hooks: {
before: withNotify("pending", function(ctx, id) {
ctx.next(ctx.payload).then(() => {
var el = document.getElementById(id)
var remove = () => el.parentNode.removeChild(el)
if (el) {
if (+el.dataset["closeDelay"] === 0) remove()
else {
el.classList.add("apicase-notify-closing")
setTimeout(remove, +el.dataset["closeDelay"])
}
}
})
}),
done: withNotify("done", function(ctx) {
return ctx.next(ctx.result)
}),
fail: withNotify("fail", function(ctx) {
return ctx.next(ctx.result)
})
}
})
}
}