-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsetidle.js
352 lines (291 loc) · 9.66 KB
/
setidle.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
/*****************************
setidle
v0.3.2
MIT license
*****************************/
(function () {
var _detectedModuleType;
if (typeof define === 'function' && define.amd) {
_detectedModuleType = 'RequireJS';
}
else if (typeof module === 'object' && module.exports) {
_detectedModuleType = 'CommonJS';
}
else if (typeof window !== 'undefined') {
_detectedModuleType = 'Browser';
}
else {
throw 'Error: No browser or module system detected!';
}
var SetIdle = {};
/**
* The default idle configuration.
*/
var defaultConfig = {
/**
* How long to wait for event silence before declaring the application as idle.
*/
interval: 3000,
/**
* A list of events to use in order to determine when the system is in use.
*/
events: [
// The user is interacting with the page.
'change',
'click',
'dblclick',
'scroll',
'touchstart',
'touchend',
// watch for indications that the browser is having to re-paint the page.
'resize',
'mutated' // this is a virtual event, we're using MutationObserver under the hood.
]
};
/**
* Pre-configured observers that can be passed into the constructor.
*/
var defaultDOMObservers = {
/**
* Observes DOM mutation events.
*/
mutated: {
/**
* Starts the given observer.
* @param element The element to monitor.
* @param callback The callback to register.
* @returns {MutationObserver} The mutation observer.
*/
on: function (element, callback) {
var observer = new MutationObserver(callback);
observer.observe(element, {
childList: true, attributes: true, attributeOldValue: false, characterData: false,
subtree: true, characterDataOldValue: false, attributeFilter: [] });
return observer;
},
/**
* Stops the given observer.
* @param observer {MutationObserver} The mutation observer to stop.
*/
off: function (observer) {
observer.disconnect();
}
}
};
/**
* @private
* @instance
* Registers an observer with the emitter.
* @param observer
* @param name
* @param element
*/
function registerObserver(observer, name, element) {
this["_on" + name] = []; // set up event handler list.
this._observerNames.push(name); // store event names.
// initialize the observer and handle registered events when the callback is triggered.
this["_" + name] = observer.on(element, function () {
// iterate through and call the registered event handlers.
for (var i = 0; i < this["_on" + name].length; i++) {
this["_on" + name][i]();
}
}.bind(this));
}
/**
* An event emitter wrapper for DOM events.
* This is helpful so that SetIdle only cares about working with event emitters in general.
* @param [element] The element to monitor for events. The default is the document object.
* @param [observers] A list of observers to register for supporting virtual DOM events.
* @constructor
*/
function DOMEventEmitter (element, observers) {
element = element || window.document;
/**
* Retrieves the HTML element being wrapped.
* @returns The HTML element being wrapped.
*/
this.getElement = function () { return element; };
observers = observers || {
mutated: defaultDOMObservers.mutated
};
this._observerNames = [];
this._observers = observers;
// iterate through the given observers...
for (var observer in observers) {
if (observers.hasOwnProperty(observer)) {
registerObserver.call(this, observers[observer], observer, element);
}
}
}
/**
* Pre-configured observers that can be passed into the constructor.
*/
DOMEventEmitter.observers = defaultDOMObservers;
/**
* Disconnects all running observers.
*/
DOMEventEmitter.prototype.disconnect = function () {
// iterate through the observers...
for (var i = 0; i < this._observerNames.length; i++) {
// call the off handler for the observer type.
var observer = this['_' + this._observerNames[i]];
if (observer) {
this._observers[this._observerNames[i]].off(observer);
}
}
};
/**
* Called when an event is registered.
* @param event {string} The event to register.
* @param fn {function} The event listener to register.
*/
DOMEventEmitter.prototype.on = function (event, fn) {
if (this._observerNames.indexOf(event) >= 0) {
this["_on" + event].push(fn);
}
else {
this.getElement()
.addEventListener(event, fn, false);
}
};
/**
* Called when an event is removed.
* @param event {string} The event to remove.
* @param fn {function} The event listener to remove.
*/
DOMEventEmitter.prototype.off = function (event, fn) {
if (this._observerNames.indexOf(event) >= 0) {
// get the event handlers array for the event.
var handlers = this["_on" + event],
index = handlers.indexOf(fn);
// remove the given function from the list.
if (index >= 0) {
handlers.splice(index, 1);
}
}
else {
this.getElement()
.removeEventListener(event, fn);
}
};
/**
* Monitors and reports on whether the given event emitted is idle.
* @param emitter An event emitter. Expects a NodeJS-style EventEmitter instance. For DOM events, use SetIdle.DOMEventEmitter.
* @constructor
*/
var SetIdle = function SetIdle(emitter) {
/**
* Retrieves the emitter being monitored.
* @returns The emitter being monitored.
*/
this.getEmitter = function () { return emitter; };
};
SetIdle.DOMEventEmitter = DOMEventEmitter;
/**
* Starts the event monitoring if not started yet.
* @param fnIdle A callback for when the application is idle.
* @param fnActive A callback for when the application is active.
* @param [config] A configuration object.
*/
SetIdle.prototype.start = function (fnIdle, fnActive, config) {
// use the default configuration if none is provided.
config = config || defaultConfig;
this._config = config;
this._eventHandlers = this._eventHandlers || [];
var prevTimeout = null;
/**
* Handles the event by resetting the idle timer.
*/
function handleEvent() {
// clear the previously running timeout.
if (prevTimeout) {
clearTimeout(prevTimeout);
prevTimeout = null;
}
// if there was no running timeout, then report that the application has become active.
else if (fnActive && typeof fnActive === 'function') {
fnActive();
}
// start a new timeout counter. If it completes, then run the idle callback.
prevTimeout = setTimeout(function () {
if (fnIdle && typeof fnIdle === 'function') {
fnIdle();
}
prevTimeout = null;
}, config.interval);
}
var events = this.getEmitter(),
eventOn = (events.on || events.addListener);
if (!eventOn || typeof eventOn !== 'function') {
throw 'The provided event emitter does not implement on() or addListener().';
}
eventOn = eventOn.bind(events);
// register the handler for all events to be monitored.
for (var i = 0; i < config.events.length; i++) {
eventOn(config.events[i], handleEvent);
}
this._eventHandlers.push(handleEvent);
};
/**
* Stops all event monitoring.
*/
SetIdle.prototype.stop = function () {
var i, j,
events = this.getEmitter(),
eventOff = (events.off || events.removeListener);
if (!eventOff || typeof eventOff !== 'function') {
throw 'The provided event emitter does not implement off() or removeListener().';
}
eventOff = eventOff.bind(events);
for (i = 0; i < this._config.events.length; i++) {
for (j = 0; j < this._eventHandlers.length; j++) {
eventOff(this._config.events[i], this._eventHandlers[j]);
}
}
};
/**
* Monitors the DOM and reports when an application is either idle or active.
* @param fnIdle {function} A callback for when the application is idle.
* @param [fnActive] {function} A callback for when the application is active.
* @param [interval] {number} The number of milliseconds to wait until the application is considered idle. The default is 2,000 milliseconds.
* @returns {SetIdle} An instance of the SetIdle class which allows for stopping and starting the event monitoring.
*/
function setIdle(fnIdle, fnActive, interval) {
// if the second callback is left out...
if (!interval && fnActive && typeof fnActive !== 'function' && !isNaN(fnActive) && isFinite(fnActive)) {
interval = fnActive;
}
interval = interval || defaultConfig.interval;
var idle = new SetIdle(new SetIdle.DOMEventEmitter());
idle.start(fnIdle, fnActive, {
interval: interval,
events: defaultConfig.events
});
return idle;
}
/**
* Stops setIdle monitoring.
* @param idle An instance of the SetIdle class returned by setIdle().
*/
function clearIdle(idle) {
idle.stop();
}
// make the simple functions available to everyone.
SetIdle.setIdle = setIdle;
SetIdle.clearIdle = clearIdle;
if (typeof _detectedModuleType !== 'undefined' && _detectedModuleType === 'Browser') {
window.setIdle = setIdle;
window.clearIdle = clearIdle;
}
switch (_detectedModuleType) {
case 'RequireJS':
define(['SetIdle'], SetIdle);
break;
case 'CommonJS':
module.exports = SetIdle;
break;
case 'Browser':
window.SetIdle = SetIdle;
break;
}
})();