diff --git a/notifiers/notificationcenter.js b/notifiers/notificationcenter.js index 87ce072..28b12d9 100644 --- a/notifiers/notificationcenter.js +++ b/notifiers/notificationcenter.js @@ -21,12 +21,23 @@ function NotificationCenter(options) { return new NotificationCenter(options); } this.options = options; + this.notifications = []; EventEmitter.call(this); } util.inherits(NotificationCenter, EventEmitter); var activeId = null; +/** + * Call this to cancel timeouts on current notifications + */ +NotificationCenter.prototype.clearAll = function() { + for (var i in this.notifications) { + this.notifications[i].kill(); + } + this.notifications = []; +}; + function noop() {} NotificationCenter.prototype.notify = function(options, callback) { var fallbackNotifier; @@ -75,11 +86,19 @@ NotificationCenter.prototype.notify = function(options, callback) { var argsList = utils.constructArgumentList(options); if (utils.isMountainLion()) { - utils.fileCommandJson( + // This will be the index of the newly added notification once its been + // added + var index = this.notifications.length; + var p = utils.fileCommandJson( this.options.customPath || notifier, argsList, - actionJackedCallback + function(e, data) { + // delete the notification since its been cleared + this.notifications.splice(index, 1); + actionJackedCallback(e, data); + }.bind(this) ); + this.notifications.push(p); return this; } diff --git a/test/terminal-notifier.js b/test/terminal-notifier.js index 17a1f2c..6474277 100644 --- a/test/terminal-notifier.js +++ b/test/terminal-notifier.js @@ -308,4 +308,42 @@ describe('terminal-notifier', function() { }); }); }); + + describe('#clearAll()', function() { + var mockProcess = { + kill: jest.fn() + }; + beforeEach(function() { + // reset mock for each test + mockProcess.kill = jest.fn(); + utils.fileCommandJson = function() { + return mockProcess; + }; + }); + + afterEach(function() { + utils.fileCommandJson = originalUtils; + }); + + it('should kill all terminal-notifier processes', function() { + notifier.notify({ message: 'Hello World' }, function() {}); + notifier.clearAll(); + expect(mockProcess.kill.mock.calls.length).toBe(1); + }); + + it('should not kill finished terminal-notifier processes', function(done) { + utils.fileCommandJson = function(n, o, cb) { + setTimeout(function() { + cb(null, ''); + // After the callback the notification will be cleared. + // Calling `clearAll` should be a no-op + notifier.clearAll(); + expect(mockProcess.kill.mock.calls.length).toBe(0); + done(); + }, 0); + return mockProcess; + }; + notifier.notify({ message: 'Hello World' }, function() {}); + }); + }); });