This repository has been archived by the owner on Jun 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
/
index.js
604 lines (547 loc) · 17.1 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
async = require('async'),
Promise = require('promise'),
gui = window.require('nw.gui')
// One animation at a time
var AnimationQueue = function(options) {
this.options = options
this.queue = []
this.running = false
}
AnimationQueue.prototype.push = function(object) {
if (this.running) {
this.queue.push(object)
}
else {
this.running = true
this.animate(object)
}
}
AnimationQueue.prototype.animate = function(object) {
var self = this
object.func.apply(null, object.args)
.then(function() {
if (self.queue.length > 0) {
// Run next animation
self.animate.call(self, self.queue.shift())
}
else {
self.running = false
}
})
.catch(function(err) {
log('nw-notify encountered an error!')
log('Please submit the error stack and code samples to: https://github.com/cgrossde/nw-notify/issues')
log(err.stack)
})
}
AnimationQueue.prototype.clear = function() {
this.queue = []
}
var config = {
width: 300,
height: 65,
padding: 10,
borderRadius: 5,
displayTime: 5000,
animationSteps: 5,
animationStepMs: 5,
animateInParallel: true,
appIcon: null,
pathToModule: '',
autoCleanup: true, // Auto cleanup
logging: true,
defaultStyleContainer: {
backgroundColor: '#f0f0f0',
overflow: 'hidden',
padding: 8,
border: '1px solid #CCC',
fontFamily: 'Arial',
fontSize: 12,
position: 'relative',
lineHeight: '15px'
},
defaultStyleAppIcon: {
overflow: 'hidden',
float: 'left',
height: 40,
width: 40,
marginRight: 10,
},
defaultStyleImage: {
overflow: 'hidden',
float: 'right',
height: 40,
width: 40,
marginLeft: 10,
},
defaultStyleClose: {
position: 'absolute',
top: 1,
right: 3,
fontSize: 11,
color: '#CCC'
},
defaultStyleText: {
margin: 0,
overflow: 'hidden',
cursor: 'default'
},
defaultWindow: {
'always-on-top': true,
'visible-on-all-workspaces': true,
'show_in_taskbar': process.platform == "darwin",
resizable: false,
show: false,
frame: false,
transparent: true,
toolbar: false
},
htmlTemplate: '<html>\n'
+ '<head></head>\n'
+ '<body style="overflow: hidden; -webkit-user-select: none;">\n'
+ '<div id="container">\n'
+ ' <img src="" id="appIcon" />\n'
+ ' <img src="" id="image" />\n'
+ ' <div id="text">\n'
+ ' <b id="title"></b>\n'
+ ' <p id="message"></p>\n'
+ ' </div>\n'
+ ' <div id="close">X</div>\n'
+ '</div>\n'
+ '</body>\n'
+ '</html>'
}
function setConfig(customConfig) {
config = _.defaults(customConfig, config)
calcDimensions()
}
// Little helper functions
function updateAppPath() {
// Get url of current page in nwjs
var pathToAppIndex = window.location.href
// Remove everything after '#'
var urlParts = pathToAppIndex.split('#')
pathToAppIndex = urlParts[0]
var pathSegemnts = pathToAppIndex.split('/')
// Remove last part (e.g. index.html of app)
pathSegemnts.pop()
config.appPath = pathSegemnts.join('/') + '/'
return config.appPath
}
function getAppPath() {
if (config.appPath === undefined) {
return updateAppPath()
}
return config.appPath
}
function updateTemplatePath() {
var scriptPath = path.join(__dirname, 'notification.html')
// Tricky stuff, sometimes this doesn't work,
// especially when webpack is involved.
// Check if we have a file at that location
try {
fs.statSync(scriptPath).isFile()
}
// No file => create our own temporary notification.html
catch (err) {
log('nw-notify: Could not find template ("' + scriptPath + '"). Fallback to writing my own template file.')
log('nw-notify: To use a different template you need to correct the config.templatePath or simply adapt config.htmlTemplate')
// Fallback to config.htmlTemplate: Place text
// in file within working path and use that
scriptPath = path.join(path.resolve(path.dirname()), 'notification.html')
try {
fs.writeFileSync(scriptPath, config.htmlTemplate)
}
// Failed to write file
catch (e) {
log('nw-notify: Failed writing my own file. nw-notify will not work.', e, e.stack)
}
}
config.templatePath = 'file://' + scriptPath
return config.templatePath
}
function getTemplatePath() {
if (config.templatePath === undefined) {
return updateTemplatePath()
}
return config.templatePath
}
function setTemplatePath(path) {
config.templatePath = path
}
var nextInsertPos = {}
function calcDimensions() {
// Calc totalHeight & totalWidth
config.totalHeight = config.height + config.padding
config.totalWidth = config.width + config.padding
// Calc pos of first notification:
config.firstPos = {
x: config.lowerRightCorner.x - config.totalWidth,
y: config.lowerRightCorner.y - config.totalHeight
}
// Set nextInsertPos
nextInsertPos.x = config.firstPos.x
nextInsertPos.y = config.firstPos.y
}
// Init screen to gather some information
gui.Screen.Init()
var screens = gui.Screen.screens
// Use first screen only
var cur_screen = screens[0]
// detect primary screen if more than 1 screen
if (screens.length > 0) {
for (var i=0; j=screens.length,i<j; i++){
if (screens[i].bounds.x === 0 && screens[i].bounds.y === 0) {
cur_screen = screens[i]
}
}
}
// Display notifications starting from lower right corner
// Calc lower right corner
config.lowerRightCorner = {}
config.lowerRightCorner.x = cur_screen.bounds.x + cur_screen.work_area.x + cur_screen.work_area.width
config.lowerRightCorner.y = cur_screen.bounds.y + cur_screen.work_area.y + cur_screen.work_area.height
calcDimensions()
// Maximum amount of Notifications we can show:
config.maxVisibleNotifications = Math.floor(cur_screen.work_area.height / (config.totalHeight))
config.maxVisibleNotifications = (config.maxVisibleNotifications > 7) ? 7 : config.maxVisibleNotifications
// Array of windows with currently showing notifications
var activeNotifications = []
// Recycle windows
var inactiveWindows = []
// If we cannot show all notifications, queue them
var notificationQueue = []
// To prevent executing mutliple animations at once
var animationQueue = new AnimationQueue()
// Give each notification a unique id
var latestID = 0
function notify(notification) {
// Is it an object and only one argument?
if (arguments.length === 1 && typeof notification === 'object') {
// Use object instead of supplied parameters
notification.id = latestID
latestID++
animationQueue.push({
func: showNotification,
args: [ notification ]
})
return notification.id
}
else {
// Since 1.0.0 all notification parameters need to be passed
// as object.
log('nw-notify: ERROR since version 1.0.0 notify() only accepts a single object with notification parameters. The use of notify(title, text, ...) was deprecated and removed.')
}
}
function showNotification(notificationObj) {
return new Promise(function(resolve, reject) {
// Can we show it?
if (activeNotifications.length < config.maxVisibleNotifications) {
// Get inactiveWindow or create new:
getWindow().then(function(notificationWindow) {
// Move window to position
calcInsertPos()
notificationWindow.moveTo(nextInsertPos.x, nextInsertPos.y)
// Add to activeNotifications
activeNotifications.push(notificationWindow)
// Close notification function
var closeNotification = function closeNotification(event) {
if (notificationObj.closed) {
//console.log('Already closed')
return new Promise(function(exitEarly) { exitEarly() })
}
else {
notificationObj.closed = true
}
if (notificationObj.onCloseFunc) {
notificationObj.onCloseFunc({
event: event,
id: notificationObj.id
})
}
// Remove event listener
var newContainer = container.cloneNode(true)
container.parentNode.replaceChild(newContainer, container)
clearTimeout(closeTimeout)
var newCloseButton = closeButton.cloneNode(true)
closeButton.parentNode.replaceChild(newCloseButton, closeButton)
// Recycle window
var pos = activeNotifications.indexOf(notificationWindow)
activeNotifications.splice(pos, 1)
inactiveWindows.push(notificationWindow)
// Hide notification
notificationWindow.hide()
checkForQueuedNotifications()
// Move notifications down
return moveOneDown(pos)
}
// Always add to animationQueue to prevent erros (e.g. notification
// got closed while it was moving will produce an error)
var closeNotificationSafely = function(reason) {
if (reason === undefined)
reason = 'closedByAPI'
animationQueue.push({
func: closeNotification,
args: [ reason ]
})
}
// Display time per notification basis.
var displayTime = (notificationObj.displayTime ? notificationObj.displayTime : config.displayTime);
// Set timeout to hide notification
var closeTimeout = setTimeout(function() {
closeNotificationSafely('timeout')
}, displayTime)
// Close button
var notiDoc = notificationWindow.window.document
var closeButton = notiDoc.getElementById('close')
closeButton.addEventListener('click',function(event) {
event.stopPropagation()
closeNotificationSafely('close')
})
// URL
var container = notiDoc.getElementById('container')
if (notificationObj.url || notificationObj.onClickFunc) {
container.addEventListener('click', function() {
if (notificationObj.url) {
gui.Shell.openExternal(notificationObj.url)
}
if (notificationObj.onClickFunc) {
notificationObj.onClickFunc({
event: 'click',
id: notificationObj.id,
closeNotification: closeNotificationSafely
})
}
})
}
// Set contents, ...
setNotficationContents(notiDoc, notificationObj)
// Show window
notificationWindow.show()
// Trigger onShowFunc if existent
if (notificationObj.onShowFunc) {
notificationObj.onShowFunc({
event: 'show',
id: notificationObj.id,
closeNotification: closeNotificationSafely
})
}
resolve(notificationWindow)
})
}
// Add to notificationQueue
else {
notificationQueue.push(notificationObj)
resolve()
}
})
}
function setNotficationContents(notiDoc, notificationObj) {
// sound
if (notificationObj.sound) {
// Check if file is accessible
try {
// If it's a local file, check it's existence
// Won't check remote files e.g. http://
if (notificationObj.sound.match(/^file\:/) !== null
|| notificationObj.sound.match(/^\//) !== null) {
fs.statSync(notificationObj.sound.replace('file://', '')).isFile()
}
var audio = new window.Audio(notificationObj.sound)
audio.play()
}
catch (e) {
log('nw-notify: ERROR could not find sound file: ' + notificationObj.sound.replace('file://', ''), e, e.stack)
}
}
// Title
var titleDoc = notiDoc.getElementById('title')
titleDoc.innerHTML = notificationObj.title || ''
// message
var messageDoc = notiDoc.getElementById('message')
messageDoc.innerHTML = notificationObj.text || ''
// Image
var imageDoc = notiDoc.getElementById('image')
if (notificationObj.image) {
imageDoc.src = notificationObj.image
}
else {
setStyleOnDomElement({ display: 'none'}, imageDoc)
}
}
/**
* Checks for queued notifications and add them
* to AnimationQueue if possible
*/
function checkForQueuedNotifications() {
if (notificationQueue.length > 0 &&
(activeNotifications.length < config.maxVisibleNotifications)) {
// Add new notification to animationQueue
animationQueue.push({
func: showNotification,
args: [ notificationQueue.shift() ]
})
}
}
/**
* Moves the notifications one position down,
* starting with notification at startPos
*
* @param {int} startPos
*/
function moveOneDown(startPos) {
return new Promise(function(resolve, reject) {
if (startPos >= activeNotifications || startPos === -1) {
resolve()
return
}
// Build array with index of affected notifications
var notificationPosArray = []
for (var i = startPos; i < activeNotifications.length; i++) {
notificationPosArray.push(i)
}
// Start to animate all notifications at once or in parallel
var asyncFunc = async.map // Best performance
if (config.animateInParallel === false) {
asyncFunc = async.mapSeries // Sluggish
}
asyncFunc(notificationPosArray, moveNotificationAnimation, function() {
resolve()
})
})
}
function moveNotificationAnimation(i, done) {
// Get notification to move
var notification = activeNotifications[i]
// Calc new y position
var newY = config.lowerRightCorner.y - config.totalHeight * (i + 1)
// Get startPos, calc step size and start animationInterval
var startY = notification.y
var step = (newY-startY)/config.animationSteps
var curStep = 1
var animationInterval = setInterval(function() {
// Abort condition
if (curStep === config.animationSteps) {
notification.moveTo(config.firstPos.x, newY)
clearInterval(animationInterval)
return done(null, 'done')
}
// Move one step down
notification.moveTo(config.firstPos.x, startY + curStep * step)
curStep++
}, config.animationStepMs)
}
/**
* Find next possible insert position (on top)
*/
function calcInsertPos() {
if (activeNotifications.length < config.maxVisibleNotifications) {
nextInsertPos.y = config.lowerRightCorner.y - config.totalHeight * (activeNotifications.length + 1)
}
}
/**
* Get a window to display a notification. Use inactiveWindows or
* create a new window
* @return {Window}
*/
function getWindow() {
return new Promise(function(resolve, reject) {
var notificationWindow
// Are there still inactiveWindows?
if (inactiveWindows.length > 0) {
notificationWindow = inactiveWindows.pop()
resolve(notificationWindow)
}
// Or create a new window
else {
var windowProperties = config.defaultWindow
windowProperties.width = config.width
windowProperties.height = config.height
notificationWindow = gui.Window.open(getTemplatePath(), config.defaultWindow)
}
// Return once DOM is loaded
notificationWindow.on('loaded', function() {
// Style it
var notiDoc = notificationWindow.window.document
var container = notiDoc.getElementById('container')
var appIcon = notiDoc.getElementById('appIcon')
var image = notiDoc.getElementById('image')
var close = notiDoc.getElementById('close')
var message = notiDoc.getElementById('message')
// Default style
setStyleOnDomElement(config.defaultStyleContainer, container)
// Size and radius
var style = {
height: config.height - 2*config.borderRadius - 2*config.defaultStyleContainer.padding,
width: config.width - 2*config.borderRadius - 2*config.defaultStyleContainer.padding,
borderRadius: config.borderRadius + 'px'
}
setStyleOnDomElement(style, container)
// Style appIcon or hide
if (config.appIcon) {
setStyleOnDomElement(config.defaultStyleAppIcon, appIcon)
appIcon.src = config.appIcon
}
else {
setStyleOnDomElement({
display: 'none'
}, appIcon)
}
// Style image
setStyleOnDomElement(config.defaultStyleImage, image)
// Style close button
setStyleOnDomElement(config.defaultStyleClose, close)
// Remove margin from text p
setStyleOnDomElement(config.defaultStyleText, message)
// Done
resolve(notificationWindow)
})
})
}
function setStyleOnDomElement(styleObj, domElement){
try {
for (var styleAttr in styleObj){
domElement.style[styleAttr] = styleObj[styleAttr]
}
}
catch (e) {
throw new Error('nw-notify: Could not set style on domElement', styleObj, domElement)
}
}
function closeAll() {
// Clear out animation Queue and close windows
animationQueue.clear()
_.forEach(activeNotifications, function(window) {
window.close()
})
_.forEach(inactiveWindows, function(window) {
window.close()
})
// Reset certain vars
nextInsertPos = {}
activeNotifications = []
inactiveWindows = []
}
function log(){
if (config.logging === true){
console.log.apply(console, arguments)
}
}
/**
* Auto cleanup
*/
gui.Window.get().on('close', function() {
if (config.autoCleanup) {
closeAll()
gui.App.quit()
}
})
module.exports.notify = notify
module.exports.setConfig = setConfig
module.exports.getAppPath = getAppPath
module.exports.getTemplatePath = getTemplatePath
module.exports.setTemplatePath = setTemplatePath
module.exports.closeAll = closeAll