<commit_before>/*
 * Copyright © 2016-2019 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
export default angular.module('thingsboard.api.attribute', [])
    .factory('attributeService', AttributeService)
    .name;

/*@ngInject*/
function AttributeService($http, $q, $filter, types, telemetryWebsocketService) {

    var entityAttributesSubscriptionMap = {};

    var service = {
        getEntityKeys: getEntityKeys,
        getEntityTimeseriesValues: getEntityTimeseriesValues,
        getEntityAttributesValues: getEntityAttributesValues,
        getEntityAttributes: getEntityAttributes,
        subscribeForEntityAttributes: subscribeForEntityAttributes,
        unsubscribeForEntityAttributes: unsubscribeForEntityAttributes,
        saveEntityAttributes: saveEntityAttributes,
        deleteEntityAttributes: deleteEntityAttributes,
        saveEntityTimeseries: saveEntityTimeseries,
        deleteEntityTimeseries: deleteEntityTimeseries
    }

    return service;

    function getEntityKeys(entityType, entityId, query, type, config) {
        var deferred = $q.defer();
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/keys/';
        if (type === types.dataKeyType.timeseries) {
            url += 'timeseries';
        } else if (type === types.dataKeyType.attribute) {
            url += 'attributes';
        }
        $http.get(url, config).then(function success(response) {
            var result = [];
            if (response.data) {
                if (query) {
                    var dataKeys = response.data;
                    var lowercaseQuery = angular.lowercase(query);
                    for (var i=0; i<dataKeys.length;i++) {
                        if (angular.lowercase(dataKeys[i]).indexOf(lowercaseQuery) === 0) {
                            result.push(dataKeys[i]);
                        }
                    }
                } else {
                    result = response.data;
                }
            }
            deferred.resolve(result);
        }, function fail(response) {
            deferred.reject(response.data);
        });
        return deferred.promise;
    }

    function getEntityTimeseriesValues(entityType, entityId, keys, startTs, endTs, limit) {
        var deferred = $q.defer();
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/values/timeseries';
        url += '?keys=' + keys;
        url += '&startTs=' + startTs;
        url += '&endTs=' + endTs;
        if (angular.isDefined(limit)) {
            url += '&limit=' + limit;
        }
        $http.get(url, null).then(function success(response) {
            deferred.resolve(response.data);
        }, function fail(response) {
            deferred.reject(response.data);
        });
        return deferred.promise;
    }

    function getEntityAttributesValues(entityType, entityId, attributeScope, keys, config) {
        var deferred = $q.defer();
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/values/attributes/' + attributeScope;
        if (keys && keys.length) {
            url += '?keys=' + keys;
        }
        $http.get(url, config).then(function success(response) {
            deferred.resolve(response.data);
        }, function fail() {
            deferred.reject();
        });
        return deferred.promise;
    }

    function processAttributes(attributes, query, deferred, successCallback, update, apply) {
        attributes = $filter('orderBy')(attributes, query.order);
        if (query.search != null) {
            attributes = $filter('filter')(attributes, {key: query.search});
        }
        var responseData = {
            count: attributes.length
        }
        var startIndex = query.limit * (query.page - 1);
        responseData.data = attributes.slice(startIndex, startIndex + query.limit);
        successCallback(responseData, update, apply);
        if (deferred) {
            deferred.resolve();
        }
    }

    function getEntityAttributes(entityType, entityId, attributeScope, query, successCallback, config) {
        var deferred = $q.defer();
        var subscriptionId = entityType + entityId + attributeScope;
        var eas = entityAttributesSubscriptionMap[subscriptionId];
        if (eas) {
            if (eas.attributes) {
                processAttributes(eas.attributes, query, deferred, successCallback);
                eas.subscriptionCallback = function(attributes) {
                    processAttributes(attributes, query, null, successCallback, true, true);
                }
            } else {
                eas.subscriptionCallback = function(attributes) {
                    processAttributes(attributes, query, deferred, successCallback, false, true);
                    eas.subscriptionCallback = function(attributes) {
                        processAttributes(attributes, query, null, successCallback, true, true);
                    }
                }
            }
        } else {
            var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/values/attributes/' + attributeScope;
            $http.get(url, config).then(function success(response) {
                processAttributes(response.data, query, deferred, successCallback);
            }, function fail() {
                deferred.reject();
            });
        }
        return deferred;
    }

    function onSubscriptionData(data, subscriptionId) {
        var entityAttributesSubscription = entityAttributesSubscriptionMap[subscriptionId];
        if (entityAttributesSubscription) {
            if (!entityAttributesSubscription.attributes) {
                entityAttributesSubscription.attributes = [];
                entityAttributesSubscription.keys = {};
            }
            var attributes = entityAttributesSubscription.attributes;
            var keys = entityAttributesSubscription.keys;
            for (var key in data) {
                var index = keys[key];
                var attribute;
                if (index > -1) {
                    attribute = attributes[index];
                } else {
                    attribute = {
                        key: key
                    };
                    index = attributes.push(attribute)-1;
                    keys[key] = index;
                }
                var attrData = data[key][0];
                attribute.lastUpdateTs = attrData[0];
                attribute.value = attrData[1];
            }
            if (entityAttributesSubscription.subscriptionCallback) {
                entityAttributesSubscription.subscriptionCallback(attributes);
            }
        }
    }

    function subscribeForEntityAttributes(entityType, entityId, attributeScope) {
        var subscriptionId = entityType + entityId + attributeScope;
        var entityAttributesSubscription = entityAttributesSubscriptionMap[subscriptionId];
        if (!entityAttributesSubscription) {
            var subscriptionCommand = {
                entityType: entityType,
                entityId: entityId,
                scope: attributeScope
            };

            var type = attributeScope === types.latestTelemetry.value ?
                types.dataKeyType.timeseries : types.dataKeyType.attribute;

            var subscriber = {
                subscriptionCommands: [subscriptionCommand],
                type: type,
                onData: function (data) {
                    if (data.data) {
                        onSubscriptionData(data.data, subscriptionId);
                    }
                }
            };
            entityAttributesSubscription = {
                subscriber: subscriber,
                attributes: null
            };
            entityAttributesSubscriptionMap[subscriptionId] = entityAttributesSubscription;
            telemetryWebsocketService.subscribe(subscriber);
        }
        return subscriptionId;
    }

    function unsubscribeForEntityAttributes(subscriptionId) {
        var entityAttributesSubscription = entityAttributesSubscriptionMap[subscriptionId];
        if (entityAttributesSubscription) {
            telemetryWebsocketService.unsubscribe(entityAttributesSubscription.subscriber);
            delete entityAttributesSubscriptionMap[subscriptionId];
        }
    }

    function saveEntityAttributes(entityType, entityId, attributeScope, attributes, config) {
        config = config || {};
        var deferred = $q.defer();
        var attributesData = {};
        var deleteAttributes = [];
        for (var a=0; a<attributes.length;a++) {
            if (angular.isDefined(attributes[a].value) && attributes[a].value !== null) {
                attributesData[attributes[a].key] = attributes[a].value;
            } else {
                deleteAttributes.push(attributes[a]);
            }
        }
        var deleteEntityAttributesPromise;
        if (deleteAttributes.length) {
            deleteEntityAttributesPromise = deleteEntityAttributes(entityType, entityId, attributeScope, deleteAttributes);
        }
        if (Object.keys(attributesData).length) {
            var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/' + attributeScope;
            $http.post(url, attributesData, config).then(function success(response) {
                if (deleteEntityAttributesPromise) {
                    deleteEntityAttributesPromise.then(
                        function success() {
                            deferred.resolve(response.data);
                        },
                        function fail() {
                            deferred.reject();
                        }
                    )
                } else {
                    deferred.resolve(response.data);
                }
            }, function fail() {
                deferred.reject();
            });
        } else if (deleteEntityAttributesPromise) {
            deleteEntityAttributesPromise.then(
                function success() {
                    deferred.resolve();
                },
                function fail() {
                    deferred.reject();
                }
            )
        } else {
            deferred.resolve();
        }
        return deferred.promise;
    }

    function saveEntityTimeseries(entityType, entityId, timeseriesScope, timeseries, config) {
        config = config || {};
        var deferred = $q.defer();
        var timeseriesData = {};
        var deleteTimeseries = [];
        for (var a=0; a<timeseries.length;a++) {
            if (angular.isDefined(timeseries[a].value) && timeseries[a].value !== null) {
                timeseriesData[timeseries[a].key] = timeseries[a].value;
            } else {
                deleteTimeseries.push(timeseries[a]);
            }
        }
        var deleteEntityTimeseriesPromise;
        if (deleteTimeseries.length) {
            deleteEntityTimeseriesPromise = deleteEntityTimeseries(entityType, entityId, deleteTimeseries, config, true);
        }
        if (Object.keys(timeseriesData).length) {
            var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/timeseries/' + timeseriesScope;
            $http.post(url, timeseriesData, config).then(function success(response) {
                if (deleteEntityTimeseriesPromise) {
                    deleteEntityTimeseriesPromise.then(
                        function success() {
                            deferred.resolve(response.data);
                        },
                        function fail() {
                            deferred.reject();
                        }
                    )
                } else {
                    deferred.resolve(response.data);
                }
            }, function fail() {
                deferred.reject();
            });
        } else if (deleteEntityTimeseriesPromise) {
            deleteEntityTimeseriesPromise.then(
                function success() {
                    deferred.resolve();
                },
                function fail() {
                    deferred.reject();
                }
            )
        } else {
            deferred.resolve();
        }
        return deferred.promise;
    }

    function deleteEntityAttributes(entityType, entityId, attributeScope, attributes, config) {
        config = config || {};
        var deferred = $q.defer();
        var keys = '';
        for (var i = 0; i < attributes.length; i++) {
            if (i > 0) {
                keys += ',';
            }
            keys += attributes[i].key;
        }
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/' + attributeScope + '?keys=' + keys;
        $http.delete(url, config).then(function success() {
            deferred.resolve();
        }, function fail() {
            deferred.reject();
        });
        return deferred.promise;
    }

    function deleteEntityTimeseries(entityType, entityId, timeseries, config, deleteAllDataForKeys) {
        config = config || {};
        deleteAllDataForKeys = deleteAllDataForKeys || false;
        var deferred = $q.defer();
        var keys = '';
        for (var i = 0; i < timeseries.length; i++) {
            if (i > 0) {
                keys += ',';
            }
            keys += timeseries[i].key;
        }
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/timeseries/delete' +
            '?keys=' + keys
            + '&deleteAllDataForKeys=' + deleteAllDataForKeys;
        $http.delete(url, config).then(function success() {
            deferred.resolve();
        }, function fail() {
            deferred.reject();
        });
        return deferred.promise;
    }

}
<commit_msg>Refactoring<commit_after>/*
 * Copyright © 2016-2019 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
export default angular.module('thingsboard.api.attribute', [])
    .factory('attributeService', AttributeService)
    .name;

/*@ngInject*/
function AttributeService($http, $q, $filter, types, telemetryWebsocketService) {

    var entityAttributesSubscriptionMap = {};

    var service = {
        getEntityKeys: getEntityKeys,
        getEntityTimeseriesValues: getEntityTimeseriesValues,
        getEntityAttributesValues: getEntityAttributesValues,
        getEntityAttributes: getEntityAttributes,
        subscribeForEntityAttributes: subscribeForEntityAttributes,
        unsubscribeForEntityAttributes: unsubscribeForEntityAttributes,
        saveEntityAttributes: saveEntityAttributes,
        deleteEntityAttributes: deleteEntityAttributes,
        saveEntityTimeseries: saveEntityTimeseries,
        deleteEntityTimeseries: deleteEntityTimeseries
    }

    return service;

    function getEntityKeys(entityType, entityId, query, type, config) {
        var deferred = $q.defer();
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/keys/';
        if (type === types.dataKeyType.timeseries) {
            url += 'timeseries';
        } else if (type === types.dataKeyType.attribute) {
            url += 'attributes';
        }
        $http.get(url, config).then(function success(response) {
            var result = [];
            if (response.data) {
                if (query) {
                    var dataKeys = response.data;
                    var lowercaseQuery = angular.lowercase(query);
                    for (var i=0; i<dataKeys.length;i++) {
                        if (angular.lowercase(dataKeys[i]).indexOf(lowercaseQuery) === 0) {
                            result.push(dataKeys[i]);
                        }
                    }
                } else {
                    result = response.data;
                }
            }
            deferred.resolve(result);
        }, function fail(response) {
            deferred.reject(response.data);
        });
        return deferred.promise;
    }

    function getEntityTimeseriesValues(entityType, entityId, keys, startTs, endTs, limit) {
        var deferred = $q.defer();
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/values/timeseries';
        url += '?keys=' + keys;
        url += '&startTs=' + startTs;
        url += '&endTs=' + endTs;
        if (angular.isDefined(limit)) {
            url += '&limit=' + limit;
        }
        $http.get(url, null).then(function success(response) {
            deferred.resolve(response.data);
        }, function fail(response) {
            deferred.reject(response.data);
        });
        return deferred.promise;
    }

    function getEntityAttributesValues(entityType, entityId, attributeScope, keys, config) {
        var deferred = $q.defer();
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/values/attributes/' + attributeScope;
        if (keys && keys.length) {
            url += '?keys=' + keys;
        }
        $http.get(url, config).then(function success(response) {
            deferred.resolve(response.data);
        }, function fail() {
            deferred.reject();
        });
        return deferred.promise;
    }

    function processAttributes(attributes, query, deferred, successCallback, update, apply) {
        attributes = $filter('orderBy')(attributes, query.order);
        if (query.search != null) {
            attributes = $filter('filter')(attributes, {key: query.search});
        }
        var responseData = {
            count: attributes.length
        }
        var startIndex = query.limit * (query.page - 1);
        responseData.data = attributes.slice(startIndex, startIndex + query.limit);
        successCallback(responseData, update, apply);
        if (deferred) {
            deferred.resolve();
        }
    }

    function getEntityAttributes(entityType, entityId, attributeScope, query, successCallback, config) {
        var deferred = $q.defer();
        var subscriptionId = entityType + entityId + attributeScope;
        var eas = entityAttributesSubscriptionMap[subscriptionId];
        if (eas) {
            if (eas.attributes) {
                processAttributes(eas.attributes, query, deferred, successCallback);
                eas.subscriptionCallback = function(attributes) {
                    processAttributes(attributes, query, null, successCallback, true, true);
                }
            } else {
                eas.subscriptionCallback = function(attributes) {
                    processAttributes(attributes, query, deferred, successCallback, false, true);
                    eas.subscriptionCallback = function(attributes) {
                        processAttributes(attributes, query, null, successCallback, true, true);
                    }
                }
            }
        } else {
            var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/values/attributes/' + attributeScope;
            $http.get(url, config).then(function success(response) {
                processAttributes(response.data, query, deferred, successCallback);
            }, function fail() {
                deferred.reject();
            });
        }
        return deferred;
    }

    function onSubscriptionData(data, subscriptionId) {
        var entityAttributesSubscription = entityAttributesSubscriptionMap[subscriptionId];
        if (entityAttributesSubscription) {
            if (!entityAttributesSubscription.attributes) {
                entityAttributesSubscription.attributes = [];
                entityAttributesSubscription.keys = {};
            }
            var attributes = entityAttributesSubscription.attributes;
            var keys = entityAttributesSubscription.keys;
            for (var key in data) {
                var index = keys[key];
                var attribute;
                if (index > -1) {
                    attribute = attributes[index];
                } else {
                    attribute = {
                        key: key
                    };
                    index = attributes.push(attribute)-1;
                    keys[key] = index;
                }
                var attrData = data[key][0];
                attribute.lastUpdateTs = attrData[0];
                attribute.value = attrData[1];
            }
            if (entityAttributesSubscription.subscriptionCallback) {
                entityAttributesSubscription.subscriptionCallback(attributes);
            }
        }
    }

    function subscribeForEntityAttributes(entityType, entityId, attributeScope) {
        var subscriptionId = entityType + entityId + attributeScope;
        var entityAttributesSubscription = entityAttributesSubscriptionMap[subscriptionId];
        if (!entityAttributesSubscription) {
            var subscriptionCommand = {
                entityType: entityType,
                entityId: entityId,
                scope: attributeScope
            };

            var type = attributeScope === types.latestTelemetry.value ?
                types.dataKeyType.timeseries : types.dataKeyType.attribute;

            var subscriber = {
                subscriptionCommands: [subscriptionCommand],
                type: type,
                onData: function (data) {
                    if (data.data) {
                        onSubscriptionData(data.data, subscriptionId);
                    }
                }
            };
            entityAttributesSubscription = {
                subscriber: subscriber,
                attributes: null
            };
            entityAttributesSubscriptionMap[subscriptionId] = entityAttributesSubscription;
            telemetryWebsocketService.subscribe(subscriber);
        }
        return subscriptionId;
    }

    function unsubscribeForEntityAttributes(subscriptionId) {
        var entityAttributesSubscription = entityAttributesSubscriptionMap[subscriptionId];
        if (entityAttributesSubscription) {
            telemetryWebsocketService.unsubscribe(entityAttributesSubscription.subscriber);
            delete entityAttributesSubscriptionMap[subscriptionId];
        }
    }

    function saveEntityAttributes(entityType, entityId, attributeScope, attributes, config) {
        config = config || {};
        var deferred = $q.defer();
        var attributesData = {};
        var deleteAttributes = [];
        for (var a=0; a<attributes.length;a++) {
            if (angular.isDefined(attributes[a].value) && attributes[a].value !== null) {
                attributesData[attributes[a].key] = attributes[a].value;
            } else {
                deleteAttributes.push(attributes[a]);
            }
        }
        var deleteEntityAttributesPromise;
        if (deleteAttributes.length) {
            deleteEntityAttributesPromise = deleteEntityAttributes(entityType, entityId, attributeScope, deleteAttributes);
        }
        if (Object.keys(attributesData).length) {
            var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/' + attributeScope;
            $http.post(url, attributesData, config).then(function success(response) {
                if (deleteEntityAttributesPromise) {
                    deleteEntityAttributesPromise.then(
                        function success() {
                            deferred.resolve(response.data);
                        },
                        function fail() {
                            deferred.reject();
                        }
                    )
                } else {
                    deferred.resolve(response.data);
                }
            }, function fail() {
                deferred.reject();
            });
        } else if (deleteEntityAttributesPromise) {
            deleteEntityAttributesPromise.then(
                function success() {
                    deferred.resolve();
                },
                function fail() {
                    deferred.reject();
                }
            )
        } else {
            deferred.resolve();
        }
        return deferred.promise;
    }

    function saveEntityTimeseries(entityType, entityId, timeseriesScope, timeseries, config) {
        config = config || {};
        var deferred = $q.defer();
        var timeseriesData = {};
        var deleteTimeseries = [];
        for (var a=0; a<timeseries.length;a++) {
            if (angular.isDefined(timeseries[a].value) && timeseries[a].value !== null) {
                timeseriesData[timeseries[a].key] = timeseries[a].value;
            } else {
                deleteTimeseries.push(timeseries[a]);
            }
        }
        var deleteEntityTimeseriesPromise;
        if (deleteTimeseries.length) {
            deleteEntityTimeseriesPromise = deleteEntityTimeseries(entityType, entityId, deleteTimeseries, config, true);
        }
        if (Object.keys(timeseriesData).length) {
            var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/timeseries/' + timeseriesScope;
            $http.post(url, timeseriesData, config).then(function success(response) {
                if (deleteEntityTimeseriesPromise) {
                    deleteEntityTimeseriesPromise.then(
                        function success() {
                            deferred.resolve(response.data);
                        },
                        function fail() {
                            deferred.reject();
                        }
                    )
                } else {
                    deferred.resolve(response.data);
                }
            }, function fail() {
                deferred.reject();
            });
        } else if (deleteEntityTimeseriesPromise) {
            deleteEntityTimeseriesPromise.then(
                function success() {
                    deferred.resolve();
                },
                function fail() {
                    deferred.reject();
                }
            )
        } else {
            deferred.resolve();
        }
        return deferred.promise;
    }

    function deleteEntityAttributes(entityType, entityId, attributeScope, attributes, config) {
        config = config || {};
        var deferred = $q.defer();
        var keys = '';
        for (var i = 0; i < attributes.length; i++) {
            if (i > 0) {
                keys += ',';
            }
            keys += attributes[i].key;
        }
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/' + attributeScope + '?keys=' + keys;
        $http.delete(url, config).then(function success() {
            deferred.resolve();
        }, function fail() {
            deferred.reject();
        });
        return deferred.promise;
    }

    function deleteEntityTimeseries(entityType, entityId, timeseries, config, deleteAllDataForKeys) {
        config = config || {};
        deleteAllDataForKeys = deleteAllDataForKeys || false;
        var deferred = $q.defer();
        var keys = '';
        for (var i = 0; i < timeseries.length; i++) {
            if (i > 0) {
                keys += ',';
            }
            keys += timeseries[i].key;
        }
        var url = '/api/plugins/telemetry/' + entityType + '/' + entityId + '/timeseries/delete' +
            '?keys=' + keys +
            '&deleteAllDataForKeys=' + deleteAllDataForKeys;
        $http.delete(url, config).then(function success() {
            deferred.resolve();
        }, function fail() {
            deferred.reject();
        });
        return deferred.promise;
    }

}
<|endoftext|>


<commit_before>import Vue from 'vue'

import HistoryMixin from '../../mixins/history.js'
import ModelToggleMixin from '../../mixins/model-toggle.js'
import PortalMixin from '../../mixins/portal.js'
import PreventScrollMixin from '../../mixins/prevent-scroll.js'

import { childHasFocus } from '../../utils/dom.js'
import EscapeKey from '../../utils/escape-key.js'
import { slot } from '../../utils/slot.js'
import { create, stop } from '../../utils/event.js'
import { cache } from '../../utils/vm.js'

let maximizedModals = 0

const positionClass = {
  standard: 'fixed-full flex-center',
  top: 'fixed-top justify-center',
  bottom: 'fixed-bottom justify-center',
  right: 'fixed-right items-center',
  left: 'fixed-left items-center'
}

const transitions = {
  standard: ['scale', 'scale'],
  top: ['slide-down', 'slide-up'],
  bottom: ['slide-up', 'slide-down'],
  right: ['slide-left', 'slide-right'],
  left: ['slide-right', 'slide-left']
}

export default Vue.extend({
  name: 'QDialog',

  mixins: [ HistoryMixin, ModelToggleMixin, PortalMixin, PreventScrollMixin ],

  props: {
    persistent: Boolean,
    autoClose: Boolean,

    noEscDismiss: Boolean,
    noBackdropDismiss: Boolean,
    noRouteDismiss: Boolean,
    noRefocus: Boolean,
    noFocus: Boolean,

    seamless: Boolean,

    maximized: Boolean,
    fullWidth: Boolean,
    fullHeight: Boolean,

    square: Boolean,

    position: {
      type: String,
      default: 'standard',
      validator: val => val === 'standard' ||
        ['top', 'bottom', 'left', 'right'].includes(val)
    },

    transitionShow: String,
    transitionHide: String
  },

  data () {
    return {
      transitionState: this.showing
    }
  },

  watch: {
    showing (val) {
      if (this.transitionShowComputed !== this.transitionHideComputed) {
        this.$nextTick(() => {
          this.transitionState = val
        })
      }
    },

    maximized (newV, oldV) {
      if (this.showing === true) {
        this.__updateState(false, oldV)
        this.__updateState(true, newV)
      }
    },

    useBackdrop (v) {
      this.__preventScroll(v)
      this.__preventFocusout(v)
    }
  },

  computed: {
    classes () {
      return `q-dialog__inner--${this.maximized === true ? 'maximized' : 'minimized'} ` +
        `q-dialog__inner--${this.position} ${positionClass[this.position]}` +
        (this.fullWidth === true ? ' q-dialog__inner--fullwidth' : '') +
        (this.fullHeight === true ? ' q-dialog__inner--fullheight' : '') +
        (this.square === true ? ' q-dialog__inner--square' : '')
    },

    transitionShowComputed () {
      return 'q-transition--' + (this.transitionShow === void 0 ? transitions[this.position][0] : this.transitionShow)
    },

    transitionHideComputed () {
      return 'q-transition--' + (this.transitionHide === void 0 ? transitions[this.position][1] : this.transitionHide)
    },

    transition () {
      return this.transitionState === true
        ? this.transitionHideComputed
        : this.transitionShowComputed
    },

    useBackdrop () {
      return this.showing === true && this.seamless !== true
    },

    hideOnRouteChange () {
      return this.persistent !== true &&
        this.noRouteDismiss !== true &&
        this.seamless !== true
    }
  },

  methods: {
    focus () {
      let node = this.__getInnerNode()

      if (node === void 0 || node.contains(document.activeElement) === true) {
        return
      }

      node = node.querySelector('[autofocus], [data-autofocus]') || node
      node.focus()
    },

    shake () {
      this.focus()

      const node = this.__getInnerNode()

      if (node !== void 0) {
        node.classList.remove('q-animate--scale')
        node.classList.add('q-animate--scale')
        clearTimeout(this.shakeTimeout)
        this.shakeTimeout = setTimeout(() => {
          node.classList.remove('q-animate--scale')
        }, 170)
      }
    },

    __getInnerNode () {
      return this.__portal !== void 0 && this.__portal.$refs !== void 0
        ? this.__portal.$refs.inner
        : void 0
    },

    __show (evt) {
      this.__addHistory()

      // IE can have null document.activeElement
      this.__refocusTarget = this.noRefocus === false && document.activeElement !== null
        ? document.activeElement
        : void 0

      this.$el.dispatchEvent(create('popup-show', { bubbles: true }))

      this.__updateState(true, this.maximized)

      EscapeKey.register(this, () => {
        if (this.seamless !== true) {
          if (this.persistent === true || this.noEscDismiss === true) {
            this.maximized !== true && this.shake()
          }
          else {
            this.$emit('escape-key')
            this.hide()
          }
        }
      })

      this.__showPortal()

      if (this.noFocus !== true) {
        // IE can have null document.activeElement
        document.activeElement !== null && document.activeElement.blur()
        this.__nextTick(this.focus)
      }

      this.__setTimeout(() => {
        if (this.$q.platform.is.ios === true && document.activeElement) {
          const
            { top, bottom } = document.activeElement.getBoundingClientRect(),
            { innerHeight } = window,
            height = window.visualViewport !== void 0
              ? window.visualViewport.height
              : innerHeight

          if (top > 0 && bottom > height / 2) {
            const scrollTop = Math.min(
              document.scrollingElement.scrollHeight - height,
              bottom >= innerHeight
                ? Infinity
                : Math.ceil(document.scrollingElement.scrollTop + bottom - height / 2)
            )

            const fn = () => {
              requestAnimationFrame(() => {
                document.scrollingElement.scrollTop += Math.ceil((scrollTop - document.scrollingElement.scrollTop) / 8)
                if (document.scrollingElement.scrollTop !== scrollTop) {
                  fn()
                }
              })
            }

            fn()
          }
          document.activeElement.scrollIntoView()
        }

        // required in order to avoid the "double-tap needed" issue
        this.$q.platform.is.ios === true && this.__portal.$el.click()

        this.$emit('show', evt)
      }, 300)
    },

    __hide (evt) {
      this.__removeHistory()
      this.__cleanup(true)

      // check null for IE
      if (this.__refocusTarget !== void 0 && this.__refocusTarget !== null) {
        this.__refocusTarget.focus()
      }

      this.$el.dispatchEvent(create('popup-hide', { bubbles: true }))

      this.__setTimeout(() => {
        this.__hidePortal()
        this.$emit('hide', evt)
      }, 300)
    },

    __cleanup (hiding) {
      clearTimeout(this.shakeTimeout)

      if (hiding === true || this.showing === true) {
        EscapeKey.pop(this)
        this.__updateState(false, this.maximized)
        if (this.seamless !== true) {
          this.__preventScroll(false)
          this.__preventFocusout(false)
        }
      }
    },

    __updateState (opening, maximized) {
      if (maximized === true) {
        if (opening === true) {
          maximizedModals < 1 && document.body.classList.add('q-body--dialog')
        }
        else if (maximizedModals < 2) {
          document.body.classList.remove('q-body--dialog')
        }
        maximizedModals += opening === true ? 1 : -1
      }
    },

    __preventFocusout (state) {
      if (this.$q.platform.is.desktop === true) {
        const action = `${state === true ? 'add' : 'remove'}EventListener`
        document.body[action]('focusin', this.__onFocusChange)
      }
    },

    __onAutoClose (e) {
      this.hide(e)
      this.$listeners.click !== void 0 && this.$emit('click', e)
    },

    __onBackdropClick (e) {
      if (this.persistent !== true && this.noBackdropDismiss !== true) {
        this.hide(e)
      }
      else {
        this.shake()
      }
    },

    __onFocusChange (e) {
      // the focus is not in a vue child component
      if (
        this.showing === true &&
        this.__portal !== void 0 &&
        childHasFocus(this.__portal.$el, e.target) !== true
      ) {
        this.focus()
      }
    },

    __renderPortal (h) {
      const on = {
        ...this.$listeners,
        // stop propagating these events from children
        input: stop,
        'popup-show': stop,
        'popup-hide': stop
      }

      if (this.autoClose === true) {
        on.click = this.__onAutoClose
      }

      return h('div', {
        staticClass: 'q-dialog fullscreen no-pointer-events',
        class: this.contentClass,
        style: this.contentStyle,
        attrs: this.$attrs
      }, [
        h('transition', {
          props: { name: 'q-transition--fade' }
        }, this.useBackdrop === true ? [
          h('div', {
            staticClass: 'q-dialog__backdrop fixed-full',
            on: cache(this, 'bkdrop', {
              click: this.__onBackdropClick
            })
          })
        ] : null),

        h('transition', {
          props: { name: this.transition }
        }, [
          this.showing === true ? h('div', {
            ref: 'inner',
            staticClass: 'q-dialog__inner flex no-pointer-events',
            class: this.classes,
            attrs: { tabindex: -1 },
            on
          }, slot(this, 'default')) : null
        ])
      ])
    }
  },

  mounted () {
    this.__processModelChange(this.value)
  },

  beforeDestroy () {
    this.__cleanup()
  }
})
<commit_msg>fix(QDialog): changing maximized and value in same cycle breaks parts of cleanup #6739<commit_after>import Vue from 'vue'

import HistoryMixin from '../../mixins/history.js'
import ModelToggleMixin from '../../mixins/model-toggle.js'
import PortalMixin from '../../mixins/portal.js'
import PreventScrollMixin from '../../mixins/prevent-scroll.js'

import { childHasFocus } from '../../utils/dom.js'
import EscapeKey from '../../utils/escape-key.js'
import { slot } from '../../utils/slot.js'
import { create, stop } from '../../utils/event.js'
import { cache } from '../../utils/vm.js'

let maximizedModals = 0

const positionClass = {
  standard: 'fixed-full flex-center',
  top: 'fixed-top justify-center',
  bottom: 'fixed-bottom justify-center',
  right: 'fixed-right items-center',
  left: 'fixed-left items-center'
}

const transitions = {
  standard: ['scale', 'scale'],
  top: ['slide-down', 'slide-up'],
  bottom: ['slide-up', 'slide-down'],
  right: ['slide-left', 'slide-right'],
  left: ['slide-right', 'slide-left']
}

export default Vue.extend({
  name: 'QDialog',

  mixins: [ HistoryMixin, ModelToggleMixin, PortalMixin, PreventScrollMixin ],

  props: {
    persistent: Boolean,
    autoClose: Boolean,

    noEscDismiss: Boolean,
    noBackdropDismiss: Boolean,
    noRouteDismiss: Boolean,
    noRefocus: Boolean,
    noFocus: Boolean,

    seamless: Boolean,

    maximized: Boolean,
    fullWidth: Boolean,
    fullHeight: Boolean,

    square: Boolean,

    position: {
      type: String,
      default: 'standard',
      validator: val => val === 'standard' ||
        ['top', 'bottom', 'left', 'right'].includes(val)
    },

    transitionShow: String,
    transitionHide: String
  },

  data () {
    return {
      transitionState: this.showing
    }
  },

  watch: {
    showing (val) {
      if (this.transitionShowComputed !== this.transitionHideComputed) {
        this.$nextTick(() => {
          this.transitionState = val
        })
      }
    },

    maximized (state) {
      this.showing === true && this.__updateMaximized(state)
    },

    useBackdrop (v) {
      this.__preventScroll(v)
      this.__preventFocusout(v)
    }
  },

  computed: {
    classes () {
      return `q-dialog__inner--${this.maximized === true ? 'maximized' : 'minimized'} ` +
        `q-dialog__inner--${this.position} ${positionClass[this.position]}` +
        (this.fullWidth === true ? ' q-dialog__inner--fullwidth' : '') +
        (this.fullHeight === true ? ' q-dialog__inner--fullheight' : '') +
        (this.square === true ? ' q-dialog__inner--square' : '')
    },

    transitionShowComputed () {
      return 'q-transition--' + (this.transitionShow === void 0 ? transitions[this.position][0] : this.transitionShow)
    },

    transitionHideComputed () {
      return 'q-transition--' + (this.transitionHide === void 0 ? transitions[this.position][1] : this.transitionHide)
    },

    transition () {
      return this.transitionState === true
        ? this.transitionHideComputed
        : this.transitionShowComputed
    },

    useBackdrop () {
      return this.showing === true && this.seamless !== true
    },

    hideOnRouteChange () {
      return this.persistent !== true &&
        this.noRouteDismiss !== true &&
        this.seamless !== true
    }
  },

  methods: {
    focus () {
      let node = this.__getInnerNode()

      if (node === void 0 || node.contains(document.activeElement) === true) {
        return
      }

      node = node.querySelector('[autofocus], [data-autofocus]') || node
      node.focus()
    },

    shake () {
      this.focus()

      const node = this.__getInnerNode()

      if (node !== void 0) {
        node.classList.remove('q-animate--scale')
        node.classList.add('q-animate--scale')
        clearTimeout(this.shakeTimeout)
        this.shakeTimeout = setTimeout(() => {
          node.classList.remove('q-animate--scale')
        }, 170)
      }
    },

    __getInnerNode () {
      return this.__portal !== void 0 && this.__portal.$refs !== void 0
        ? this.__portal.$refs.inner
        : void 0
    },

    __show (evt) {
      this.__addHistory()

      // IE can have null document.activeElement
      this.__refocusTarget = this.noRefocus === false && document.activeElement !== null
        ? document.activeElement
        : void 0

      this.$el.dispatchEvent(create('popup-show', { bubbles: true }))
      this.__updateMaximized(this.maximized)

      EscapeKey.register(this, () => {
        if (this.seamless !== true) {
          if (this.persistent === true || this.noEscDismiss === true) {
            this.maximized !== true && this.shake()
          }
          else {
            this.$emit('escape-key')
            this.hide()
          }
        }
      })

      this.__showPortal()

      if (this.noFocus !== true) {
        // IE can have null document.activeElement
        document.activeElement !== null && document.activeElement.blur()
        this.__nextTick(this.focus)
      }

      this.__setTimeout(() => {
        if (this.$q.platform.is.ios === true && document.activeElement) {
          const
            { top, bottom } = document.activeElement.getBoundingClientRect(),
            { innerHeight } = window,
            height = window.visualViewport !== void 0
              ? window.visualViewport.height
              : innerHeight

          if (top > 0 && bottom > height / 2) {
            const scrollTop = Math.min(
              document.scrollingElement.scrollHeight - height,
              bottom >= innerHeight
                ? Infinity
                : Math.ceil(document.scrollingElement.scrollTop + bottom - height / 2)
            )

            const fn = () => {
              requestAnimationFrame(() => {
                document.scrollingElement.scrollTop += Math.ceil((scrollTop - document.scrollingElement.scrollTop) / 8)
                if (document.scrollingElement.scrollTop !== scrollTop) {
                  fn()
                }
              })
            }

            fn()
          }
          document.activeElement.scrollIntoView()
        }

        // required in order to avoid the "double-tap needed" issue
        this.$q.platform.is.ios === true && this.__portal.$el.click()

        this.$emit('show', evt)
      }, 300)
    },

    __hide (evt) {
      this.__removeHistory()
      this.__cleanup(true)

      // check null for IE
      if (this.__refocusTarget !== void 0 && this.__refocusTarget !== null) {
        this.__refocusTarget.focus()
      }

      this.$el.dispatchEvent(create('popup-hide', { bubbles: true }))

      this.__setTimeout(() => {
        this.__hidePortal()
        this.$emit('hide', evt)
      }, 300)
    },

    __cleanup (hiding) {
      clearTimeout(this.shakeTimeout)

      if (hiding === true || this.showing === true) {
        EscapeKey.pop(this)
        this.__updateMaximized(false)

        if (this.seamless !== true) {
          this.__preventScroll(false)
          this.__preventFocusout(false)
        }
      }
    },

    __updateMaximized (active) {
      if (active === true) {
        if (this.isMaximized !== true) {
          maximizedModals < 1 && document.body.classList.add('q-body--dialog')
          maximizedModals++

          this.isMaximized = true
        }
      }
      else if (this.isMaximized === true) {
        if (maximizedModals < 2) {
          document.body.classList.remove('q-body--dialog')
        }

        maximizedModals--
        this.isMaximized = false
      }
    },

    __preventFocusout (state) {
      if (this.$q.platform.is.desktop === true) {
        const action = `${state === true ? 'add' : 'remove'}EventListener`
        document.body[action]('focusin', this.__onFocusChange)
      }
    },

    __onAutoClose (e) {
      this.hide(e)
      this.$listeners.click !== void 0 && this.$emit('click', e)
    },

    __onBackdropClick (e) {
      if (this.persistent !== true && this.noBackdropDismiss !== true) {
        this.hide(e)
      }
      else {
        this.shake()
      }
    },

    __onFocusChange (e) {
      // the focus is not in a vue child component
      if (
        this.showing === true &&
        this.__portal !== void 0 &&
        childHasFocus(this.__portal.$el, e.target) !== true
      ) {
        this.focus()
      }
    },

    __renderPortal (h) {
      const on = {
        ...this.$listeners,
        // stop propagating these events from children
        input: stop,
        'popup-show': stop,
        'popup-hide': stop
      }

      if (this.autoClose === true) {
        on.click = this.__onAutoClose
      }

      return h('div', {
        staticClass: 'q-dialog fullscreen no-pointer-events',
        class: this.contentClass,
        style: this.contentStyle,
        attrs: this.$attrs
      }, [
        h('transition', {
          props: { name: 'q-transition--fade' }
        }, this.useBackdrop === true ? [
          h('div', {
            staticClass: 'q-dialog__backdrop fixed-full',
            on: cache(this, 'bkdrop', {
              click: this.__onBackdropClick
            })
          })
        ] : null),

        h('transition', {
          props: { name: this.transition }
        }, [
          this.showing === true ? h('div', {
            ref: 'inner',
            staticClass: 'q-dialog__inner flex no-pointer-events',
            class: this.classes,
            attrs: { tabindex: -1 },
            on
          }, slot(this, 'default')) : null
        ])
      ])
    }
  },

  mounted () {
    this.__processModelChange(this.value)
  },

  beforeDestroy () {
    this.__cleanup()
  }
})
<|endoftext|>


<commit_before>var gith = require('gith').create(3141);
var execFile = require('child_process').execFile;

gith({
  repo: 'cs-zsc/ieee-zsb.org'
}).on('all', function(payload) {
  if (payload.branch === 'testing') {
    execFile(__dirname + '/hooks/update-testing.sh', function(err, stdout, stderr) {
      if (!err) {
        console.log('Testing branch updated successfully');
      } else {
        console.log('Error updating testing branch, checkout stdout/stderr');
        console.log('stdout:');
        console.log(stdout);
        console.log('stderr:');
        console.log(stderr);
      }
    });
  } else if (payload.branch === 'master') {
    execFile(__dirname + '/hooks/update-master.sh', function(err, stdout, stderr) {
      if (!err) {
        console.log('Testing branch updated successfully');
      } else {
        console.log('Error updating master branch, checkout stdout/stderr');
        console.log('stdout:');
        console.log(stdout);
        console.log('stderr:');
        console.log(stderr);
      }
  }
});
<commit_msg>Fixed syntax error<commit_after>var gith = require('gith').create(3141);
var execFile = require('child_process').execFile;

gith({
  repo: 'cs-zsc/ieee-zsb.org'
}).on('all', function(payload) {
  if (payload.branch === 'testing') {
    execFile(__dirname + '/hooks/update-testing.sh', function(err, stdout, stderr) {
      if (!err) {
        console.log('Testing branch updated successfully');
      } else {
        console.log('Error updating testing branch, checkout stdout/stderr');
        console.log('stdout:');
        console.log(stdout);
        console.log('stderr:');
        console.log(stderr);
      }
    });
  } else if (payload.branch === 'master') {
    execFile(__dirname + '/hooks/update-master.sh', function(err, stdout, stderr) {
      if (!err) {
        console.log('Testing branch updated successfully');
      } else {
        console.log('Error updating master branch, checkout stdout/stderr');
        console.log('stdout:');
        console.log(stdout);
        console.log('stderr:');
        console.log(stderr);
      }
    });
  }
});
<|endoftext|>


<commit_before>"use strict"

var Vnode = require("../render/vnode")

var selectorParser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[(.+?)(?:\s*=\s*("|'|)((?:\\["'\]]|.)*?)\5)?\])/g
var selectorCache = {}
function hyperscript(selector) {
	if (selector == null || typeof selector !== "string" && !selector.view) {
		throw Error("The selector must be either a string or a component.");
	}

	if (typeof selector === "string") {
		if (selectorCache[selector] === undefined) {
			var match, tag, classes = [], attributes = {}
			while (match = selectorParser.exec(selector)) {
				var type = match[1], value = match[2]
				if (type === "" && value !== "") tag = value
				else if (type === "#") attributes.id = value
				else if (type === ".") classes.push(value)
				else if (match[3][0] === "[") {
					var attrValue = match[6]
					if (attrValue) attrValue = attrValue.replace(/\\(["'])/g, "$1").replace(/\\\\/g, "\\")
					attributes[match[4]] = attrValue || true
				}
			}
			if (classes.length > 0) attributes.className = classes.join(" ")
			selectorCache[selector] = function(attrs, children) {
				var hasAttrs = false, childList, text
				var className = attrs.className || attrs.class
				for (var key in attributes) attrs[key] = attributes[key]
				if (className !== undefined) {
					if (attrs.class !== undefined) {
						attrs.class = undefined
						attrs.className = className
					}
					if (attributes.className !== undefined) attrs.className = attributes.className + " " + className
				}
				for (var key in attrs) {
					if (key !== "key") {
						hasAttrs = true
						break
					}
				}
				if (children instanceof Array && children.length == 1 && children[0] != null && children[0].tag === "#") text = children[0].children
				else childList = children

				return Vnode(tag || "div", attrs.key, hasAttrs ? attrs : undefined, childList, text, undefined)
			}
		}
	}
	var attrs, children, childrenIndex
	if (arguments[1] == null || typeof arguments[1] === "object" && arguments[1].tag === undefined && !(arguments[1] instanceof Array)) {
		attrs = arguments[1]
		childrenIndex = 2
	}
	else childrenIndex = 1
	if (arguments.length === childrenIndex + 1) {
		children = arguments[childrenIndex] instanceof Array ? arguments[childrenIndex] : [arguments[childrenIndex]]
	}
	else {
		children = []
		for (var i = childrenIndex; i < arguments.length; i++) children.push(arguments[i])
	}

	if (typeof selector === "string") return selectorCache[selector](attrs || {}, Vnode.normalizeChildren(children))

	return Vnode(selector, attrs && attrs.key, attrs || {}, Vnode.normalizeChildren(children), undefined, undefined)
}

module.exports = hyperscript
<commit_msg>don't cast to boolean<commit_after>"use strict"

var Vnode = require("../render/vnode")

var selectorParser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[(.+?)(?:\s*=\s*("|'|)((?:\\["'\]]|.)*?)\5)?\])/g
var selectorCache = {}
function hyperscript(selector) {
	if (selector == null || typeof selector !== "string" && selector.view == null) {
		throw Error("The selector must be either a string or a component.");
	}

	if (typeof selector === "string") {
		if (selectorCache[selector] === undefined) {
			var match, tag, classes = [], attributes = {}
			while (match = selectorParser.exec(selector)) {
				var type = match[1], value = match[2]
				if (type === "" && value !== "") tag = value
				else if (type === "#") attributes.id = value
				else if (type === ".") classes.push(value)
				else if (match[3][0] === "[") {
					var attrValue = match[6]
					if (attrValue) attrValue = attrValue.replace(/\\(["'])/g, "$1").replace(/\\\\/g, "\\")
					attributes[match[4]] = attrValue || true
				}
			}
			if (classes.length > 0) attributes.className = classes.join(" ")
			selectorCache[selector] = function(attrs, children) {
				var hasAttrs = false, childList, text
				var className = attrs.className || attrs.class
				for (var key in attributes) attrs[key] = attributes[key]
				if (className !== undefined) {
					if (attrs.class !== undefined) {
						attrs.class = undefined
						attrs.className = className
					}
					if (attributes.className !== undefined) attrs.className = attributes.className + " " + className
				}
				for (var key in attrs) {
					if (key !== "key") {
						hasAttrs = true
						break
					}
				}
				if (children instanceof Array && children.length == 1 && children[0] != null && children[0].tag === "#") text = children[0].children
				else childList = children

				return Vnode(tag || "div", attrs.key, hasAttrs ? attrs : undefined, childList, text, undefined)
			}
		}
	}
	var attrs, children, childrenIndex
	if (arguments[1] == null || typeof arguments[1] === "object" && arguments[1].tag === undefined && !(arguments[1] instanceof Array)) {
		attrs = arguments[1]
		childrenIndex = 2
	}
	else childrenIndex = 1
	if (arguments.length === childrenIndex + 1) {
		children = arguments[childrenIndex] instanceof Array ? arguments[childrenIndex] : [arguments[childrenIndex]]
	}
	else {
		children = []
		for (var i = childrenIndex; i < arguments.length; i++) children.push(arguments[i])
	}

	if (typeof selector === "string") return selectorCache[selector](attrs || {}, Vnode.normalizeChildren(children))

	return Vnode(selector, attrs && attrs.key, attrs || {}, Vnode.normalizeChildren(children), undefined, undefined)
}

module.exports = hyperscript
<|endoftext|>


<commit_before>
/*
 * Document ready start
 */

$(document).ready(function() {

  /*! cookie function. get, set, or forget a cookie. [c]2014 @scottjehl, Filament Group, Inc. Licensed MIT */

  function createCookie(name,value,days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
  }

  var html = document.documentElement;
  html.classList.add('fonts-loading');

  var light = new FontFaceObserver('Linotte-Light', {
      weight: 400
  });
  var regular = new FontFaceObserver('Linotte-Regular', {
      weight: 400
  });
  var semibold = new FontFaceObserver('Linotte-Semibold', {
      weight: 400
  });
  var fontawesome = new FontFaceObserver('FontAwesome', {
      weight: 400
  });

  Promise.all([
    light.load(null, 5000),
    regular.load(null, 5000),
    semibold.load(null, 5000)
  ]).then(function () {
    console.log('Linotte light, regular & semibold have loaded');
    fontawesome.load(null, 5000).then(function () {
      console.log('Fontawesome has loaded');
      html.classList.remove('fonts-loading');
      html.classList.add('fonts-loaded');
      createCookie('fonts-loaded', '1', 1);
      /* sessionStorage.fontsLoaded = true; */
    }).catch(function () {
      console.log('Fontawesome loading failed, using fallback font');
      html.classList.remove('fonts-loading');
      html.classList.add('fonts-failed');
      /* sessionStorage.fontsLoaded = false; */
    });
  });

  /*
   *  Enabling all inline JS-blocks (= Lightslider), by cloning / appending
   *  them to the body and setting the correct type "text/javascript".
   *  as seen in: https://stackoverflow.com/questions/20180556/defer-inline-javascript-execution
   */

/*
  $(function() {
    $("script[type='text/example']").each(function() {
        $(this).clone().attr("type","text/javascript").appendTo("body");
    });
  });
*/

  /*
   * Center active menu item
   */

  var activeMenu = function() {

    if ( $('.nav__item.active').length ) {

      var navi = $('.main-nav');
      var target = $('.nav__item.active');

      var w = navi.width();
      // console.log("navi.width = " + w );

      var x = navi[0].scrollWidth;
      // console.log("navi.scrollwidth = " + x );

      var y = target.outerWidth(true);
      // console.log("target.outerWidth = " + y );

      var p = target.position().left;
      // console.log("target.position = " + p );

      var t = (((w / 2) - (y / 2)) - p);
      // console.log("move by = " + t );

      navi.scrollLeft( -t );

    }

  };

  activeMenu();

  // Sticky header via headroom.js
  // https://github.com/WickyNilliams/headroom.js
  // http://wicky.nillia.ms/headroom.js/
$("nav").headroom({
  "offset": 90,
  "tolerance": 5,
  "classes": {
    "initial": "animated",
    "pinned": "slideDown",
    "unpinned": "slideUp"
  }
});

  // the animation slide-duration corresponds with values in the css
  // that set the fading bg-color
  var accordionSlide = function() {

    // hide all answers, except the first one
    $('.faq-answer').not(':eq(0)').hide();

    $('.faq-question').click(function(){

      // e.preventDefault();

      var currentQ = $(this);
      var currentA = $(this).next('.faq-answer');
      var lastQ    = $('.faq-question.is-open');
      var lastA    = lastQ.next('.faq-answer');

      var currentTarget = $(this).children(":first");
      console.log(currentTarget);

      $('html,body').animate({ scrollTop: $(currentTarget).offset().top }, 'slow');

      // only slide if the click is on a different question than last time
      if ( this !== lastQ.get(0) ) {
        lastQ.addClass('is-closing').removeClass('is-open');
        currentQ.addClass('is-open');

        lastA.removeClass('is-visible').addClass('is-closing').slideUp({
            duration: 400,
            queue: false,
            complete: function () {
              // change class when slide finishes
              // remove classes, used for css-keyframe-animations
              $(this).removeClass('is-closing');
              lastQ.removeClass('is-closing');
            }
          });
        currentA.addClass('is-visible').slideDown(400);
      }
    });

  }

  accordionSlide();

  /*
   *  Providing filter functionality to .cards collections.
   *
   */
  $(function(){
    var $optionSets = $('.filter');
    var $optionLinks = $optionSets.find('a');
    var $notCurrentCategory;

    $optionLinks.click(function(e){

      var $this = $(this);
      // don't proceed if already selected
      if ( $this.hasClass('js-selected') ) {
        e.preventDefault();
      }

      var $optionSet = $this.parents('.filter');
      $optionSet.find('.js-selected').removeClass('js-selected');
      $this.addClass('js-selected');

      var $currentCategory = $this.attr('data-category-name');
      var $categorySet = $this.parents('.filter').siblings('.cards');

      if ( $notCurrentCategory ) {
        $notCurrentCategory.appendTo( $categorySet );
      }

      if ( $currentCategory == 'js-category-all') {
        $notCurrentCategory.appendTo( $categorySet );
      } else {
        $notCurrentCategory = $('.card:not([data-partner-category="'+ $currentCategory + '"])');
        $notCurrentCategory.detach();
      }

      e.preventDefault();
    });
  });

  /*
   * Trigger "plus de details / moins de details" in .category-content on list pages
   */
  $(function(){
    $(".js-show-info").click(function(e) {
        $(this).closest(".js-info-toggler").nextAll(".js-info-to-toggle:first").toggle().addClass('is-shown');
        $(this).siblings(".js-hide-info").css('display','inline-block');
        $(this).css('display','none');
        e.preventDefault();
    });
    $(".js-hide-info").click(function(e) {
        $(this).closest(".js-info-toggler").nextAll(".js-info-to-toggle:first").hide().toggleClass('is-shown');
        $(this).siblings(".js-show-info").css('display','inline-block');
        $(this).css('display','none');
        e.preventDefault();
    });
  });

  jQuery(".row-with-title figcaption").fitText(0.4, { minFontSize: '24px', maxFontSize: '42px' });

  var $timeline_block = $('.timeline-row, .block--cta');

  //hide timeline blocks which are outside the viewport
  $timeline_block.each(function(){
    if($(this).offset().top > $(window).scrollTop()+$(window).height()*0.90) {
      $(this).find('.timeline-row__img, .timeline-row__info, .headline--cta').addClass('is-hidden');
    }
  });

  //on scolling, show/animate timeline blocks when enter the viewport
  $(window).on('scroll', function(){
    $timeline_block.each(function(){
      if( $(this).offset().top <= $(window).scrollTop()+$(window).height()*0.90 && $(this).find('.timeline-row__img, .headline--cta').hasClass('is-hidden') ) {
        $(this).find('.timeline-row__img, .timeline-row__info, .timeline-row__info, .headline--cta').removeClass('is-hidden').addClass('bounce-in');
      }
    });
  });

  /*
   * Button scroll to top
   */
  var id = 'js-scrolltop';
  $('.' + id).click(function(){
      $('html, body').animate({ scrollTop: 0 }, 150);
  });
  window.onscroll = function () {
      if(window.pageYOffset < 9000) {
          $('.' + id).fadeOut(300);
      }
      else {
          $('.' + id).fadeIn(300);
      }
  }

	/*
   * Button scroll menu
   */
  $('.js-scrollmenu').click(function(){
      if ( $( this ).hasClass( "active" ) ) {
      	$('.main-nav').animate({ scrollLeft: "-=450" }, 350);
      	$( this ).toggleClass("active");
			} else {
      	$('.main-nav').animate({ scrollLeft: "+=450" }, 350);
      	$( this ).toggleClass("active");
      }
  });

  /*
   * Button scroll block
   */

  var scrollContents = function() {

    if ( $('.js-scrollblock').length ) {
      // Get elements & position
      var wrapper = $('.block__scroll-wrapper');
      var firstItem = $('a.card:first-of-type');
      var fip = firstItem.position().left;
      var fipi = fip; // initial offset for first card
      console.log("first ever fipi = " + fipi);
    }

    $('.js-scrollblock').click(function(){
      // Get widths & this
      var ww = wrapper[0].scrollWidth;
      console.log("wrapper scrollWidth = " + ww);
      var sw = $( window ).width();
      console.log("window width = " + sw);
      var $this = $(this);

      if ( $this.hasClass( "reverse" ) ) {

        wrapper.animate({ scrollLeft: "-=" + (sw - (fipi / 2) ) },
          { complete: function(){
              var fip = firstItem.position().left;
              console.log("new fip after scroll left = " + ( -fip - fipi ));

              if ( ( fip - fipi ) == 0 ) {
                $this.toggleClass("reverse");
              }
            }
          },
        500);

      } else {

        wrapper.animate({ scrollLeft: "+=" + (sw - (fipi / 2) ) },
          { complete: function(){
              var fip = firstItem.position().left;
              console.log("new fip after scroll right = " + ( -fip + fipi ));
              console.log("result = " + (( -fip + fipi) >= ( ww - sw )) );

              if ( ( -fip + fipi) == ( ww - sw )  ) {
                $this.toggleClass("reverse");
              }
            }
          },
        500);
      }

      // console.log( "firstitem position - firstitem initial position = " + (fip - fipi) );
      // console.log( "wrapperwidth - screenwidth = " + (ww - sw) );
      // document.activeElement = null;
    });
  }

  scrollContents();

/*
 *
 *  Resize-Listener
 */

  // var resizeTimer;

  // $(window).on('resize', function(e) {

  //   clearTimeout(resizeTimer);
  //   resizeTimer = setTimeout(function() {

  //   if ( $('.js-scrollblock').length ) {
  //     fip = $('a.card:first-of-type').position().left;
  //     console.log("FIP after resize = " + fip);
  //   }

  //   scrollContents(fip);

  //   }, 2000);

  // });

  // $(window).resize(function() {
  //   clearTimeout(window.resizedFinished);
  //   window.resizedFinished = setTimeout(function(){
  //     if ( $('.js-scrollblock').length ) {
  //       fip = $('a.card:first-of-type').position().left;
  //       console.log('Resized finished.');
  //       console.log("FIP after resize = " + fip);
  //       scrollContents(fip);
  //     }
  //   }, 250);
  // });

  var screen = window; //To access the dom only once
  var cWidth = $( window ).width();
  var newWidth = cWidth; //If you want a log to show at startup, change to: newWidth = 0
  console.log("Initial newWidth:", newWidth);

  $(window).resize(function() {
    clearTimeout(window.resizedFinished);
    window.resizedFinished = setTimeout(function(){

      newWidth = $( window ).width();
      console.log("New newWidth in window.resize:", newWidth);
      console.log("cWidth in window.resize:", cWidth);
      if(cWidth != newWidth){
          cWidth = newWidth;
          console.log("clientWidth:", cWidth); //instead of alert(cWidth);
          // fip = $('a.card:first-of-type').position().left;

          // Unbind the click event, otherwise the scroll would accumulate
          // with every resize.
          $('.js-scrollblock').off("click");
          scrollContents();
       };

    }, 500);
  });

});<commit_msg>asdasd<commit_after>
/*
 * Document ready start
 */

$(document).ready(function() {

  /*! cookie function. get, set, or forget a cookie. [c]2014 @scottjehl, Filament Group, Inc. Licensed MIT */

  function createCookie(name,value,days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
  }

  var html = document.documentElement;
  html.classList.add('fonts-loading');

  var light = new FontFaceObserver('Linotte-Light', {
      weight: 400
  });
  var regular = new FontFaceObserver('Linotte-Regular', {
      weight: 400
  });
  var semibold = new FontFaceObserver('Linotte-Semibold', {
      weight: 400
  });
  var fontawesome = new FontFaceObserver('FontAwesome', {
      weight: 400
  });

  Promise.all([
    light.load(null, 5000),
    regular.load(null, 5000),
    semibold.load(null, 5000)
  ]).then(function () {
    console.log('Linotte light, regular & semibold have loaded');
    fontawesome.load(null, 5000).then(function () {
      console.log('Fontawesome has loaded');
      html.classList.remove('fonts-loading');
      html.classList.add('fonts-loaded');
      createCookie('fonts-loaded', '1', 1);
      /* sessionStorage.fontsLoaded = true; */
    }).catch(function () {
      console.log('Fontawesome loading failed, using fallback font');
      html.classList.remove('fonts-loading');
      html.classList.add('fonts-failed');
      /* sessionStorage.fontsLoaded = false; */
    });
  });

  /*
   *  Enabling all inline JS-blocks (= Lightslider), by cloning / appending
   *  them to the body and setting the correct type "text/javascript".
   *  as seen in: https://stackoverflow.com/questions/20180556/defer-inline-javascript-execution
   */

/*
  $(function() {
    $("script[type='text/example']").each(function() {
        $(this).clone().attr("type","text/javascript").appendTo("body");
    });
  });
*/

  /*
   * Center active menu item
   */

  var activeMenu = function() {

    if ( $('.nav__item.active').length ) {

      var navi = $('.main-nav');
      var target = $('.nav__item.active');

      var w = navi.width();
      // console.log("navi.width = " + w );

      var x = navi[0].scrollWidth;
      // console.log("navi.scrollwidth = " + x );

      var y = target.outerWidth(true);
      // console.log("target.outerWidth = " + y );

      var p = target.position().left;
      // console.log("target.position = " + p );

      var t = (((w / 2) - (y / 2)) - p);
      // console.log("move by = " + t );

      navi.scrollLeft( -t );

    }

  };

  activeMenu();

  // Sticky header via headroom.js
  // https://github.com/WickyNilliams/headroom.js
  // http://wicky.nillia.ms/headroom.js/
$("nav").headroom({
  "offset": 90,
  "tolerance": 5,
  "classes": {
    "initial": "animated",
    "pinned": "slideDown",
    "unpinned": "slideUp"
  }
});

  // the animation slide-duration corresponds with values in the css
  // that set the fading bg-color
  var accordionSlide = function() {

    // hide all answers, except the first one
    $('.faq-answer').not(':eq(0)').hide();

    $('.faq-question').click(function(e){

      e.preventDefault(e);

      var currentQ = $(this);
      var currentA = $(this).next('.faq-answer');
      var lastQ    = $('.faq-question.is-open');
      var lastA    = lastQ.next('.faq-answer');

      var currentTarget = $(this).children(":first");
      console.log(currentTarget);

      $('html,body').animate({ scrollTop: $(currentTarget).offset().top + 84 }, 'slow');

      // only slide if the click is on a different question than last time
      if ( this !== lastQ.get(0) ) {
        lastQ.addClass('is-closing').removeClass('is-open');
        currentQ.addClass('is-open');

        lastA.removeClass('is-visible').addClass('is-closing').slideUp({
            duration: 400,
            queue: false,
            complete: function () {
              // change class when slide finishes
              // remove classes, used for css-keyframe-animations
              $(this).removeClass('is-closing');
              lastQ.removeClass('is-closing');
            }
          });
        currentA.addClass('is-visible').slideDown(400);
      }
    });

  }

  accordionSlide();

  /*
   *  Providing filter functionality to .cards collections.
   *
   */
  $(function(){
    var $optionSets = $('.filter');
    var $optionLinks = $optionSets.find('a');
    var $notCurrentCategory;

    $optionLinks.click(function(e){

      var $this = $(this);
      // don't proceed if already selected
      if ( $this.hasClass('js-selected') ) {
        e.preventDefault();
      }

      var $optionSet = $this.parents('.filter');
      $optionSet.find('.js-selected').removeClass('js-selected');
      $this.addClass('js-selected');

      var $currentCategory = $this.attr('data-category-name');
      var $categorySet = $this.parents('.filter').siblings('.cards');

      if ( $notCurrentCategory ) {
        $notCurrentCategory.appendTo( $categorySet );
      }

      if ( $currentCategory == 'js-category-all') {
        $notCurrentCategory.appendTo( $categorySet );
      } else {
        $notCurrentCategory = $('.card:not([data-partner-category="'+ $currentCategory + '"])');
        $notCurrentCategory.detach();
      }

      e.preventDefault();
    });
  });

  /*
   * Trigger "plus de details / moins de details" in .category-content on list pages
   */
  $(function(){
    $(".js-show-info").click(function(e) {
        $(this).closest(".js-info-toggler").nextAll(".js-info-to-toggle:first").toggle().addClass('is-shown');
        $(this).siblings(".js-hide-info").css('display','inline-block');
        $(this).css('display','none');
        e.preventDefault();
    });
    $(".js-hide-info").click(function(e) {
        $(this).closest(".js-info-toggler").nextAll(".js-info-to-toggle:first").hide().toggleClass('is-shown');
        $(this).siblings(".js-show-info").css('display','inline-block');
        $(this).css('display','none');
        e.preventDefault();
    });
  });

  jQuery(".row-with-title figcaption").fitText(0.4, { minFontSize: '24px', maxFontSize: '42px' });

  var $timeline_block = $('.timeline-row, .block--cta');

  //hide timeline blocks which are outside the viewport
  $timeline_block.each(function(){
    if($(this).offset().top > $(window).scrollTop()+$(window).height()*0.90) {
      $(this).find('.timeline-row__img, .timeline-row__info, .headline--cta').addClass('is-hidden');
    }
  });

  //on scolling, show/animate timeline blocks when enter the viewport
  $(window).on('scroll', function(){
    $timeline_block.each(function(){
      if( $(this).offset().top <= $(window).scrollTop()+$(window).height()*0.90 && $(this).find('.timeline-row__img, .headline--cta').hasClass('is-hidden') ) {
        $(this).find('.timeline-row__img, .timeline-row__info, .timeline-row__info, .headline--cta').removeClass('is-hidden').addClass('bounce-in');
      }
    });
  });

  /*
   * Button scroll to top
   */
  var id = 'js-scrolltop';
  $('.' + id).click(function(){
      $('html, body').animate({ scrollTop: 0 }, 150);
  });
  window.onscroll = function () {
      if(window.pageYOffset < 9000) {
          $('.' + id).fadeOut(300);
      }
      else {
          $('.' + id).fadeIn(300);
      }
  }

	/*
   * Button scroll menu
   */
  $('.js-scrollmenu').click(function(){
      if ( $( this ).hasClass( "active" ) ) {
      	$('.main-nav').animate({ scrollLeft: "-=450" }, 350);
      	$( this ).toggleClass("active");
			} else {
      	$('.main-nav').animate({ scrollLeft: "+=450" }, 350);
      	$( this ).toggleClass("active");
      }
  });

  /*
   * Button scroll block
   */

  var scrollContents = function() {

    if ( $('.js-scrollblock').length ) {
      // Get elements & position
      var wrapper = $('.block__scroll-wrapper');
      var firstItem = $('a.card:first-of-type');
      var fip = firstItem.position().left;
      var fipi = fip; // initial offset for first card
      console.log("first ever fipi = " + fipi);
    }

    $('.js-scrollblock').click(function(){
      // Get widths & this
      var ww = wrapper[0].scrollWidth;
      console.log("wrapper scrollWidth = " + ww);
      var sw = $( window ).width();
      console.log("window width = " + sw);
      var $this = $(this);

      if ( $this.hasClass( "reverse" ) ) {

        wrapper.animate({ scrollLeft: "-=" + (sw - (fipi / 2) ) },
          { complete: function(){
              var fip = firstItem.position().left;
              console.log("new fip after scroll left = " + ( -fip - fipi ));

              if ( ( fip - fipi ) == 0 ) {
                $this.toggleClass("reverse");
              }
            }
          },
        500);

      } else {

        wrapper.animate({ scrollLeft: "+=" + (sw - (fipi / 2) ) },
          { complete: function(){
              var fip = firstItem.position().left;
              console.log("new fip after scroll right = " + ( -fip + fipi ));
              console.log("result = " + (( -fip + fipi) >= ( ww - sw )) );

              if ( ( -fip + fipi) == ( ww - sw )  ) {
                $this.toggleClass("reverse");
              }
            }
          },
        500);
      }

      // console.log( "firstitem position - firstitem initial position = " + (fip - fipi) );
      // console.log( "wrapperwidth - screenwidth = " + (ww - sw) );
      // document.activeElement = null;
    });
  }

  scrollContents();

/*
 *
 *  Resize-Listener
 */

  // var resizeTimer;

  // $(window).on('resize', function(e) {

  //   clearTimeout(resizeTimer);
  //   resizeTimer = setTimeout(function() {

  //   if ( $('.js-scrollblock').length ) {
  //     fip = $('a.card:first-of-type').position().left;
  //     console.log("FIP after resize = " + fip);
  //   }

  //   scrollContents(fip);

  //   }, 2000);

  // });

  // $(window).resize(function() {
  //   clearTimeout(window.resizedFinished);
  //   window.resizedFinished = setTimeout(function(){
  //     if ( $('.js-scrollblock').length ) {
  //       fip = $('a.card:first-of-type').position().left;
  //       console.log('Resized finished.');
  //       console.log("FIP after resize = " + fip);
  //       scrollContents(fip);
  //     }
  //   }, 250);
  // });

  var screen = window; //To access the dom only once
  var cWidth = $( window ).width();
  var newWidth = cWidth; //If you want a log to show at startup, change to: newWidth = 0
  console.log("Initial newWidth:", newWidth);

  $(window).resize(function() {
    clearTimeout(window.resizedFinished);
    window.resizedFinished = setTimeout(function(){

      newWidth = $( window ).width();
      console.log("New newWidth in window.resize:", newWidth);
      console.log("cWidth in window.resize:", cWidth);
      if(cWidth != newWidth){
          cWidth = newWidth;
          console.log("clientWidth:", cWidth); //instead of alert(cWidth);
          // fip = $('a.card:first-of-type').position().left;

          // Unbind the click event, otherwise the scroll would accumulate
          // with every resize.
          $('.js-scrollblock').off("click");
          scrollContents();
       };

    }, 500);
  });

});<|endoftext|>


<commit_before>
/**
 * globals
 */
game = null;
input = null;

/**
 * main game object class
 */
var HopeGame = {

	init: function() {
		this.player = null;
		this.bkg = null;

		/**
		 * map data
		 */
		this.map = null;
		this.map_base = null;
		this.map_collide = null;
	},

	/**
	 * preload resources
	 */
	preload: function() {
		debug('preloading resources');
		game.load.image('sprites/space_bkg', 'res/sprites/space_bg.png');
		game.load.image('tilesheets/dev', 'res/tilesheets/dev.png');
		game.load.spritesheet('spritesheets/player_dev',
			'res/spritesheets/player_dev.png', 32, 32, 8);
		game.load.tilemap('maps/test', 'res/maps/test.json', null,
			Phaser.Tilemap.TILED_JSON);
	},

	/**
	 * resources loaded - init game
	 */
	create: function() {
		debug('preloaded resources', 'success');
		debug('starting game');
		game.physics.startSystem(Phaser.Physics.ARCADE);
		this.bkg = game.add.tileSprite(0, 0, game.width, game.height,
			'sprites/space_bkg');
		this.map = game.add.tilemap('maps/test');

		/**
		 * todo: make new dev/test map with more relevant tileset name
		 */
		this.map.addTilesetImage('wex_dev', 'tilesheets/dev');

		this.map_base = this.map.createLayer('base');
		this.map_base.visible = true;

		this.map_collide = this.map.createLayer('collision');
		this.map_collide.visible = false;
		this.map_collide.immovable = true;
		this.map_collide.enableBody = true;

		this.map.setCollision([36], true, this.map_collide);
		game.world.setBounds(0, 0, 640, 360);
		this.map_base.resizeWorld();

		/**
		 * bring player into the world
		 */
		this.player = Object.create(Player);
		this.player.init();
		game.camera.follow(this.player.sprite,
			Phaser.Camera.FOLLOW_PLATFORMER);
	},

	update: function() {
		game.physics.arcade.collide(this.player.sprite,
			this.map_collide);
		this.player.update();
	},
};

/**
 * init game objects
 */
window.onload = function() {
	debug('hope started', 'success');

	/**
	 * configure input
	 */
	input = Object.create(Input);
	input.init(document);
	input.bind([
		{name: 'up', code: [38, 87],
			preventDefault: true, callback: null},
		{name: 'down', code: [40, 83],
			preventDefault: true, callback: null},
		{name: 'left', code: [37, 65],
			preventDefault: true, callback: null},
		{name: 'right', code: [39, 68],
			preventDefault: true, callback: null},
	]);

	/**
	 * init phaser
	 */
	game = new Phaser.Game(640, 360, Phaser.AUTO, 'main');

	/**
	 * game states
	 */
	game.state.add('main', HopeGame);

	/**
	 * init state chain
	 */
	game.state.start('main');
};

<commit_msg>added test resize code<commit_after>
/**
 * globals
 */
game = null;
input = null;

/**
 * main game object class
 */
var HopeGame = {

	init: function() {
		this.player = null;
		this.bkg = null;

		/**
		 * map data
		 */
		this.map = null;
		this.map_base = null;
		this.map_collide = null;

		/**
		 * extra dom events
	 	 */
		window.addEventListener('resize', function(e) {
			try_resize_game();
		});
		try_resize_game();
	},

	/**
	 * preload resources
	 */
	preload: function() {
		debug('preloading resources');
		game.load.image('sprites/space_bkg', 'res/sprites/space_bg.png');
		game.load.image('tilesheets/dev', 'res/tilesheets/dev.png');
		game.load.spritesheet('spritesheets/player_dev',
			'res/spritesheets/player_dev.png', 32, 32, 8);
		game.load.tilemap('maps/test', 'res/maps/test.json', null,
			Phaser.Tilemap.TILED_JSON);
	},

	/**
	 * resources loaded - init game
	 */
	create: function() {
		debug('preloaded resources', 'success');
		debug('starting game');
		game.physics.startSystem(Phaser.Physics.ARCADE);
		this.bkg = game.add.tileSprite(0, 0, game.width, game.height,
			'sprites/space_bkg');
		this.map = game.add.tilemap('maps/test');

		/**
		 * todo: make new dev/test map with more relevant tileset name
		 */
		this.map.addTilesetImage('wex_dev', 'tilesheets/dev');

		this.map_base = this.map.createLayer('base');
		this.map_base.visible = true;

		this.map_collide = this.map.createLayer('collision');
		this.map_collide.visible = false;
		this.map_collide.immovable = true;
		this.map_collide.enableBody = true;

		this.map.setCollision([36], true, this.map_collide);
		game.world.setBounds(0, 0, 640, 360);
		this.map_base.resizeWorld();

		/**
		 * bring player into the world
		 */
		this.player = Object.create(Player);
		this.player.init();
		game.camera.follow(this.player.sprite,
			Phaser.Camera.FOLLOW_PLATFORMER);
	},

	update: function() {
		game.physics.arcade.collide(this.player.sprite,
			this.map_collide);
		this.player.update();
	},
};

/**
 * helper function to resize game based on window width/height
 * will only resize when necessary
 */
var try_resize_game = function() {
	debug(game.width);
	debug(game.height);
	debug(window.innerWidth);
	debug(window.innerHeight);
	if (window.innerWidth < 1280 || window.innerHeight <= 720) {
		if (game.width != 640 && game.height != 320) {
			debug('resize 640x320');
		}
	}
	else if (window.innerWidth < 1920 || window.innerHeight < 1080) {
		if (game.width != 1280 && game.height != 720) {
			debug('resize 1280x720');
		}
	}
	else if (window.innerWidth >= 1920 && window.innerHeight >= 1080) {
		if (game.width != 1920 && game.width != 1080) {
			debug('resize 1920x1080');
		}
	}
	// game.stage.smoothed = false;
};

/**
 * init game objects
 */
window.onload = function() {
	debug('hope started', 'success');

	/**
	 * configure input
	 */
	input = Object.create(Input);
	input.init(document);
	input.bind([
		{name: 'up', code: [38, 87],
			preventDefault: true, callback: null},
		{name: 'down', code: [40, 83],
			preventDefault: true, callback: null},
		{name: 'left', code: [37, 65],
			preventDefault: true, callback: null},
		{name: 'right', code: [39, 68],
			preventDefault: true, callback: null},
	]);

	/**
	 * init phaser
	 */
	game = new Phaser.Game(640, 360, Phaser.AUTO, 'main');

	/**
	 * game states
	 */
	game.state.add('main', HopeGame);

	/**
	 * init state chain
	 */
	game.state.start('main');
};

<|endoftext|>


<commit_before>import React from 'react'
import Helmet from 'react-helmet'

import { prefixLink } from 'gatsby-helpers'
import { TypographyStyle } from 'utils/typography'

export default class extends React.Component {
  static propTypes = {
    title: React.PropTypes.string,
  }

  render () {
    const head = Helmet.rewind()

    let cssLink
    if (process.env.NODE_ENV === 'production') {
      cssLink = <link rel="stylesheet" href={prefixLink('/styles.css')} />
    }

    return (

          <meta charSet="utf-8" />
          <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0 maximum-scale=1.0"
          />
          <meta name="theme-color" content="#f3df49" />
          {head.title.toComponent()}
          {head.meta.toComponent()}
          {head.link.toComponent()}
          <link rel="shortcut icon" href={this.props.favicon} />
          <TypographyStyle />
          {cssLink}


<commit_before>function injectBorders() {
    var now = new Date();
    var changed = [];
    now = new Date(now.getFullYear(), now.getMonth(), now.getDate());

    for (var i = 0; i < subjects.length; i++) {
        var object = subjects[i];

        var rawLastUpdated = getLastUpdated(object);
        var year = rawLastUpdated.slice(6);
        var month = rawLastUpdated.slice(3, (rawLastUpdated.length - 3)) - 1;
        var day = rawLastUpdated.slice(0, rawLastUpdated.length - 6);
        var lastUpdated = new Date('20' + year, month, day);

        var twoWeeks = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 14);
        if (lastUpdated > twoWeeks) {
            object.style.border = '2px solid #0596A6';
            changed.push(getNameOfLecture(object));
        } else {
            object.style.border = '2px solid #435779';
        }
    }

    if (changed.length <= 3) {
        for (var i = 0; i < changed.length; i++) {
            toastr.info('Es gab eine Änderung innerhalb der letzten 2 Wochen im Fach ' + changed[i], 'Änderung');
        }
    } else {
        toastr.info('Es gab eine Änderung innerhalb der letzten 2 Wochen in mehr als 3 Fächern', 'Änderung');
    }
}<commit_msg>change background color of changed at<commit_after>function injectBorders() {
    var now = new Date();
    var changed = [];
    now = new Date(now.getFullYear(), now.getMonth(), now.getDate());

    for (var i = 0; i < subjects.length; i++) {
        var object = subjects[i];

        var rawLastUpdated = getLastUpdated(object);
        var year = rawLastUpdated.slice(6);
        var month = rawLastUpdated.slice(3, (rawLastUpdated.length - 3)) - 1;
        var day = rawLastUpdated.slice(0, rawLastUpdated.length - 6);
        var lastUpdated = new Date('20' + year, month, day);

        var twoWeeks = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 14);
        if (lastUpdated > twoWeeks) {
            object.style.border = '2px solid #435779';
            object.childNodes[5].childNodes[3].childNodes[0].childNodes[13].style.background = '#ea6a68';
            object.childNodes[5].childNodes[3].childNodes[0].childNodes[13].style.color = 'white';
            changed.push(getNameOfLecture(object));
        } else {
            object.style.border = '2px solid #435779';
        }
    }

    if (changed.length <= 3) {
        for (var i = 0; i < changed.length; i++) {
            toastr.info('Es gab eine Änderung innerhalb der letzten 2 Wochen im Fach ' + changed[i], 'Änderung');
        }
    } else {
        toastr.info('Es gab eine Änderung innerhalb der letzten 2 Wochen in mehr als 3 Fächern', 'Änderung');
    }
}<|endoftext|>


<commit_before>/* Geena Http HttpClient
 *
 * This file is part of the geena.http package.
 * Copyright (c) 2013 Rhinostone <geena@rhinontone.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * HttpClient Constructor
 *
 * @constructor
 *
 * @param {opject} options
 * @param {object} [data]
 *
 * TODO - Support behind proxy query for insecure world
 * TODO - Download query, wget like
 * TODO - Unit tests and functional tests
 *
 * */
var HttpClient;

//Imports.
var http        = require('http'),
    utils       = require('geena').utils;
if (utils == undefined) {
    console.error('You need to install Geena: $ npm install geena');
    process.exit(1);
}
var logger      = utils.logger;

HttpClient = function(){
    var _this = this;

    var _data = {};

    var _options = {
        host    : undefined,
        path    : undefined,
        port    : undefined,
        method  : 'POST',
        agent   : false,
        headers : {
            'Content-Type': 'application/json',
            'Content-Length': _data.length
        }
    };

    this.getDefaultOptions  = function(){
        return _options;
    };

    this.query = function(options, data, callback){

        var queryData = {}, defaultOptions = _this.getDefaultOptions();
        var path = options.path;

        utils.extend(true, options, defaultOptions);

        //console.log("Querying ", "\n[0]" + options, "\n[1]" + data, "\n[2]" + callback);
        if (arguments.length <3) {
            if ( typeof(data) == 'function') {
                var callback = data;
                var data = undefined;
            } else {
                callback = undefined;
            }
        }
        //console.log("PATH => ", options.path, " VS ", data);
        //console.log(".....PRE details ", "\n[0]" + JSON.stringify(options, null, 4), "\n[1]" + JSON.stringify(data, null, 4), "\n[2]" + callback);

        if ( typeof(data) != "undefined" &&  data.count() > 0) {

            queryData = '?';

            for (var d in data) {
                if ( typeof(data[d]) == 'object') {
                    data[d] = JSON.stringify(data[d]);
                }
                queryData += d + '=' + data[d] + '&';
            }

            //console.log(".....details ", "\n[0]" + JSON.stringify(options, null, 4), "\n[1]" + JSON.stringify(data, null, 4), "\n[2]" + callback);
            queryData = queryData.substring(0, queryData.length-1);
            options.path += queryData;

            //Sample request.
            //options.path = '/updater/start?release={"version":"0.0.5-dev","url":"http://10.1.0.1:8080/project/bundle/repository/archive?ref=0.0.5-dev","date":1383669077141}&pid=46493';
        }

        queryData = JSON.stringify(queryData);
        //you need this, even for empty.
        options.headers['Content-Length'] = queryData.length;
        var req = http.request(options, function(res) {
            res.setEncoding('utf8');
            //console.log("STATUS ", res.statusCode );
            if (res.statusCode != 200) {
                var err = 'BAD connection or BAD serveur response on ' + options.host +  ':' +options.port +options.path;
                logger.error('etap', 'ETAP:HTTPAPI:ERR:1', err, __stack);
            } else {
                res.on('data', function (chunk) {
                    //Only when needed.
                    if ( typeof(callback) != "undefined") {
                        console.log("trying to callback ", typeof(callback));
                        callback( false, JSON.parse( chunk.toString() ) );
                    }
                });
            }

        })
        .write(queryData);
        //starting from from >0.10.15
//        .on('error', function(err){
//            logger.error(
//                'geena.http',
//                'GEENA:HTTP_CLIENT:ERR:1',
//                '['+options.host + '] must be down or refusing connection @ ' + options.host +  ':' +options.port +options.path,
//                __stack
//            );
//        });
//        if (!req) {
//            logger.error(
//                'geena.http',
//                'GEENA:HTTP_CLIENT:ERR:2',
//                '['+options.host + '] must be down or refusing connection @ ' + options.host +  ':' +options.port +options.path,
//                __stack
//            );
//        }

    };

    this.download  = function(url, target, callback){
        //callback(err)
    };

};

module.exports = HttpClient;<commit_msg>Handled connection error<commit_after>/* Geena Http HttpClient
 *
 * This file is part of the geena.http package.
 * Copyright (c) 2013 Rhinostone <geena@rhinontone.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * HttpClient Constructor
 *
 * @constructor
 *
 * @param {opject} options
 * @param {object} [data]
 *
 * TODO - Support behind proxy query for insecure world
 * TODO - Download query, wget like
 * TODO - Unit tests and functional tests
 *
 * */
var HttpClient;

//Imports.
var http        = require('http'),
    utils       = require('geena').utils;
if (utils == undefined) {
    console.error('You need to install Geena: $ npm install geena');
    process.exit(1);
}
var logger      = utils.logger;

HttpClient = function(){
    var _this = this;

    var _data = {};

    var _options = {
        host    : undefined,
        path    : undefined,
        port    : undefined,
        method  : 'POST',
        agent   : false,
        headers : {
            'Content-Type': 'application/json',
            'Content-Length': _data.length
        }
    };

    this.getDefaultOptions  = function(){
        return _options;
    };

    this.query = function(options, data, callback){

        var queryData = {}, defaultOptions = _this.getDefaultOptions();
        var path = options.path;

        utils.extend(true, options, defaultOptions);

        //console.log("Querying ", "\n[0]" + options, "\n[1]" + data, "\n[2]" + callback);
        if (arguments.length <3) {
            if ( typeof(data) == 'function') {
                var callback = data;
                var data = undefined;
            } else {
                callback = undefined;
            }
        }
        //console.log("PATH => ", options.path, " VS ", data);
        //console.log(".....PRE details ", "\n[0]" + JSON.stringify(options, null, 4), "\n[1]" + JSON.stringify(data, null, 4), "\n[2]" + callback);

        if ( typeof(data) != "undefined" &&  data.count() > 0) {

            queryData = '?';

            for (var d in data) {
                if ( typeof(data[d]) == 'object') {
                    data[d] = JSON.stringify(data[d]);
                }
                queryData += d + '=' + data[d] + '&';
            }

            //console.log(".....details ", "\n[0]" + JSON.stringify(options, null, 4), "\n[1]" + JSON.stringify(data, null, 4), "\n[2]" + callback);
            queryData = queryData.substring(0, queryData.length-1);
            options.path += queryData;

            //Sample request.
            //options.path = '/updater/start?release={"version":"0.0.5-dev","url":"http://10.1.0.1:8080/project/bundle/repository/archive?ref=0.0.5-dev","date":1383669077141}&pid=46493';
        }

        queryData = JSON.stringify(queryData);
        //you need this, even for empty.
        options.headers['Content-Length'] = queryData.length;
        var req = http.request(options, function(res) {
            //Maybe useless ???.
            if (res.statusCode != 200) {
                var err = 'BAD connection or BAD serveur response on ' + options.host +  ':' +options.port +options.path;
                logger.error('etap', 'ETAP:HTTPAPI:ERR:1', err, __stack);
                if ( typeof(callback) != "undefined") {
                    callback(err);
                }
            } else {
                res.on('data', function (chunk) {
                    //Only when needed.
                    if ( typeof(callback) != "undefined") {
                        console.log("trying to callback ", typeof(callback));
                        callback( false, JSON.parse( chunk.toString() ) );
                    }
                });
            }

        });
        if (req) {
            req.write(queryData);
        }
        //starting from from >0.10.15
        req.on('error', function(err){
            logger.error(
                'geena.http',
                'GEENA:HTTP_CLIENT:ERR:1',
                '['+options.host + '] must be down or refusing connection @ ' + options.host +  ':' +options.port +options.path,
                __stack
            );
            if ( typeof(callback) != "undefined") {
                err.stack += '\nat    '+__stack;
                callback(err);
            }
        });
    };

    this.download  = function(url, target, callback){
        //callback(err)
    };

};

module.exports = HttpClient;<|endoftext|>


<commit_before>// Handle search query states
// Listens for changes in query string, then ensures that provided values are coherent,
// and if all is fine emits valid query objects
// (which are usually consumed by list managers to update state of tables)

'use strict';

var ensureObject     = require('es5-ext/object/valid-object')
  , ensureString     = require('es5-ext/object/validate-stringifiable-value')
  , once             = require('timers-ext/once')
  , fixLocationQuery = require('./fix-location-query')
  , QueryHandler     = require('./utils/query-handler');

module.exports = function (handlersList, appLocation, pathname) {
	var queryHandler, update;
	appLocation = ensureObject(appLocation);
	pathname = ensureString(pathname);
	queryHandler = new QueryHandler(handlersList);
	update = once(function () {
		if (pathname !== appLocation.pathname) return;
		try {
			queryHandler.resolve(appLocation.query);
		} catch (e) {
			if (!e.queryHandler) throw e;
			fixLocationQuery(e.queryHandler.name, e.fixedQueryValue);
			return;
		}
	});
	queryHandler._handlers.forEach(function (handler) {
		appLocation.query.get(handler.name).on('change', update);
	});
	appLocation.on('change', update);
	update();
	return queryHandler;
};
<commit_msg>Fix require paths<commit_after>// Handle search query states
// Listens for changes in query string, then ensures that provided values are coherent,
// and if all is fine emits valid query objects
// (which are usually consumed by list managers to update state of tables)

'use strict';

var ensureObject     = require('es5-ext/object/valid-object')
  , ensureString     = require('es5-ext/object/validate-stringifiable-value')
  , once             = require('timers-ext/once')
  , fixLocationQuery = require('./fix-location-query')
  , QueryHandler     = require('./query-handler');

module.exports = function (handlersList, appLocation, pathname) {
	var queryHandler, update;
	appLocation = ensureObject(appLocation);
	pathname = ensureString(pathname);
	queryHandler = new QueryHandler(handlersList);
	update = once(function () {
		if (pathname !== appLocation.pathname) return;
		try {
			queryHandler.resolve(appLocation.query);
		} catch (e) {
			if (!e.queryHandler) throw e;
			fixLocationQuery(e.queryHandler.name, e.fixedQueryValue);
			return;
		}
	});
	queryHandler._handlers.forEach(function (handler) {
		appLocation.query.get(handler.name).on('change', update);
	});
	appLocation.on('change', update);
	update();
	return queryHandler;
};
<|endoftext|>