This repository has been archived by the owner on Apr 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathrx.winjs.js
619 lines (541 loc) · 25.2 KB
/
rx.winjs.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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
(function (root, factory) {
var freeExports = typeof exports == 'object' && exports,
freeModule = typeof module == 'object' && module && module.exports == freeExports && module,
freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal) {
window = freeGlobal;
}
// Because of build optimizers
if (typeof define === 'function' && define.amd) {
define(['rx', 'winjs', 'exports'], function (Rx, winjs, exports) {
root.Rx = factory(root, exports, Rx, winjs);
return root.Rx;
});
} else if (typeof module === 'object' && module && module.exports === freeExports) {
module.exports = factory(root, module.exports, require('rx'), require('winjs'));
} else {
root.Rx = factory(root, {}, root.Rx, root.WinJS);
}
}(this, function (global, exp, Rx, WinJS, undefined) { var freeExports = typeof exports == 'object' && exports,
freeModule = typeof module == 'object' && module && module.exports == freeExports && module,
freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal) {
window = freeGlobal;
}
var Rx = window.Rx,
Subject = Rx.Subject,
AsyncSubject = Rx.AsyncSubject,
Observer = Rx.Observer,
observerCreate = Observer.create,
Observable = Rx.Observable,
observableProto = Observable.prototype,
observableCreate = Observable.create,
observableCreateWithDisposable = Observable.createWithDisposable,
CompositeDisposable = Rx.CompositeDisposable,
disposableCreate = Rx.Disposable.create,
disposableEmpty = Rx.Disposable.empty,
Promise = WinJS.Promise,
Binding = WinJS.Binding;
Rx.WinJS = {};
function createEventListener(el, eventName, handler) {
var disposables = new CompositeDisposable();
function createListener(element, en, fn) {
element.addEventListener(en, fn, false);
return disposableCreate(function () {
element.removeEventListener(en, fn, false);
});
};
// Assume collection versus single
if (el && el.length) {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el[i], eventName, handler));
}
} else {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Binds an event to a given element or item. This supports either a single object or a collection.
*
* @param {Element|NodeList} element The element or object to bind the event to.
* @param {String} eventName The name of the event to bind to the given element
* @returns {Observable} An observable sequence which listens to the event on the given element or object
*/
Rx.WinJS.fromEvent = function (element, eventName) {
return observableCreateWithDisposable(function (observer) {
return createEventListener(element, eventName, observer.onNext.bind(observer));
}).publish().refCount();
};
/**
* Converts an existing WinJS Promise object to an observable sequence with an optional observer for progress.
* @param {Function|Observer} [observerOrOnNext] An optional Observer or onNext function to capture progress events.
* @returns {Observable} An observable sequence wrapping an existing WinJS Promise object.
*/
Promise.prototype.toObservable = function (observerOrOnNext) {
var subject = new AsyncSubject();
this.done(
function (next) {
subject.onNext(next);
subject.onCompleted();
},
subject.onError.bind(subject),
function (progress) {
if (typeof observerOrOnNext === 'function') {
observerOrOnNext(progress);
} else if (observerOrOnNext) {
observerOrOnNext.onNext(progress);
}
}
);
return subject.asObservable();
};
/**
* Converts an existing Observable to a WinJS Promise object.
* @returns {WinJS.Promise} A WinJS Promise object which encapsulates the given Observable sequence.
*/
observableProto.toPromise = function () {
var parent = this, subscription, value;
return new Promise(function (c, e) {
subscription = parent.subscribe(function (v) {
value = v;
}, function (exn) {
e(exn);
}, function () {
c(value);
});
}, function () {
if (subscription) { subscription.dispose(); }
});
};
/**
* Converts an existing WinJS Promise object to an observable sequence with an optional observer for progress.
* @param {WinJS.Promise} promise The Promise to convert to an Observable sequence.
* @param {Function|Observer} [observerOrOnNext] An optional Observer or onNext function to capture progress events.
* @returns {Observable} An observable sequence wrapping an existing WinJS Promise object.
*/
Promise.toObservable = function (promise, observerOrOnNext) {
return Promise.prototype.toObservable.call(promise, observerOrOnNext);
}; var originalAs = Binding.as;
function bindObservable(bindable, name) {
return observableCreate(function (observer) {
var handler = function (newValue, oldValue) {
observer.onNext({
name: name,
newValue: newValue,
oldValue: oldValue,
dataObject: bindable
});
};
bindable.bind(name, handler);
return function () {
bindable.unbind(name, handler);
};
});
}
/**
* Returns an observable object. This may be an observable proxy for the specified object, an existing proxy, or
* the specified object itself if it directly supports observability.
* This also adds a `toObservable` method which allows to turn the given binding object into an observable object.
*
* @param {Object} data Object to provide observability for.
*
* @returns {Observable} The observable object.
*/
Binding.as = function (data) {
var bindable = originalAs(data);
bindable.toObservable = function () {
if (arguments.length === 0) {
throw new Error('Must have at least one binding');
}
var observables = [];
for (var i = 0, len = arguments.length; i < len; i++) {
observables.push(bindObservable(bindable, arguments[i]));
}
return Observable.merge(observables);
};
return bindable;
};
if (window.MutationObserver) {
/**
* Creates an observable sequence from a Mutation Observer.
* MutationObserver provides developers a way to react to changes in a DOM.
* @example
* Rx.DOM.fromMutationObserver(document.getElementById('foo'), { attributes: true, childList: true, characterData: true });
*
* @param {Object} target The Node on which to obserave DOM mutations.
* @param {Object} options A MutationObserverInit object, specifies which DOM mutations should be reported.
* @returns {Observable} An observable sequence which contains mutations on the given DOM target.
*/
Rx.WinJS.fromMutationObserver = function (target, options) {
return observableCreate(function (observer) {
var mutationObserver = new MutationObserver(function (mutations) {
observer.onNext(mutations);
});
mutationObserver.observe(target, options);
return function () {
mutationObserver.disconnect();
};
});
};
}
/**
* Creates a WebSocket Subject with a given URL, protocol and an optional observer for the open event.
*
* @example
* var socket = Rx.DOM.fromWebSocket('http://localhost:8080', 'stock-protocol', function(e) { ... });
* var socket = Rx.DOM.fromWebSocket('http://localhost:8080', 'stock-protocol', observer);
*
* @param {String} url The URL of the WebSocket.
* @param {String} protocol The protocol of the WebSocket.
* @param {Function|Observer} [observerOrOnNext] An optional Observer or onNext function to capture the open event.
* @returns {Subject} An observable sequence wrapping a WebSocket.
*/
Rx.WinJS.fromWebSocket = function (url, protocol, observerOrOnNext) {
var socket = new window.WebSocket(url, protocol);
var observable = observableCreate(function (obs) {
if (observerOrOnNext) {
socket.onopen = function (openEvent) {
if (typeof observerOrOnNext === 'function') {
observerOrOnNext(openEvent);
} else if (observerOrOnNext.onNext) {
observerOrOnNext.onNext(openEvent);
}
};
}
socket.onmessage = function (data) {
obs.onNext(data);
};
socket.onerror = function (err) {
obs.onError(err);
};
socket.onclose = function () {
obs.onCompleted();
};
return function () {
socket.close();
};
});
var observer = observerCreate(function (data) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(data);
}
});
return Subject.create(observer, observable);
};
if (window.Worker) {
/**
* Creates a Web Worker with a given URL as a Subject.
*
* @example
* var worker = Rx.DOM.fromWebWorker('worker.js');
*
* @param {String} url The URL of the Web Worker.
* @returns {Subject} A Subject wrapping the Web Worker.
*/
Rx.WinJS.fromWebWorker = function (url) {
var worker = new window.Worker(url);
var observable = observableCreateWithDisposable(function (obs) {
worker.onmessage = function (data) {
obs.onNext(data);
};
worker.onerror = function (err) {
obs.onError(err);
};
return disposableCreate(function () {
worker.close();
});
});
var observer = observerCreate(function (data) {
worker.postMessage(data);
});
return Subject.create(observer, observable);
};
} Rx.WinJS.Geolocation = {
/**
* Obtains the geographic position, in terms of latitude and longitude coordinates, of the device.
* @param {Object} [geolocationOptions] An object literal to specify one or more of the following attributes and desired values:
* - enableHighAccuracy: Specify true to obtain the most accurate position possible, or false to optimize in favor of performance and power consumption.
* - timeout: An Integer value that indicates the time, in milliseconds, allowed for obtaining the position.
* If timeout is Infinity, (the default value) the location request will not time out.
* If timeout is zero (0) or negative, the results depend on the behavior of the location provider.
* - maximumAge: An Integer value indicating the maximum age, in milliseconds, of cached position information.
* If maximumAge is non-zero, and a cached position that is no older than maximumAge is available, the cached position is used instead of obtaining an updated location.
* If maximumAge is zero (0), watchPosition always tries to obtain an updated position, even if a cached position is already available.
* If maximumAge is Infinity, any cached position is used, regardless of its age, and watchPosition only tries to obtain an updated position if no cached position data exists.
* @returns {AsyncSubject} An observable sequence with the geographical location of the device running the client.
*/
getCurrentPosition: function (geolocationOptions) {
var subject = new Rx.AsyncSubject();
window.navigator.geolocation.getCurrentPosition(
function successHandler (loc) {
subject.onNext(loc);
subject.onCompleted();
},
function errorHandler (err) {
subject.onError(err);
},
geolocationOptions);
return subject.asObservable();
},
/**
* Begins listening for updates to the current geographical location of the device running the client.
* @param {Object} [geolocationOptions] An object literal to specify one or more of the following attributes and desired values:
* - enableHighAccuracy: Specify true to obtain the most accurate position possible, or false to optimize in favor of performance and power consumption.
* - timeout: An Integer value that indicates the time, in milliseconds, allowed for obtaining the position.
* If timeout is Infinity, (the default value) the location request will not time out.
* If timeout is zero (0) or negative, the results depend on the behavior of the location provider.
* - maximumAge: An Integer value indicating the maximum age, in milliseconds, of cached position information.
* If maximumAge is non-zero, and a cached position that is no older than maximumAge is available, the cached position is used instead of obtaining an updated location.
* If maximumAge is zero (0), watchPosition always tries to obtain an updated position, even if a cached position is already available.
* If maximumAge is Infinity, any cached position is used, regardless of its age, and watchPosition only tries to obtain an updated position if no cached position data exists.
* @returns {Observable} An observable sequence with the current geographical location of the device running the client.
*/
watchPosition: function (geolocationOptions) {
return observableCreate(function (observer) {
var watchId = window.navigator.geolocation.watchPosition(
function successHandler (loc) {
observer.onNext(loc);
},
function errorHandler (err) {
observer.onError(err);
},
geolocationOptions);
return function () {
window.navigator.geolocation.clearWatch(watchId);
};
}).publish().refCount();
}
};
/**
* Creates a wrapper for listening to WinJS sensor's events.
* @param {Object} sensor The WinJS sensor to attach the event listener.
* @param {String} eventName The event name to listen for.
* @returns {Observable} An observable sequence wrapping the Sensor's given event event.
*/
var fromSensorEvent = Rx.WinJS.fromSensorEvent = function (sensor, eventName) {
return observableCreateWithDisposable(function (observer) {
if (!sensor) {
observer.onError('Sensor not supported');
return disposableEmpty;
}
function handler(eventData) {
observer.onNext(eventData);
}
sensor.addEventListener(sensor, eventName, false);
return disposableCreate(function () {
sensor.removeEventListener(sensor, eventName, false);
});
}).publish().refCount();
};
var accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
Rx.WinJS.Accelerometer = {
/**
* Creates a wrapper for the Accelerometer which listens for the readingchanged event.
* @returns {Observable} An observable sequence wrapping the Accelerometer's readingchanged event.
*/
readingChanged: function () {
return fromSensorEvent(accelerometer, 'readingchanged');
},
/**
* Creates a wrapper for the Accelerometer which listens for the shaken event.
* @returns {Observable} An observable sequence wrapping the Accelerometer's shaken event.
*/
shaken: function () {
return fromSensorEvent(accelerometer, 'shaken');
}
}
var compass = Windows.Devices.Sensors.Compass.getDefault();
Rx.WinJS.Compass = {
/**
* Creates a wrapper for the Compass which listens for the readingchanged event.
* @returns {Observable} An observable sequence wrapping the Compass's readingchanged event.
*/
readingChanged: function () {
return fromSensorEvent(compass, 'readingchanged');
}
};
var lightSensor = Windows.Devices.Sensors.LightSensor.getDefault();
Rx.WinJS.LightSensor = {
/**
* Creates a wrapper for the LightSensor which listens for the readingchanged event.
* @returns {Observable} An observable sequence wrapping the LightSensor's readingchanged event.
*/
readingChanged: function () {
return fromSensorEvent(lightSensor, 'readingchanged');
}
};
var orientationSensor = Windows.Devices.Sensors.OrientationSensor.getDefault();
Rx.WinJS.OrientationSensor = {
/**
* Creates a wrapper for the OrientationSensor which listens for the readingchanged event.
* @returns {Observable} An observable sequence wrapping the OrientationSensor's readingchanged event.
*/
readingChanged: function () {
return fromSensorEvent(orientationSensor, 'readingchanged');
}
};
var simpleOrientationSensor = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault();
Rx.WinJS.SimpleOrientationSensor = {
/**
* Creates a wrapper for the SimpleOrientationSensor which listens for the orientationchanged event.
* @returns {Observable} An observable sequence wrapping the SimpleOrientationSensor's orientationchanged event.
*/
orientationChanged: function (reportInterval) {
return fromSensorEvent(simpleOrientationSensor, 'orientationchanged');
}
};
// Get the right animation frame method
var requestAnimFrame, cancelAnimFrame;
if (window.requestAnimationFrame) {
requestAnimFrame = window.requestAnimationFrame;
cancelAnimFrame = window.cancelAnimationFrame;
} else if (window.mozRequestAnimationFrame) {
requestAnimFrame = window.mozRequestAnimationFrame;
cancelAnimFrame = window.mozCancelAnimationFrame;
} else if (window.webkitRequestAnimationFrame) {
requestAnimFrame = window.webkitRequestAnimationFrame;
cancelAnimFrame = window.webkitCancelAnimationFrame;
} else if (window.msRequestAnimationFrame) {
requestAnimFrame = window.msRequestAnimationFrame;
cancelAnimFrame = window.msCancelAnimationFrame;
} else if (window.oRequestAnimationFrame) {
requestAnimFrame = window.oRequestAnimationFrame;
cancelAnimFrame = window.oCancelAnimationFrame;
} else {
requestAnimFrame = function(cb) { window.setTimeout(cb, 1000 / 60); };
cancelAnimFrame = window.clearTimeout;
}
/**
* Gets a scheduler that schedules schedules work on the requestAnimationFrame for immediate actions.
*
* @memberOf Scheduler
*/
Scheduler.requestAnimationFrame = (function () {
var defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }());
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = requestAnimFrame(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
cancelAnimFrame(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable(),
id;
var scheduleFunc = function () {
if (id) { cancelAnimFrame(id); }
if (dt - scheduler.now() <= 0) {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
} else {
id = requestAnimFrame(scheduleFunc);
}
};
id = requestAnimFrame(scheduleFunc);
return new CompositeDisposable(disposable, disposableCreate(function () {
cancelAnimFrame(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
// Check for mutation observer
var BrowserMutationObserver = window.MutationObserver;
if (BrowserMutationObserver) {
/**
* Scheduler that uses a MutationObserver changes as the scheduling mechanism
* @memberOf {Scheduler}
*/
Scheduler.mutationObserver = (function () {
var queue = {}, queueId = 0;
function cloneObj (obj) {
var newObj = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
newObj[prop] = obj[prop];
}
}
return newObj;
}
var observer = new BrowserMutationObserver(function() {
var toProcess = cloneObj(queue);
queue = {};
for (var prop in toProcess) {
if (toProcess.hasOwnProperty(prop)) {
toProcess[prop]();
}
}
});
var element = document.createElement('div');
observer.observe(element, { attributes: true });
// Prevent leaks
window.addEventListener('unload', function () {
observer.disconnect();
observer = null;
}, false);
function scheduleMethod (action) {
var id = queueId++;
queue[id] = action;
element.setAttribute('drainQueue', 'drainQueue');
return id;
}
function cancelMethod (id) {
delete queue[id];
}
function defaultNow () { return new Date().getTime(); }
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return disposable;
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable(),
id;
var scheduleFunc = function () {
if (id) { cancelMethod(id); }
if (dt - scheduler.now() <= 0) {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
} else {
id = scheduleMethod(scheduleFunc);
}
};
id = scheduleMethod(scheduleFunc);
return new CompositeDisposable(disposable, disposableCreate(function () {
cancelMethod(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
}
return Rx;
}));