GPQAPP

Форк
0
946 строк · 26.1 Кб
1
(function() {
2
  var AjaxMonitor, Bar, DocumentMonitor, ElementMonitor, ElementTracker, EventLagMonitor, Evented, Events, NoTargetError, Pace, RequestIntercept, SOURCE_KEYS, Scaler, SocketRequestTracker, XHRRequestTracker, _WebSocket, _XDomainRequest, _XMLHttpRequest, _intercept, _pushState, _replaceState, animation, avgAmplitude, bar, cancelAnimation, cancelAnimationFrame, defaultOptions, extend, extendNative, getFromDOM, getIntercept, handlePushState, ignoreStack, init, k, len, now, options, ref, requestAnimationFrame, result, runAnimation, scalers, shouldIgnoreURL, shouldTrack, source, sources, uniScaler,
3
    slice = [].slice,
4
    hasProp = {}.hasOwnProperty,
5
    extend1 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
6
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
7

8
  defaultOptions = {
9
    catchupTime: 100,
10
    initialRate: .03,
11
    minTime: 250,
12
    ghostTime: 100,
13
    maxProgressPerFrame: 20,
14
    easeFactor: 1.25,
15
    startOnPageLoad: true,
16
    restartOnPushState: true,
17
    restartOnRequestAfter: 500,
18
    target: 'body',
19
    elements: {
20
      checkInterval: 100,
21
      selectors: ['body']
22
    },
23
    eventLag: {
24
      minSamples: 10,
25
      sampleCount: 3,
26
      lagThreshold: 3
27
    },
28
    ajax: {
29
      trackMethods: ['GET'],
30
      trackWebSockets: true,
31
      ignoreURLs: []
32
    }
33
  };
34

35
  now = function() {
36
    var ref;
37
    return (ref = typeof performance !== "undefined" && performance !== null ? typeof performance.now === "function" ? performance.now() : void 0 : void 0) != null ? ref : +(new Date);
38
  };
39

40
  requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
41

42
  cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
43

44
  if (requestAnimationFrame == null) {
45
    requestAnimationFrame = function(fn) {
46
      return setTimeout(fn, 50);
47
    };
48
    cancelAnimationFrame = function(id) {
49
      return clearTimeout(id);
50
    };
51
  }
52

53
  runAnimation = function(fn) {
54
    var last, tick;
55
    last = now();
56
    tick = function() {
57
      var diff;
58
      diff = now() - last;
59
      if (diff >= 33) {
60
        last = now();
61
        return fn(diff, function() {
62
          return requestAnimationFrame(tick);
63
        });
64
      } else {
65
        return setTimeout(tick, 33 - diff);
66
      }
67
    };
68
    return tick();
69
  };
70

71
  result = function() {
72
    var args, key, obj;
73
    obj = arguments[0], key = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : [];
74
    if (typeof obj[key] === 'function') {
75
      return obj[key].apply(obj, args);
76
    } else {
77
      return obj[key];
78
    }
79
  };
80

81
  extend = function() {
82
    var k, key, len, out, source, sources, val;
83
    out = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];
84
    for (k = 0, len = sources.length; k < len; k++) {
85
      source = sources[k];
86
      if (source) {
87
        for (key in source) {
88
          if (!hasProp.call(source, key)) continue;
89
          val = source[key];
90
          if ((out[key] != null) && typeof out[key] === 'object' && (val != null) && typeof val === 'object') {
91
            extend(out[key], val);
92
          } else {
93
            out[key] = val;
94
          }
95
        }
96
      }
97
    }
98
    return out;
99
  };
100

101
  avgAmplitude = function(arr) {
102
    var count, k, len, sum, v;
103
    sum = count = 0;
104
    for (k = 0, len = arr.length; k < len; k++) {
105
      v = arr[k];
106
      sum += Math.abs(v);
107
      count++;
108
    }
109
    return sum / count;
110
  };
111

112
  getFromDOM = function(key, json) {
113
    var data, e, el, error;
114
    if (key == null) {
115
      key = 'options';
116
    }
117
    if (json == null) {
118
      json = true;
119
    }
120
    el = document.querySelector("[data-pace-" + key + "]");
121
    if (!el) {
122
      return;
123
    }
124
    data = el.getAttribute("data-pace-" + key);
125
    if (!json) {
126
      return data;
127
    }
128
    try {
129
      return JSON.parse(data);
130
    } catch (error) {
131
      e = error;
132
      return typeof console !== "undefined" && console !== null ? console.error("Error parsing inline pace options", e) : void 0;
133
    }
134
  };
135

136
  Evented = (function() {
137
    function Evented() {}
138

139
    Evented.prototype.on = function(event, handler, ctx, once) {
140
      var base;
141
      if (once == null) {
142
        once = false;
143
      }
144
      if (this.bindings == null) {
145
        this.bindings = {};
146
      }
147
      if ((base = this.bindings)[event] == null) {
148
        base[event] = [];
149
      }
150
      return this.bindings[event].push({
151
        handler: handler,
152
        ctx: ctx,
153
        once: once
154
      });
155
    };
156

157
    Evented.prototype.once = function(event, handler, ctx) {
158
      return this.on(event, handler, ctx, true);
159
    };
160

161
    Evented.prototype.off = function(event, handler) {
162
      var i, ref, results;
163
      if (((ref = this.bindings) != null ? ref[event] : void 0) == null) {
164
        return;
165
      }
166
      if (handler == null) {
167
        return delete this.bindings[event];
168
      } else {
169
        i = 0;
170
        results = [];
171
        while (i < this.bindings[event].length) {
172
          if (this.bindings[event][i].handler === handler) {
173
            results.push(this.bindings[event].splice(i, 1));
174
          } else {
175
            results.push(i++);
176
          }
177
        }
178
        return results;
179
      }
180
    };
181

182
    Evented.prototype.trigger = function() {
183
      var args, ctx, event, handler, i, once, ref, ref1, results;
184
      event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
185
      if ((ref = this.bindings) != null ? ref[event] : void 0) {
186
        i = 0;
187
        results = [];
188
        while (i < this.bindings[event].length) {
189
          ref1 = this.bindings[event][i], handler = ref1.handler, ctx = ref1.ctx, once = ref1.once;
190
          handler.apply(ctx != null ? ctx : this, args);
191
          if (once) {
192
            results.push(this.bindings[event].splice(i, 1));
193
          } else {
194
            results.push(i++);
195
          }
196
        }
197
        return results;
198
      }
199
    };
200

201
    return Evented;
202

203
  })();
204

205
  Pace = window.Pace || {};
206

207
  window.Pace = Pace;
208

209
  extend(Pace, Evented.prototype);
210

211
  options = Pace.options = extend({}, defaultOptions, window.paceOptions, getFromDOM());
212

213
  ref = ['ajax', 'document', 'eventLag', 'elements'];
214
  for (k = 0, len = ref.length; k < len; k++) {
215
    source = ref[k];
216
    if (options[source] === true) {
217
      options[source] = defaultOptions[source];
218
    }
219
  }
220

221
  NoTargetError = (function(superClass) {
222
    extend1(NoTargetError, superClass);
223

224
    function NoTargetError() {
225
      return NoTargetError.__super__.constructor.apply(this, arguments);
226
    }
227

228
    return NoTargetError;
229

230
  })(Error);
231

232
  Bar = (function() {
233
    function Bar() {
234
      this.progress = 0;
235
    }
236

237
    Bar.prototype.getElement = function() {
238
      var targetElement;
239
      if (this.el == null) {
240
        targetElement = document.querySelector(options.target);
241
        if (!targetElement) {
242
          throw new NoTargetError;
243
        }
244
        this.el = document.createElement('div');
245
        this.el.classList.add('pace');
246
        this.el.classList.add('pace-active');
247
        document.body.classList.remove('pace-done');
248
        document.body.classList.add('pace-running');
249
        this.el.innerHTML = '<div class="pace-progress">\n  <div class="pace-progress-inner"></div>\n</div>\n<div class="pace-activity"></div>';
250
        if (targetElement.firstChild != null) {
251
          targetElement.insertBefore(this.el, targetElement.firstChild);
252
        } else {
253
          targetElement.appendChild(this.el);
254
        }
255
      }
256
      return this.el;
257
    };
258

259
    Bar.prototype.finish = function() {
260
      var el;
261
      el = this.getElement();
262
      el.classList.remove('pace-active');
263
      el.classList.add('pace-inactive');
264
      document.body.classList.remove('pace-running');
265
      return document.body.classList.add('pace-done');
266
    };
267

268
    Bar.prototype.update = function(prog) {
269
      this.progress = prog;
270
      return this.render();
271
    };
272

273
    Bar.prototype.destroy = function() {
274
      var error;
275
      try {
276
        this.getElement().parentNode.removeChild(this.getElement());
277
      } catch (error) {
278
        NoTargetError = error;
279
      }
280
      return this.el = void 0;
281
    };
282

283
    Bar.prototype.render = function() {
284
      var el, key, l, len1, progressStr, ref1, transform;
285
      if (document.querySelector(options.target) == null) {
286
        return false;
287
      }
288
      el = this.getElement();
289
      transform = "translate3d(" + this.progress + "%, 0, 0)";
290
      ref1 = ['webkitTransform', 'msTransform', 'transform'];
291
      for (l = 0, len1 = ref1.length; l < len1; l++) {
292
        key = ref1[l];
293
        el.children[0].style[key] = transform;
294
      }
295
      if (!this.lastRenderedProgress || this.lastRenderedProgress | 0 !== this.progress | 0) {
296
        el.children[0].setAttribute('data-progress-text', (this.progress | 0) + "%");
297
        if (this.progress >= 100) {
298
          progressStr = '99';
299
        } else {
300
          progressStr = this.progress < 10 ? "0" : "";
301
          progressStr += this.progress | 0;
302
        }
303
        el.children[0].setAttribute('data-progress', "" + progressStr);
304
      }
305
      return this.lastRenderedProgress = this.progress;
306
    };
307

308
    Bar.prototype.done = function() {
309
      return this.progress >= 100;
310
    };
311

312
    return Bar;
313

314
  })();
315

316
  Events = (function() {
317
    function Events() {
318
      this.bindings = {};
319
    }
320

321
    Events.prototype.trigger = function(name, val) {
322
      var binding, l, len1, ref1, results;
323
      if (this.bindings[name] != null) {
324
        ref1 = this.bindings[name];
325
        results = [];
326
        for (l = 0, len1 = ref1.length; l < len1; l++) {
327
          binding = ref1[l];
328
          results.push(binding.call(this, val));
329
        }
330
        return results;
331
      }
332
    };
333

334
    Events.prototype.on = function(name, fn) {
335
      var base;
336
      if ((base = this.bindings)[name] == null) {
337
        base[name] = [];
338
      }
339
      return this.bindings[name].push(fn);
340
    };
341

342
    return Events;
343

344
  })();
345

346
  _XMLHttpRequest = window.XMLHttpRequest;
347

348
  _XDomainRequest = window.XDomainRequest;
349

350
  _WebSocket = window.WebSocket;
351

352
  extendNative = function(to, from) {
353
    var e, error, key, results;
354
    results = [];
355
    for (key in from.prototype) {
356
      try {
357
        if ((to[key] == null) && typeof from[key] !== 'function') {
358
          if (typeof Object.defineProperty === 'function') {
359
            results.push(Object.defineProperty(to, key, {
360
              get: function() {
361
                return from.prototype[key];
362
              },
363
              configurable: true,
364
              enumerable: true
365
            }));
366
          } else {
367
            results.push(to[key] = from.prototype[key]);
368
          }
369
        } else {
370
          results.push(void 0);
371
        }
372
      } catch (error) {
373
        e = error;
374
      }
375
    }
376
    return results;
377
  };
378

379
  ignoreStack = [];
380

381
  Pace.ignore = function() {
382
    var args, fn, ret;
383
    fn = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
384
    ignoreStack.unshift('ignore');
385
    ret = fn.apply(null, args);
386
    ignoreStack.shift();
387
    return ret;
388
  };
389

390
  Pace.track = function() {
391
    var args, fn, ret;
392
    fn = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
393
    ignoreStack.unshift('track');
394
    ret = fn.apply(null, args);
395
    ignoreStack.shift();
396
    return ret;
397
  };
398

399
  shouldTrack = function(method) {
400
    var ref1;
401
    if (method == null) {
402
      method = 'GET';
403
    }
404
    if (ignoreStack[0] === 'track') {
405
      return 'force';
406
    }
407
    if (!ignoreStack.length && options.ajax) {
408
      if (method === 'socket' && options.ajax.trackWebSockets) {
409
        return true;
410
      } else if (ref1 = method.toUpperCase(), indexOf.call(options.ajax.trackMethods, ref1) >= 0) {
411
        return true;
412
      }
413
    }
414
    return false;
415
  };
416

417
  RequestIntercept = (function(superClass) {
418
    extend1(RequestIntercept, superClass);
419

420
    function RequestIntercept() {
421
      var monitorXHR;
422
      RequestIntercept.__super__.constructor.apply(this, arguments);
423
      monitorXHR = (function(_this) {
424
        return function(req) {
425
          var _open;
426
          _open = req.open;
427
          return req.open = function(type, url, async) {
428
            if (shouldTrack(type)) {
429
              _this.trigger('request', {
430
                type: type,
431
                url: url,
432
                request: req
433
              });
434
            }
435
            return _open.apply(req, arguments);
436
          };
437
        };
438
      })(this);
439
      window.XMLHttpRequest = function(flags) {
440
        var req;
441
        req = new _XMLHttpRequest(flags);
442
        monitorXHR(req);
443
        return req;
444
      };
445
      try {
446
        extendNative(window.XMLHttpRequest, _XMLHttpRequest);
447
      } catch (undefined) {}
448
      if (_XDomainRequest != null) {
449
        window.XDomainRequest = function() {
450
          var req;
451
          req = new _XDomainRequest;
452
          monitorXHR(req);
453
          return req;
454
        };
455
        try {
456
          extendNative(window.XDomainRequest, _XDomainRequest);
457
        } catch (undefined) {}
458
      }
459
      if ((_WebSocket != null) && options.ajax.trackWebSockets) {
460
        window.WebSocket = (function(_this) {
461
          return function(url, protocols) {
462
            var req;
463
            if (protocols != null) {
464
              req = new _WebSocket(url, protocols);
465
            } else {
466
              req = new _WebSocket(url);
467
            }
468
            if (shouldTrack('socket')) {
469
              _this.trigger('request', {
470
                type: 'socket',
471
                url: url,
472
                protocols: protocols,
473
                request: req
474
              });
475
            }
476
            return req;
477
          };
478
        })(this);
479
        try {
480
          extendNative(window.WebSocket, _WebSocket);
481
        } catch (undefined) {}
482
      }
483
    }
484

485
    return RequestIntercept;
486

487
  })(Events);
488

489
  _intercept = null;
490

491
  getIntercept = function() {
492
    if (_intercept == null) {
493
      _intercept = new RequestIntercept;
494
    }
495
    return _intercept;
496
  };
497

498
  shouldIgnoreURL = function(url) {
499
    var l, len1, pattern, ref1;
500
    ref1 = options.ajax.ignoreURLs;
501
    for (l = 0, len1 = ref1.length; l < len1; l++) {
502
      pattern = ref1[l];
503
      if (typeof pattern === 'string') {
504
        if (url.indexOf(pattern) !== -1) {
505
          return true;
506
        }
507
      } else {
508
        if (pattern.test(url)) {
509
          return true;
510
        }
511
      }
512
    }
513
    return false;
514
  };
515

516
  getIntercept().on('request', function(arg) {
517
    var after, args, request, type, url;
518
    type = arg.type, request = arg.request, url = arg.url;
519
    if (shouldIgnoreURL(url)) {
520
      return;
521
    }
522
    if (!Pace.running && (options.restartOnRequestAfter !== false || shouldTrack(type) === 'force')) {
523
      args = arguments;
524
      after = options.restartOnRequestAfter || 0;
525
      if (typeof after === 'boolean') {
526
        after = 0;
527
      }
528
      return setTimeout(function() {
529
        var l, len1, ref1, ref2, results, stillActive;
530
        if (type === 'socket') {
531
          stillActive = request.readyState < 2;
532
        } else {
533
          stillActive = (0 < (ref1 = request.readyState) && ref1 < 4);
534
        }
535
        if (stillActive) {
536
          Pace.restart();
537
          ref2 = Pace.sources;
538
          results = [];
539
          for (l = 0, len1 = ref2.length; l < len1; l++) {
540
            source = ref2[l];
541
            if (source instanceof AjaxMonitor) {
542
              source.watch.apply(source, args);
543
              break;
544
            } else {
545
              results.push(void 0);
546
            }
547
          }
548
          return results;
549
        }
550
      }, after);
551
    }
552
  });
553

554
  AjaxMonitor = (function() {
555
    function AjaxMonitor() {
556
      this.elements = [];
557
      getIntercept().on('request', (function(_this) {
558
        return function() {
559
          return _this.watch.apply(_this, arguments);
560
        };
561
      })(this));
562
    }
563

564
    AjaxMonitor.prototype.watch = function(arg) {
565
      var request, tracker, type, url;
566
      type = arg.type, request = arg.request, url = arg.url;
567
      if (shouldIgnoreURL(url)) {
568
        return;
569
      }
570
      if (type === 'socket') {
571
        tracker = new SocketRequestTracker(request);
572
      } else {
573
        tracker = new XHRRequestTracker(request);
574
      }
575
      return this.elements.push(tracker);
576
    };
577

578
    return AjaxMonitor;
579

580
  })();
581

582
  XHRRequestTracker = (function() {
583
    function XHRRequestTracker(request) {
584
      var _onreadystatechange, event, l, len1, ref1, size;
585
      this.progress = 0;
586
      if (window.ProgressEvent != null) {
587
        size = null;
588
        request.addEventListener('progress', (function(_this) {
589
          return function(evt) {
590
            if (evt.lengthComputable) {
591
              return _this.progress = 100 * evt.loaded / evt.total;
592
            } else {
593
              return _this.progress = _this.progress + (100 - _this.progress) / 2;
594
            }
595
          };
596
        })(this), false);
597
        ref1 = ['load', 'abort', 'timeout', 'error'];
598
        for (l = 0, len1 = ref1.length; l < len1; l++) {
599
          event = ref1[l];
600
          request.addEventListener(event, (function(_this) {
601
            return function() {
602
              return _this.progress = 100;
603
            };
604
          })(this), false);
605
        }
606
      } else {
607
        _onreadystatechange = request.onreadystatechange;
608
        request.onreadystatechange = (function(_this) {
609
          return function() {
610
            var ref2;
611
            if ((ref2 = request.readyState) === 0 || ref2 === 4) {
612
              _this.progress = 100;
613
            } else if (request.readyState === 3) {
614
              _this.progress = 50;
615
            }
616
            return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0;
617
          };
618
        })(this);
619
      }
620
    }
621

622
    return XHRRequestTracker;
623

624
  })();
625

626
  SocketRequestTracker = (function() {
627
    function SocketRequestTracker(request) {
628
      var event, l, len1, ref1;
629
      this.progress = 0;
630
      ref1 = ['error', 'open'];
631
      for (l = 0, len1 = ref1.length; l < len1; l++) {
632
        event = ref1[l];
633
        request.addEventListener(event, (function(_this) {
634
          return function() {
635
            return _this.progress = 100;
636
          };
637
        })(this), false);
638
      }
639
    }
640

641
    return SocketRequestTracker;
642

643
  })();
644

645
  ElementMonitor = (function() {
646
    function ElementMonitor(options) {
647
      var l, len1, ref1, selector;
648
      if (options == null) {
649
        options = {};
650
      }
651
      this.elements = [];
652
      if (options.selectors == null) {
653
        options.selectors = [];
654
      }
655
      ref1 = options.selectors;
656
      for (l = 0, len1 = ref1.length; l < len1; l++) {
657
        selector = ref1[l];
658
        this.elements.push(new ElementTracker(selector));
659
      }
660
    }
661

662
    return ElementMonitor;
663

664
  })();
665

666
  ElementTracker = (function() {
667
    function ElementTracker(selector1) {
668
      this.selector = selector1;
669
      this.progress = 0;
670
      this.check();
671
    }
672

673
    ElementTracker.prototype.check = function() {
674
      if (document.querySelector(this.selector)) {
675
        return this.done();
676
      } else {
677
        return setTimeout(((function(_this) {
678
          return function() {
679
            return _this.check();
680
          };
681
        })(this)), options.elements.checkInterval);
682
      }
683
    };
684

685
    ElementTracker.prototype.done = function() {
686
      return this.progress = 100;
687
    };
688

689
    return ElementTracker;
690

691
  })();
692

693
  DocumentMonitor = (function() {
694
    DocumentMonitor.prototype.states = {
695
      loading: 0,
696
      interactive: 50,
697
      complete: 100
698
    };
699

700
    function DocumentMonitor() {
701
      var _onreadystatechange, ref1;
702
      this.progress = (ref1 = this.states[document.readyState]) != null ? ref1 : 100;
703
      _onreadystatechange = document.onreadystatechange;
704
      document.onreadystatechange = (function(_this) {
705
        return function() {
706
          if (_this.states[document.readyState] != null) {
707
            _this.progress = _this.states[document.readyState];
708
          }
709
          return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0;
710
        };
711
      })(this);
712
    }
713

714
    return DocumentMonitor;
715

716
  })();
717

718
  EventLagMonitor = (function() {
719
    function EventLagMonitor() {
720
      var avg, interval, last, points, samples;
721
      this.progress = 0;
722
      avg = 0;
723
      samples = [];
724
      points = 0;
725
      last = now();
726
      interval = setInterval((function(_this) {
727
        return function() {
728
          var diff;
729
          diff = now() - last - 50;
730
          last = now();
731
          samples.push(diff);
732
          if (samples.length > options.eventLag.sampleCount) {
733
            samples.shift();
734
          }
735
          avg = avgAmplitude(samples);
736
          if (++points >= options.eventLag.minSamples && avg < options.eventLag.lagThreshold) {
737
            _this.progress = 100;
738
            return clearInterval(interval);
739
          } else {
740
            return _this.progress = 100 * (3 / (avg + 3));
741
          }
742
        };
743
      })(this), 50);
744
    }
745

746
    return EventLagMonitor;
747

748
  })();
749

750
  Scaler = (function() {
751
    function Scaler(source1) {
752
      this.source = source1;
753
      this.last = this.sinceLastUpdate = 0;
754
      this.rate = options.initialRate;
755
      this.catchup = 0;
756
      this.progress = this.lastProgress = 0;
757
      if (this.source != null) {
758
        this.progress = result(this.source, 'progress');
759
      }
760
    }
761

762
    Scaler.prototype.tick = function(frameTime, val) {
763
      var scaling;
764
      if (val == null) {
765
        val = result(this.source, 'progress');
766
      }
767
      if (val >= 100) {
768
        this.done = true;
769
      }
770
      if (val === this.last) {
771
        this.sinceLastUpdate += frameTime;
772
      } else {
773
        if (this.sinceLastUpdate) {
774
          this.rate = (val - this.last) / this.sinceLastUpdate;
775
        }
776
        this.catchup = (val - this.progress) / options.catchupTime;
777
        this.sinceLastUpdate = 0;
778
        this.last = val;
779
      }
780
      if (val > this.progress) {
781
        this.progress += this.catchup * frameTime;
782
      }
783
      scaling = 1 - Math.pow(this.progress / 100, options.easeFactor);
784
      this.progress += scaling * this.rate * frameTime;
785
      this.progress = Math.min(this.lastProgress + options.maxProgressPerFrame, this.progress);
786
      this.progress = Math.max(0, this.progress);
787
      this.progress = Math.min(100, this.progress);
788
      this.lastProgress = this.progress;
789
      return this.progress;
790
    };
791

792
    return Scaler;
793

794
  })();
795

796
  sources = null;
797

798
  scalers = null;
799

800
  bar = null;
801

802
  uniScaler = null;
803

804
  animation = null;
805

806
  cancelAnimation = null;
807

808
  Pace.running = false;
809

810
  handlePushState = function() {
811
    if (options.restartOnPushState) {
812
      return Pace.restart();
813
    }
814
  };
815

816
  if (window.history.pushState != null) {
817
    _pushState = window.history.pushState;
818
    window.history.pushState = function() {
819
      handlePushState();
820
      return _pushState.apply(window.history, arguments);
821
    };
822
  }
823

824
  if (window.history.replaceState != null) {
825
    _replaceState = window.history.replaceState;
826
    window.history.replaceState = function() {
827
      handlePushState();
828
      return _replaceState.apply(window.history, arguments);
829
    };
830
  }
831

832
  SOURCE_KEYS = {
833
    ajax: AjaxMonitor,
834
    elements: ElementMonitor,
835
    document: DocumentMonitor,
836
    eventLag: EventLagMonitor
837
  };
838

839
  (init = function() {
840
    var l, len1, len2, m, ref1, ref2, ref3, type;
841
    Pace.sources = sources = [];
842
    ref1 = ['ajax', 'elements', 'document', 'eventLag'];
843
    for (l = 0, len1 = ref1.length; l < len1; l++) {
844
      type = ref1[l];
845
      if (options[type] !== false) {
846
        sources.push(new SOURCE_KEYS[type](options[type]));
847
      }
848
    }
849
    ref3 = (ref2 = options.extraSources) != null ? ref2 : [];
850
    for (m = 0, len2 = ref3.length; m < len2; m++) {
851
      source = ref3[m];
852
      sources.push(new source(options));
853
    }
854
    Pace.bar = bar = new Bar;
855
    scalers = [];
856
    return uniScaler = new Scaler;
857
  })();
858

859
  Pace.stop = function() {
860
    Pace.trigger('stop');
861
    Pace.running = false;
862
    bar.destroy();
863
    cancelAnimation = true;
864
    if (animation != null) {
865
      if (typeof cancelAnimationFrame === "function") {
866
        cancelAnimationFrame(animation);
867
      }
868
      animation = null;
869
    }
870
    return init();
871
  };
872

873
  Pace.restart = function() {
874
    Pace.trigger('restart');
875
    Pace.stop();
876
    return Pace.start();
877
  };
878

879
  Pace.go = function() {
880
    var start;
881
    Pace.running = true;
882
    bar.render();
883
    start = now();
884
    cancelAnimation = false;
885
    return animation = runAnimation(function(frameTime, enqueueNextFrame) {
886
      var avg, count, done, element, elements, i, j, l, len1, len2, m, ref1, remaining, scaler, scalerList, sum;
887
      remaining = 100 - bar.progress;
888
      count = sum = 0;
889
      done = true;
890
      for (i = l = 0, len1 = sources.length; l < len1; i = ++l) {
891
        source = sources[i];
892
        scalerList = scalers[i] != null ? scalers[i] : scalers[i] = [];
893
        elements = (ref1 = source.elements) != null ? ref1 : [source];
894
        for (j = m = 0, len2 = elements.length; m < len2; j = ++m) {
895
          element = elements[j];
896
          scaler = scalerList[j] != null ? scalerList[j] : scalerList[j] = new Scaler(element);
897
          done &= scaler.done;
898
          if (scaler.done) {
899
            continue;
900
          }
901
          count++;
902
          sum += scaler.tick(frameTime);
903
        }
904
      }
905
      avg = sum / count;
906
      bar.update(uniScaler.tick(frameTime, avg));
907
      if (bar.done() || done || cancelAnimation) {
908
        bar.update(100);
909
        Pace.trigger('done');
910
        return setTimeout(function() {
911
          bar.finish();
912
          Pace.running = false;
913
          return Pace.trigger('hide');
914
        }, Math.max(options.ghostTime, Math.max(options.minTime - (now() - start), 0)));
915
      } else {
916
        return enqueueNextFrame();
917
      }
918
    });
919
  };
920

921
  Pace.start = function(_options) {
922
    var error;
923
    extend(options, _options);
924
    Pace.running = true;
925
    try {
926
      bar.render();
927
    } catch (error) {
928
      NoTargetError = error;
929
    }
930
    if (!document.querySelector('.pace')) {
931
      return setTimeout(Pace.start, 50);
932
    } else {
933
      Pace.trigger('start');
934
      return Pace.go();
935
    }
936
  };
937

938
  if (typeof exports === 'object') {
939
    module.exports = Pace;
940
  }
941

942
  if (options.startOnPageLoad) {
943
    Pace.start();
944
  }
945

946
}).call(this);
947

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.