GPQAPP
946 строк · 26.1 Кб
1(function() {2var 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,3slice = [].slice,4hasProp = {}.hasOwnProperty,5extend1 = 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; },6indexOf = [].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
8defaultOptions = {9catchupTime: 100,10initialRate: .03,11minTime: 250,12ghostTime: 100,13maxProgressPerFrame: 20,14easeFactor: 1.25,15startOnPageLoad: true,16restartOnPushState: true,17restartOnRequestAfter: 500,18target: 'body',19elements: {20checkInterval: 100,21selectors: ['body']22},23eventLag: {24minSamples: 10,25sampleCount: 3,26lagThreshold: 327},28ajax: {29trackMethods: ['GET'],30trackWebSockets: true,31ignoreURLs: []32}33};34
35now = function() {36var ref;37return (ref = typeof performance !== "undefined" && performance !== null ? typeof performance.now === "function" ? performance.now() : void 0 : void 0) != null ? ref : +(new Date);38};39
40requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;41
42cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;43
44if (requestAnimationFrame == null) {45requestAnimationFrame = function(fn) {46return setTimeout(fn, 50);47};48cancelAnimationFrame = function(id) {49return clearTimeout(id);50};51}52
53runAnimation = function(fn) {54var last, tick;55last = now();56tick = function() {57var diff;58diff = now() - last;59if (diff >= 33) {60last = now();61return fn(diff, function() {62return requestAnimationFrame(tick);63});64} else {65return setTimeout(tick, 33 - diff);66}67};68return tick();69};70
71result = function() {72var args, key, obj;73obj = arguments[0], key = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : [];74if (typeof obj[key] === 'function') {75return obj[key].apply(obj, args);76} else {77return obj[key];78}79};80
81extend = function() {82var k, key, len, out, source, sources, val;83out = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];84for (k = 0, len = sources.length; k < len; k++) {85source = sources[k];86if (source) {87for (key in source) {88if (!hasProp.call(source, key)) continue;89val = source[key];90if ((out[key] != null) && typeof out[key] === 'object' && (val != null) && typeof val === 'object') {91extend(out[key], val);92} else {93out[key] = val;94}95}96}97}98return out;99};100
101avgAmplitude = function(arr) {102var count, k, len, sum, v;103sum = count = 0;104for (k = 0, len = arr.length; k < len; k++) {105v = arr[k];106sum += Math.abs(v);107count++;108}109return sum / count;110};111
112getFromDOM = function(key, json) {113var data, e, el, error;114if (key == null) {115key = 'options';116}117if (json == null) {118json = true;119}120el = document.querySelector("[data-pace-" + key + "]");121if (!el) {122return;123}124data = el.getAttribute("data-pace-" + key);125if (!json) {126return data;127}128try {129return JSON.parse(data);130} catch (error) {131e = error;132return typeof console !== "undefined" && console !== null ? console.error("Error parsing inline pace options", e) : void 0;133}134};135
136Evented = (function() {137function Evented() {}138
139Evented.prototype.on = function(event, handler, ctx, once) {140var base;141if (once == null) {142once = false;143}144if (this.bindings == null) {145this.bindings = {};146}147if ((base = this.bindings)[event] == null) {148base[event] = [];149}150return this.bindings[event].push({151handler: handler,152ctx: ctx,153once: once154});155};156
157Evented.prototype.once = function(event, handler, ctx) {158return this.on(event, handler, ctx, true);159};160
161Evented.prototype.off = function(event, handler) {162var i, ref, results;163if (((ref = this.bindings) != null ? ref[event] : void 0) == null) {164return;165}166if (handler == null) {167return delete this.bindings[event];168} else {169i = 0;170results = [];171while (i < this.bindings[event].length) {172if (this.bindings[event][i].handler === handler) {173results.push(this.bindings[event].splice(i, 1));174} else {175results.push(i++);176}177}178return results;179}180};181
182Evented.prototype.trigger = function() {183var args, ctx, event, handler, i, once, ref, ref1, results;184event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];185if ((ref = this.bindings) != null ? ref[event] : void 0) {186i = 0;187results = [];188while (i < this.bindings[event].length) {189ref1 = this.bindings[event][i], handler = ref1.handler, ctx = ref1.ctx, once = ref1.once;190handler.apply(ctx != null ? ctx : this, args);191if (once) {192results.push(this.bindings[event].splice(i, 1));193} else {194results.push(i++);195}196}197return results;198}199};200
201return Evented;202
203})();204
205Pace = window.Pace || {};206
207window.Pace = Pace;208
209extend(Pace, Evented.prototype);210
211options = Pace.options = extend({}, defaultOptions, window.paceOptions, getFromDOM());212
213ref = ['ajax', 'document', 'eventLag', 'elements'];214for (k = 0, len = ref.length; k < len; k++) {215source = ref[k];216if (options[source] === true) {217options[source] = defaultOptions[source];218}219}220
221NoTargetError = (function(superClass) {222extend1(NoTargetError, superClass);223
224function NoTargetError() {225return NoTargetError.__super__.constructor.apply(this, arguments);226}227
228return NoTargetError;229
230})(Error);231
232Bar = (function() {233function Bar() {234this.progress = 0;235}236
237Bar.prototype.getElement = function() {238var targetElement;239if (this.el == null) {240targetElement = document.querySelector(options.target);241if (!targetElement) {242throw new NoTargetError;243}244this.el = document.createElement('div');245this.el.classList.add('pace');246this.el.classList.add('pace-active');247document.body.classList.remove('pace-done');248document.body.classList.add('pace-running');249this.el.innerHTML = '<div class="pace-progress">\n <div class="pace-progress-inner"></div>\n</div>\n<div class="pace-activity"></div>';250if (targetElement.firstChild != null) {251targetElement.insertBefore(this.el, targetElement.firstChild);252} else {253targetElement.appendChild(this.el);254}255}256return this.el;257};258
259Bar.prototype.finish = function() {260var el;261el = this.getElement();262el.classList.remove('pace-active');263el.classList.add('pace-inactive');264document.body.classList.remove('pace-running');265return document.body.classList.add('pace-done');266};267
268Bar.prototype.update = function(prog) {269this.progress = prog;270return this.render();271};272
273Bar.prototype.destroy = function() {274var error;275try {276this.getElement().parentNode.removeChild(this.getElement());277} catch (error) {278NoTargetError = error;279}280return this.el = void 0;281};282
283Bar.prototype.render = function() {284var el, key, l, len1, progressStr, ref1, transform;285if (document.querySelector(options.target) == null) {286return false;287}288el = this.getElement();289transform = "translate3d(" + this.progress + "%, 0, 0)";290ref1 = ['webkitTransform', 'msTransform', 'transform'];291for (l = 0, len1 = ref1.length; l < len1; l++) {292key = ref1[l];293el.children[0].style[key] = transform;294}295if (!this.lastRenderedProgress || this.lastRenderedProgress | 0 !== this.progress | 0) {296el.children[0].setAttribute('data-progress-text', (this.progress | 0) + "%");297if (this.progress >= 100) {298progressStr = '99';299} else {300progressStr = this.progress < 10 ? "0" : "";301progressStr += this.progress | 0;302}303el.children[0].setAttribute('data-progress', "" + progressStr);304}305return this.lastRenderedProgress = this.progress;306};307
308Bar.prototype.done = function() {309return this.progress >= 100;310};311
312return Bar;313
314})();315
316Events = (function() {317function Events() {318this.bindings = {};319}320
321Events.prototype.trigger = function(name, val) {322var binding, l, len1, ref1, results;323if (this.bindings[name] != null) {324ref1 = this.bindings[name];325results = [];326for (l = 0, len1 = ref1.length; l < len1; l++) {327binding = ref1[l];328results.push(binding.call(this, val));329}330return results;331}332};333
334Events.prototype.on = function(name, fn) {335var base;336if ((base = this.bindings)[name] == null) {337base[name] = [];338}339return this.bindings[name].push(fn);340};341
342return Events;343
344})();345
346_XMLHttpRequest = window.XMLHttpRequest;347
348_XDomainRequest = window.XDomainRequest;349
350_WebSocket = window.WebSocket;351
352extendNative = function(to, from) {353var e, error, key, results;354results = [];355for (key in from.prototype) {356try {357if ((to[key] == null) && typeof from[key] !== 'function') {358if (typeof Object.defineProperty === 'function') {359results.push(Object.defineProperty(to, key, {360get: function() {361return from.prototype[key];362},363configurable: true,364enumerable: true365}));366} else {367results.push(to[key] = from.prototype[key]);368}369} else {370results.push(void 0);371}372} catch (error) {373e = error;374}375}376return results;377};378
379ignoreStack = [];380
381Pace.ignore = function() {382var args, fn, ret;383fn = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];384ignoreStack.unshift('ignore');385ret = fn.apply(null, args);386ignoreStack.shift();387return ret;388};389
390Pace.track = function() {391var args, fn, ret;392fn = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];393ignoreStack.unshift('track');394ret = fn.apply(null, args);395ignoreStack.shift();396return ret;397};398
399shouldTrack = function(method) {400var ref1;401if (method == null) {402method = 'GET';403}404if (ignoreStack[0] === 'track') {405return 'force';406}407if (!ignoreStack.length && options.ajax) {408if (method === 'socket' && options.ajax.trackWebSockets) {409return true;410} else if (ref1 = method.toUpperCase(), indexOf.call(options.ajax.trackMethods, ref1) >= 0) {411return true;412}413}414return false;415};416
417RequestIntercept = (function(superClass) {418extend1(RequestIntercept, superClass);419
420function RequestIntercept() {421var monitorXHR;422RequestIntercept.__super__.constructor.apply(this, arguments);423monitorXHR = (function(_this) {424return function(req) {425var _open;426_open = req.open;427return req.open = function(type, url, async) {428if (shouldTrack(type)) {429_this.trigger('request', {430type: type,431url: url,432request: req433});434}435return _open.apply(req, arguments);436};437};438})(this);439window.XMLHttpRequest = function(flags) {440var req;441req = new _XMLHttpRequest(flags);442monitorXHR(req);443return req;444};445try {446extendNative(window.XMLHttpRequest, _XMLHttpRequest);447} catch (undefined) {}448if (_XDomainRequest != null) {449window.XDomainRequest = function() {450var req;451req = new _XDomainRequest;452monitorXHR(req);453return req;454};455try {456extendNative(window.XDomainRequest, _XDomainRequest);457} catch (undefined) {}458}459if ((_WebSocket != null) && options.ajax.trackWebSockets) {460window.WebSocket = (function(_this) {461return function(url, protocols) {462var req;463if (protocols != null) {464req = new _WebSocket(url, protocols);465} else {466req = new _WebSocket(url);467}468if (shouldTrack('socket')) {469_this.trigger('request', {470type: 'socket',471url: url,472protocols: protocols,473request: req474});475}476return req;477};478})(this);479try {480extendNative(window.WebSocket, _WebSocket);481} catch (undefined) {}482}483}484
485return RequestIntercept;486
487})(Events);488
489_intercept = null;490
491getIntercept = function() {492if (_intercept == null) {493_intercept = new RequestIntercept;494}495return _intercept;496};497
498shouldIgnoreURL = function(url) {499var l, len1, pattern, ref1;500ref1 = options.ajax.ignoreURLs;501for (l = 0, len1 = ref1.length; l < len1; l++) {502pattern = ref1[l];503if (typeof pattern === 'string') {504if (url.indexOf(pattern) !== -1) {505return true;506}507} else {508if (pattern.test(url)) {509return true;510}511}512}513return false;514};515
516getIntercept().on('request', function(arg) {517var after, args, request, type, url;518type = arg.type, request = arg.request, url = arg.url;519if (shouldIgnoreURL(url)) {520return;521}522if (!Pace.running && (options.restartOnRequestAfter !== false || shouldTrack(type) === 'force')) {523args = arguments;524after = options.restartOnRequestAfter || 0;525if (typeof after === 'boolean') {526after = 0;527}528return setTimeout(function() {529var l, len1, ref1, ref2, results, stillActive;530if (type === 'socket') {531stillActive = request.readyState < 2;532} else {533stillActive = (0 < (ref1 = request.readyState) && ref1 < 4);534}535if (stillActive) {536Pace.restart();537ref2 = Pace.sources;538results = [];539for (l = 0, len1 = ref2.length; l < len1; l++) {540source = ref2[l];541if (source instanceof AjaxMonitor) {542source.watch.apply(source, args);543break;544} else {545results.push(void 0);546}547}548return results;549}550}, after);551}552});553
554AjaxMonitor = (function() {555function AjaxMonitor() {556this.elements = [];557getIntercept().on('request', (function(_this) {558return function() {559return _this.watch.apply(_this, arguments);560};561})(this));562}563
564AjaxMonitor.prototype.watch = function(arg) {565var request, tracker, type, url;566type = arg.type, request = arg.request, url = arg.url;567if (shouldIgnoreURL(url)) {568return;569}570if (type === 'socket') {571tracker = new SocketRequestTracker(request);572} else {573tracker = new XHRRequestTracker(request);574}575return this.elements.push(tracker);576};577
578return AjaxMonitor;579
580})();581
582XHRRequestTracker = (function() {583function XHRRequestTracker(request) {584var _onreadystatechange, event, l, len1, ref1, size;585this.progress = 0;586if (window.ProgressEvent != null) {587size = null;588request.addEventListener('progress', (function(_this) {589return function(evt) {590if (evt.lengthComputable) {591return _this.progress = 100 * evt.loaded / evt.total;592} else {593return _this.progress = _this.progress + (100 - _this.progress) / 2;594}595};596})(this), false);597ref1 = ['load', 'abort', 'timeout', 'error'];598for (l = 0, len1 = ref1.length; l < len1; l++) {599event = ref1[l];600request.addEventListener(event, (function(_this) {601return function() {602return _this.progress = 100;603};604})(this), false);605}606} else {607_onreadystatechange = request.onreadystatechange;608request.onreadystatechange = (function(_this) {609return function() {610var ref2;611if ((ref2 = request.readyState) === 0 || ref2 === 4) {612_this.progress = 100;613} else if (request.readyState === 3) {614_this.progress = 50;615}616return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0;617};618})(this);619}620}621
622return XHRRequestTracker;623
624})();625
626SocketRequestTracker = (function() {627function SocketRequestTracker(request) {628var event, l, len1, ref1;629this.progress = 0;630ref1 = ['error', 'open'];631for (l = 0, len1 = ref1.length; l < len1; l++) {632event = ref1[l];633request.addEventListener(event, (function(_this) {634return function() {635return _this.progress = 100;636};637})(this), false);638}639}640
641return SocketRequestTracker;642
643})();644
645ElementMonitor = (function() {646function ElementMonitor(options) {647var l, len1, ref1, selector;648if (options == null) {649options = {};650}651this.elements = [];652if (options.selectors == null) {653options.selectors = [];654}655ref1 = options.selectors;656for (l = 0, len1 = ref1.length; l < len1; l++) {657selector = ref1[l];658this.elements.push(new ElementTracker(selector));659}660}661
662return ElementMonitor;663
664})();665
666ElementTracker = (function() {667function ElementTracker(selector1) {668this.selector = selector1;669this.progress = 0;670this.check();671}672
673ElementTracker.prototype.check = function() {674if (document.querySelector(this.selector)) {675return this.done();676} else {677return setTimeout(((function(_this) {678return function() {679return _this.check();680};681})(this)), options.elements.checkInterval);682}683};684
685ElementTracker.prototype.done = function() {686return this.progress = 100;687};688
689return ElementTracker;690
691})();692
693DocumentMonitor = (function() {694DocumentMonitor.prototype.states = {695loading: 0,696interactive: 50,697complete: 100698};699
700function DocumentMonitor() {701var _onreadystatechange, ref1;702this.progress = (ref1 = this.states[document.readyState]) != null ? ref1 : 100;703_onreadystatechange = document.onreadystatechange;704document.onreadystatechange = (function(_this) {705return function() {706if (_this.states[document.readyState] != null) {707_this.progress = _this.states[document.readyState];708}709return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0;710};711})(this);712}713
714return DocumentMonitor;715
716})();717
718EventLagMonitor = (function() {719function EventLagMonitor() {720var avg, interval, last, points, samples;721this.progress = 0;722avg = 0;723samples = [];724points = 0;725last = now();726interval = setInterval((function(_this) {727return function() {728var diff;729diff = now() - last - 50;730last = now();731samples.push(diff);732if (samples.length > options.eventLag.sampleCount) {733samples.shift();734}735avg = avgAmplitude(samples);736if (++points >= options.eventLag.minSamples && avg < options.eventLag.lagThreshold) {737_this.progress = 100;738return clearInterval(interval);739} else {740return _this.progress = 100 * (3 / (avg + 3));741}742};743})(this), 50);744}745
746return EventLagMonitor;747
748})();749
750Scaler = (function() {751function Scaler(source1) {752this.source = source1;753this.last = this.sinceLastUpdate = 0;754this.rate = options.initialRate;755this.catchup = 0;756this.progress = this.lastProgress = 0;757if (this.source != null) {758this.progress = result(this.source, 'progress');759}760}761
762Scaler.prototype.tick = function(frameTime, val) {763var scaling;764if (val == null) {765val = result(this.source, 'progress');766}767if (val >= 100) {768this.done = true;769}770if (val === this.last) {771this.sinceLastUpdate += frameTime;772} else {773if (this.sinceLastUpdate) {774this.rate = (val - this.last) / this.sinceLastUpdate;775}776this.catchup = (val - this.progress) / options.catchupTime;777this.sinceLastUpdate = 0;778this.last = val;779}780if (val > this.progress) {781this.progress += this.catchup * frameTime;782}783scaling = 1 - Math.pow(this.progress / 100, options.easeFactor);784this.progress += scaling * this.rate * frameTime;785this.progress = Math.min(this.lastProgress + options.maxProgressPerFrame, this.progress);786this.progress = Math.max(0, this.progress);787this.progress = Math.min(100, this.progress);788this.lastProgress = this.progress;789return this.progress;790};791
792return Scaler;793
794})();795
796sources = null;797
798scalers = null;799
800bar = null;801
802uniScaler = null;803
804animation = null;805
806cancelAnimation = null;807
808Pace.running = false;809
810handlePushState = function() {811if (options.restartOnPushState) {812return Pace.restart();813}814};815
816if (window.history.pushState != null) {817_pushState = window.history.pushState;818window.history.pushState = function() {819handlePushState();820return _pushState.apply(window.history, arguments);821};822}823
824if (window.history.replaceState != null) {825_replaceState = window.history.replaceState;826window.history.replaceState = function() {827handlePushState();828return _replaceState.apply(window.history, arguments);829};830}831
832SOURCE_KEYS = {833ajax: AjaxMonitor,834elements: ElementMonitor,835document: DocumentMonitor,836eventLag: EventLagMonitor837};838
839(init = function() {840var l, len1, len2, m, ref1, ref2, ref3, type;841Pace.sources = sources = [];842ref1 = ['ajax', 'elements', 'document', 'eventLag'];843for (l = 0, len1 = ref1.length; l < len1; l++) {844type = ref1[l];845if (options[type] !== false) {846sources.push(new SOURCE_KEYS[type](options[type]));847}848}849ref3 = (ref2 = options.extraSources) != null ? ref2 : [];850for (m = 0, len2 = ref3.length; m < len2; m++) {851source = ref3[m];852sources.push(new source(options));853}854Pace.bar = bar = new Bar;855scalers = [];856return uniScaler = new Scaler;857})();858
859Pace.stop = function() {860Pace.trigger('stop');861Pace.running = false;862bar.destroy();863cancelAnimation = true;864if (animation != null) {865if (typeof cancelAnimationFrame === "function") {866cancelAnimationFrame(animation);867}868animation = null;869}870return init();871};872
873Pace.restart = function() {874Pace.trigger('restart');875Pace.stop();876return Pace.start();877};878
879Pace.go = function() {880var start;881Pace.running = true;882bar.render();883start = now();884cancelAnimation = false;885return animation = runAnimation(function(frameTime, enqueueNextFrame) {886var avg, count, done, element, elements, i, j, l, len1, len2, m, ref1, remaining, scaler, scalerList, sum;887remaining = 100 - bar.progress;888count = sum = 0;889done = true;890for (i = l = 0, len1 = sources.length; l < len1; i = ++l) {891source = sources[i];892scalerList = scalers[i] != null ? scalers[i] : scalers[i] = [];893elements = (ref1 = source.elements) != null ? ref1 : [source];894for (j = m = 0, len2 = elements.length; m < len2; j = ++m) {895element = elements[j];896scaler = scalerList[j] != null ? scalerList[j] : scalerList[j] = new Scaler(element);897done &= scaler.done;898if (scaler.done) {899continue;900}901count++;902sum += scaler.tick(frameTime);903}904}905avg = sum / count;906bar.update(uniScaler.tick(frameTime, avg));907if (bar.done() || done || cancelAnimation) {908bar.update(100);909Pace.trigger('done');910return setTimeout(function() {911bar.finish();912Pace.running = false;913return Pace.trigger('hide');914}, Math.max(options.ghostTime, Math.max(options.minTime - (now() - start), 0)));915} else {916return enqueueNextFrame();917}918});919};920
921Pace.start = function(_options) {922var error;923extend(options, _options);924Pace.running = true;925try {926bar.render();927} catch (error) {928NoTargetError = error;929}930if (!document.querySelector('.pace')) {931return setTimeout(Pace.start, 50);932} else {933Pace.trigger('start');934return Pace.go();935}936};937
938if (typeof exports === 'object') {939module.exports = Pace;940}941
942if (options.startOnPageLoad) {943Pace.start();944}945
946}).call(this);947