-
Notifications
You must be signed in to change notification settings - Fork 1
/
bundle.js
3550 lines (3153 loc) · 103 KB
/
bundle.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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 10);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Created by snail on 4/11/17.
*/
var debug_1 = __webpack_require__(9);
exports.tileSize = 32; // 32x32 px per tile
exports.blockSize = 16; // 8x8 tiles per block
// (px/tile) * (tiles/chunk) = px/chunk
exports.pixelsPerChunk = exports.tileSize * exports.blockSize;
// Provided by seed-random
Math.seedrandom(3);
exports.noise = new SimplexNoise();
exports.game = {
'user': null,
'camera': null,
'resources': null,
'chunkManager': null,
'controls': null,
'debug': new debug_1.Debug().getProxyObject()
};
exports.terrain = {
WATER: 222,
SAND: 18,
GRASS: 0,
STONE: 1,
GOLD: 32
};
function mapDefault(x, y) {
var val = 0;
var max = 0, min = 0;
function step(coordScale, valScale) {
val += exports.noise.noise2D(x / coordScale, y / coordScale) * valScale;
max += valScale;
min -= valScale;
}
var large = 1024;
var small = 1;
for (var i = 1; i < 6; i++) {
step(large, small);
large /= 3;
small /= 2;
}
// step(10, .25);
var v = (val - min) / (max - min);
if (v < .33) {
return { value: exports.terrain.WATER };
}
else if (v < .4) {
return { value: exports.terrain.SAND };
}
else if (v < .6) {
return { value: exports.terrain.GRASS };
}
else {
// mountain resources
if (v > .7 && exports.noise.noise2D(x * 2, y * 2) > .5) {
return { value: exports.terrain.GOLD };
}
return { value: exports.terrain.STONE };
}
}
exports.mapDefault = mapDefault;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var globals = __webpack_require__(0);
;
var Camera = (function () {
function Camera() {
var _this = this;
if (globals.game.camera)
throw new Error("Camera re-initialized");
globals.game.camera = this;
this.worldX = 0;
this.worldY = 0;
this.displayWidth = 0;
this.displayHeight = 0;
this.displayZoom = 1;
this.subscriptions = {};
this.layers = [new TerrainLayer(), new OverlayLayer()];
window.onresize =
function () { _this.setSize(window.innerWidth, window.innerHeight); };
this.setCenter(0, 0);
window.onresize(null);
}
Camera.prototype.subscribe = function (event, handler) {
this.subscriptions[event] = this.subscriptions[event] || [];
this.subscriptions[event].push(handler);
};
Camera.prototype.publishEvent = function (event) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
(this.subscriptions[event] || []).forEach(function (cb) { return cb.apply(void 0, args); });
};
Object.defineProperty(Camera.prototype, "topLayer", {
get: function () { return this.layers[this.layers.length - 1]; },
enumerable: true,
configurable: true
});
Camera.prototype.forEachLayer = function (cb) { this.layers.forEach(cb); };
Camera.prototype.setSize = function (width, height) {
this.displayWidth = width;
this.displayHeight = height;
this.publishEvent("resize", width, height);
};
Camera.prototype.moveCenter = function (dx, dy) { this.setCenter(this.worldX + dx, this.worldY + dy); };
Camera.prototype.setCenter = function (x, y) {
this.worldX = x;
this.worldY = y;
this.publishEvent("moved", this.worldX, this.worldY);
};
Object.defineProperty(Camera.prototype, "zoom", {
get: function () { return this.displayZoom; },
set: function (z) {
var old = this.displayZoom;
this.displayZoom = Math.min(4, Math.max(.5, z));
if (this.displayZoom != old)
this.publishEvent("zoomed", this.displayZoom);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "screenLeft", {
/* Returns world coordinates for the left/right/top/bottom of the screen */
get: function () {
return Math.floor(this.worldX - this.displayWidth / 2 / this.displayZoom);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "screenTop", {
get: function () {
return Math.floor(this.worldY - this.displayHeight / 2 / this.displayZoom);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "screenRight", {
get: function () {
return Math.ceil(this.worldX + this.displayWidth / 2 / this.displayZoom);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera.prototype, "screenBottom", {
get: function () {
return Math.ceil(this.worldY + this.displayHeight / 2 / this.displayZoom);
},
enumerable: true,
configurable: true
});
/**
Given screen (x,y) return
{chunk: [x,y], tile:[x,y]}
*/
Camera.prototype.screenPointToWorld = function (x, y) {
var worldX = x / this.displayZoom + this.screenLeft;
var worldY = y / this.displayZoom + this.screenTop;
var chunkX = Math.floor(worldX / globals.pixelsPerChunk);
var chunkY = Math.floor(worldY / globals.pixelsPerChunk);
var tileX = Math.floor((worldX - chunkX * globals.pixelsPerChunk) / globals.tileSize);
var tileY = Math.floor((worldY - chunkY * globals.pixelsPerChunk) / globals.tileSize);
return { chunk: [chunkX, chunkY], tile: [tileX, tileY] };
};
/**
* Set the transform on the canvas to map the camera's world position and
* zoom.
*/
Camera.prototype.applyWorldTransform = function (ctx) {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.scale(this.displayZoom, this.displayZoom);
ctx.translate(-this.screenLeft, -this.screenTop);
};
return Camera;
}());
exports.Camera = Camera;
var Layer = (function () {
function Layer() {
var _this = this;
this.canvas = document.createElement("canvas");
this.canvas.style.imageRendering = "pixelated";
this.ctx = this.canvas.getContext("2d");
document.getElementById("layers").appendChild(this.canvas);
globals.game.camera.subscribe("resize", function (width, height) {
_this.canvas.width = width;
_this.canvas.height = height;
_this.ctx.imageSmoothingEnabled = false;
_this.redrawAll();
});
}
Layer.prototype.redrawAll = function () { };
return Layer;
}());
var TerrainLayer = (function (_super) {
__extends(TerrainLayer, _super);
function TerrainLayer() {
var _this = _super.call(this) || this;
var worldUpdateHandler = _this.worldUpdateHandler.bind(_this);
globals.game.camera.subscribe("moved", worldUpdateHandler);
globals.game.camera.subscribe("zoomed", worldUpdateHandler);
globals.game.camera.subscribe("resize", worldUpdateHandler);
globals.game.chunkManager.subscribe("update", _this.redrawChunk.bind(_this));
return _this;
}
TerrainLayer.prototype.worldUpdateHandler = function () {
var _this = this;
var camera = globals.game.camera;
var chunkLeft = Math.floor(camera.screenLeft / globals.pixelsPerChunk) - 1;
var chunkTop = Math.floor(camera.screenTop / globals.pixelsPerChunk) - 1;
var chunkRight = Math.ceil(camera.screenRight / globals.pixelsPerChunk) + 1;
var chunkBot = Math.ceil(camera.screenBottom / globals.pixelsPerChunk) + 1;
camera.applyWorldTransform(this.ctx);
var chunkLocations = new Set();
for (var y = chunkTop; y < chunkBot; y++)
for (var x = chunkLeft; x < chunkRight; x++) {
chunkLocations.add(x + "," + y);
}
globals.game.chunkManager.ensureLoadedChunks(chunkLocations);
globals.game.chunkManager.loadedChunks.forEach(function (chunk) {
_this.redrawChunk(chunk);
});
};
TerrainLayer.prototype.redrawChunk = function (chunk) {
var x = chunk.x * globals.pixelsPerChunk;
var y = chunk.y * globals.pixelsPerChunk;
this.ctx.font = "20px";
this.ctx.drawImage(chunk.image, x, y);
if (globals.game.debug.showChunks) {
this.ctx.beginPath();
this.ctx.rect(x, y, globals.pixelsPerChunk, globals.pixelsPerChunk);
this.ctx.fillText("(" + chunk.x + "," + chunk.y + ")", x + globals.pixelsPerChunk / 2, y + globals.pixelsPerChunk / 2);
this.ctx.stroke();
}
};
return TerrainLayer;
}(Layer));
var OverlayLayer = (function (_super) {
__extends(OverlayLayer, _super);
function OverlayLayer() {
var _this = _super.call(this) || this;
_this.setupLocationHash();
return _this;
}
OverlayLayer.prototype.setupLocationHash = function () {
var updating = false;
globals.game.camera.subscribe("moved", function (x, y) {
// make the coords integers.
x |= 0;
y |= 0;
globals.game.debug.location = x + "," + y;
if (updating)
return;
updating = true;
setTimeout(function () {
window.location.hash = globals.game.debug.location;
updating = false;
}, 1000);
});
};
return OverlayLayer;
}(Layer));
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var globals_1 = __webpack_require__(0);
var chunk_1 = __webpack_require__(8);
var ChunkManager = (function () {
function ChunkManager() {
if (globals_1.game.chunkManager)
throw new Error("ChunkManager re-initialized");
globals_1.game.chunkManager = this;
this.loadedChunks = new Map();
this.subscriptions = {};
}
ChunkManager.prototype.subscribe = function (event, handler) {
this.subscriptions[event] = this.subscribe[event] || [];
this.subscriptions[event].push(handler);
};
ChunkManager.prototype.publishEvent = function (event) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
(this.subscriptions[event] || []).forEach(function (cb) { return cb.apply(void 0, args); });
};
/**
* @param {Set} chunkLocations
*/
ChunkManager.prototype.ensureLoadedChunks = function (chunkLocations) {
// chunkLocations = all locations we want.
// loadedChunks = all locations we have.
var _this = this;
this.loadedChunks.forEach(function (chunk, key) {
if (chunkLocations.has(key)) {
// we want to keep this chunk, remove its key from the 'locations we
// want'
chunkLocations.delete(key);
}
else {
// we don't want this chunk, unload it.
if (chunk.unload())
_this.loadedChunks.delete(key);
}
});
// We're left with chunks we want but didn't have, load them.
chunkLocations.forEach(function (loc) {
var coords = loc.split(",");
_this.loadedChunks.set(loc, new chunk_1.ChunkType(parseInt(coords[0]), parseInt(coords[1])));
});
};
return ChunkManager;
}());
exports.ChunkManager = ChunkManager;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
__webpack_require__(7);
var globals_1 = __webpack_require__(0);
var Controls = (function () {
function Controls() {
if (globals_1.game.controls)
throw new Error("Controls re-initialized");
globals_1.game.controls = this;
this.mouseLayer = globals_1.game.camera.topLayer.canvas;
this.hammer = new Hammer(this.mouseLayer);
this.setupPinchZoom();
this.setupWheelZoom();
this.setupPanning();
this.setupTap();
}
Controls.prototype.setupPinchZoom = function () {
var baseZoom = null;
this.hammer.get('pinch').set({ enable: true });
this.hammer.on("pinchstart", function () {
baseZoom = globals_1.game.camera.zoom;
});
this.hammer.on("pinch", function (e) {
globals_1.game.camera.zoom = baseZoom * e.scale;
});
};
Controls.prototype.setupWheelZoom = function () {
this.mouseLayer.addEventListener("mousewheel", this.wheelZoom, false);
this.mouseLayer.addEventListener("DOMMouseScroll", this.wheelZoom, false);
};
Controls.prototype.wheelZoom = function (e) {
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
if (delta > 0)
globals_1.game.camera.zoom *= 1.03;
else
globals_1.game.camera.zoom /= 1.03;
};
Controls.prototype.setupPanning = function () {
var last = null;
this.hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL });
this.hammer.on("pan press panstart", function (e) {
if (last === null) {
last = e.center;
return;
}
if (e.isFinal) {
last = null;
return;
}
var dx = last.x - e.center.x;
var dy = last.y - e.center.y;
globals_1.game.camera.moveCenter(dx / globals_1.game.camera.zoom, dy / globals_1.game.camera.zoom);
last = e.center;
});
};
Controls.prototype.setupTap = function () {
this.hammer.on("tap", function (e) {
var target = globals_1.game.camera.screenPointToWorld(e.center.x, e.center.y);
var chunk = globals_1.game.chunkManager.loadedChunks.get("" + target.chunk);
chunk.clicked(target.tile[0], target.tile[1]);
});
};
return Controls;
}());
exports.Controls = Controls;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var config = {
apiKey: "AIzaSyChgv4F6sgROm0Lkv2qbMMsLsyXytAkqgk",
authDomain: "snail-53ef6.firebaseapp.com",
databaseURL: "https://snail-53ef6.firebaseio.com",
projectId: "snail-53ef6",
storageBucket: "snail-53ef6.appspot.com",
messagingSenderId: "248204123455"
};
function initFirebase(onChange) {
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged(function (user) {
if (user === null)
return firebase.auth().signInAnonymously();
var ref = firebase.database().ref("users/" + user.uid);
if (user.isAnonymous) {
// Delete anonymous users when they leave.
ref.onDisconnect().remove();
}
onChange(user, ref);
});
}
exports.initFirebase = initFirebase;
;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var globals_1 = __webpack_require__(0);
var Resources = (function () {
function Resources() {
if (globals_1.game.resources)
throw new Error("Resources re-initialized");
globals_1.game.resources = this;
this.tilesets = new Map();
}
Resources.prototype.drawTile = function (tilesheet, tile, ctx, dx, dy) {
var x = tile % 16;
var y = (tile - x) / 16;
ctx.drawImage(tilesheet, x * globals_1.tileSize, y * globals_1.tileSize, globals_1.tileSize, globals_1.tileSize, dx, dy, globals_1.tileSize, globals_1.tileSize);
};
/**
* Returns a promise that is resolved with the image. If the image is in cache
* this promise resolves immediately.
*/
Resources.prototype.getTilesheet = function (url) {
if (this.tilesets.has(url)) {
return this.tilesets.get(url);
}
var img = new Image();
var p = new Promise(function (resolve, reject) {
img.onload = function () {
var rows = img.height / globals_1.tileSize;
var cols = img.width / globals_1.tileSize;
if (!Number.isInteger(rows) || !Number.isInteger(cols)) {
console.warn("Image " + url + " not evenly divisible by " + globals_1.tileSize);
console.warn(img.width, img.height);
reject();
}
else {
resolve(img);
}
};
img.onerror = function () { reject(); };
});
this.tilesets.set(url, p);
img.src = url;
return p;
};
return Resources;
}());
exports.Resources = Resources;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var globals_1 = __webpack_require__(0);
var User = (function () {
function User(user, ref) {
if (globals_1.game.user)
throw new Error("User re-initialized");
globals_1.game.user = this;
this.user = user;
this.ref = ref;
this.setupListeners();
}
User.prototype.setupListeners = function () {
var _this = this;
this.ref.on('value', function (v) {
v = v.val();
if (v === null)
return _this.spawn();
return _this.update(v);
});
};
User.prototype.spawn = function () {
var spawn = { x: 0, y: 0 };
var hash = window.location.hash.substr(1);
if (hash) {
var args = hash.split(",");
spawn.x = parseInt(args[0]) | 0;
spawn.y = parseInt(args[1]) | 0;
}
this.ref.set(spawn);
};
User.prototype.update = function (details) { globals_1.game.camera.setCenter(details.x, details.y); };
return User;
}());
exports.User = User;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.7 - 2016-04-22
* http://hammerjs.github.io/
*
* Copyright (c) 2016 Jorik Tangelder;
* Licensed under the MIT license */
(function(window, document, exportName, undefined) {
'use strict';
var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = document.createElement('div');
var TYPE_FUNCTION = 'function';
var round = Math.round;
var abs = Math.abs;
var now = Date.now;
/**
* set a timeout with a given scope
* @param {Function} fn
* @param {Number} timeout
* @param {Object} context
* @returns {number}
*/
function setTimeoutContext(fn, timeout, context) {
return setTimeout(bindFn(fn, context), timeout);
}
/**
* if the argument is an array, we want to execute the fn on each entry
* if it aint an array we don't want to do a thing.
* this is used by all the methods that accept a single and array argument.
* @param {*|Array} arg
* @param {String} fn
* @param {Object} [context]
* @returns {Boolean}
*/
function invokeArrayArg(arg, fn, context) {
if (Array.isArray(arg)) {
each(arg, context[fn], context);
return true;
}
return false;
}
/**
* walk objects and arrays
* @param {Object} obj
* @param {Function} iterator
* @param {Object} context
*/
function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
}
/**
* wrap a method with a deprecation warning and stack trace
* @param {Function} method
* @param {String} name
* @param {String} message
* @returns {Function} A new function wrapping the supplied method.
*/
function deprecate(method, name, message) {
var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
return function() {
var e = new Error('get-stack-trace');
var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
.replace(/^\s+at\s+/gm, '')
.replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
var log = window.console && (window.console.warn || window.console.log);
if (log) {
log.call(window.console, deprecationMessage, stack);
}
return method.apply(this, arguments);
};
}
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} target
* @param {...Object} objects_to_assign
* @returns {Object} target
*/
var assign;
if (typeof Object.assign !== 'function') {
assign = function assign(target) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
} else {
assign = Object.assign;
}
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} dest
* @param {Object} src
* @param {Boolean} [merge=false]
* @returns {Object} dest
*/
var extend = deprecate(function extend(dest, src, merge) {
var keys = Object.keys(src);
var i = 0;
while (i < keys.length) {
if (!merge || (merge && dest[keys[i]] === undefined)) {
dest[keys[i]] = src[keys[i]];
}
i++;
}
return dest;
}, 'extend', 'Use `assign`.');
/**
* merge the values from src in the dest.
* means that properties that exist in dest will not be overwritten by src
* @param {Object} dest
* @param {Object} src
* @returns {Object} dest
*/
var merge = deprecate(function merge(dest, src) {
return extend(dest, src, true);
}, 'merge', 'Use `assign`.');
/**
* simple class inheritance
* @param {Function} child
* @param {Function} base
* @param {Object} [properties]
*/
function inherit(child, base, properties) {
var baseP = base.prototype,
childP;
childP = child.prototype = Object.create(baseP);
childP.constructor = child;
childP._super = baseP;
if (properties) {
assign(childP, properties);
}
}
/**
* simple function bind
* @param {Function} fn
* @param {Object} context
* @returns {Function}
*/
function bindFn(fn, context) {
return function boundFn() {
return fn.apply(context, arguments);
};
}
/**
* let a boolean value also be a function that must return a boolean
* this first item in args will be used as the context
* @param {Boolean|Function} val
* @param {Array} [args]
* @returns {Boolean}
*/
function boolOrFn(val, args) {
if (typeof val == TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
}
/**
* use the val2 when val1 is undefined
* @param {*} val1
* @param {*} val2
* @returns {*}
*/
function ifUndefined(val1, val2) {
return (val1 === undefined) ? val2 : val1;
}
/**
* addEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function addEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.addEventListener(type, handler, false);
});
}
/**
* removeEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function removeEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.removeEventListener(type, handler, false);
});
}
/**
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent(node, parent) {
while (node) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
/**
* small indexOf wrapper
* @param {String} str
* @param {String} find
* @returns {Boolean} found
*/
function inStr(str, find) {
return str.indexOf(find) > -1;
}
/**
* split string on whitespace
* @param {String} str
* @returns {Array} words
*/
function splitStr(str) {
return str.trim().split(/\s+/g);
}
/**
* find if a array contains the object using indexOf or a simple polyFill
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number} false when not found, or the index
*/
function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
return i;
}
i++;
}
return -1;
}
}
/**
* convert array-like objects to real arrays
* @param {Object} obj
* @returns {Array}
*/
function toArray(obj) {
return Array.prototype.slice.call(obj, 0);
}
/**
* unique array with objects based on a key (like 'id') or just by the array's value
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
function uniqueArray(src, key, sort) {
var results = [];
var values = [];
var i = 0;
while (i < src.length) {
var val = key ? src[i][key] : src[i];
if (inArray(values, val) < 0) {
results.push(src[i]);
}
values[i] = val;
i++;
}
if (sort) {
if (!key) {
results = results.sort();
} else {
results = results.sort(function sortUniqueArray(a, b) {
return a[key] > b[key];
});
}
}
return results;
}
/**
* get the prefixed property
* @param {Object} obj
* @param {String} property
* @returns {String|Undefined} prefixed
*/
function prefixed(obj, property) {
var prefix, prop;
var camelProp = property[0].toUpperCase() + property.slice(1);
var i = 0;
while (i < VENDOR_PREFIXES.length) {
prefix = VENDOR_PREFIXES[i];
prop = (prefix) ? prefix + camelProp : property;
if (prop in obj) {
return prop;
}
i++;
}
return undefined;
}
/**
* get a unique id
* @returns {number} uniqueId
*/
var _uniqueId = 1;
function uniqueId() {
return _uniqueId++;
}
/**
* get the window object of an element
* @param {HTMLElement} element
* @returns {DocumentView|Window}
*/
function getWindowForElement(element) {
var doc = element.ownerDocument || element;
return (doc.defaultView || doc.parentWindow || window);
}
var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
var SUPPORT_TOUCH = ('ontouchstart' in window);
var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;