<commit_before>const Config                    = use("config");
const Controllers               = use('core/controllers');
const Factories                 = use('core/factories');

const OpenApi = {

    generate() {
        return Object.values(this.sections).reduce((obj, section) => {
            return Object.assign(obj, section.apply(this, arguments));
        }, {});
    },

    sections: {
        _version:    (meta) => {return {"swagger": "2.0"}},

        _info:       (meta) => {return {"info": {
                "title": meta.title,
                "description": meta.description,
                "version": meta.version,
            }
        }},
        _host:       (meta) => {return {"host": Config.server.url.replace(/https?:\/\//,"")}},
        _basePath:   (meta) => {return {"basePath": "/" + Config.router.urlPrefix.slice(0, -1)}},
        _schemes:    (meta) => {return {"schemes": ["https"]}},
        _tags:       (meta) => {return {"tags": [...Controllers.get()].map(([tag]) => {return {"name": tag}} ).sort((a,b) => a.name.toLowerCase() < b.name.toLowerCase()? -1 : 1)}},
        _definitions:(meta) => {return {"definitions": OpenApi._definitions()}},
        _paths:      (meta) => {return {"paths": OpenApi._paths()}},
        _securityDef:(meta) => {return {"securityDefinitions": {
                "Permission": {
                    "description": "Provides access to private API's",
                    "type": "oauth2",
                    "authorizationUrl": "https://dev.friskyradio.com/auth",
                    "flow": "implicit",
                    "scopes": OpenApi._permissionScopes
                },
                "Root permission": {
                    "description": "Provides root access to private API's",
                    "type": "oauth2",
                    "authorizationUrl": "https://dev.friskyradio.com/auth",
                    "flow": "implicit",
                    "scopes": OpenApi._permissionRootScopes
                }
            }
        }}
    },

    _models() {
        return [...Controllers.get()].map(([tag, route]) => {
            try {
                const modelName = tag.split("\/").map(cap => cap[0].toUpperCase() + cap.substring(1)).join('');
                return Factories(modelName);
            }catch(e){
                return null;
            }
        }).filter(model => model);
    },

    _definitions() {
        const models = this._models();
        return models.reduce((definition, model) => {
            definition[model.__model__.name] = {
                "type": "object",
                "xml": {
                    "name": model.__model__.name
                },
                "required": [],
                "properties": {}
            };

            definition[`${model.__model__.name} Reference`] = {
                "type": "object",
                "xml": {
                    "name": `${model.__model__.name} Reference`
                },
                "required": [],
                "properties": {
                    "id": {"type": "number", "example": 42},
                    "model": {"type": "string", "example": model.__model__.name},
                    "link": {"type": "string", "example": `${model.__model__.name.toLowerCase()}/42`}
                }
            };

            Object.entries(model.__model__.prototype.scheme).forEach(([propertyName, property]) => {
                if([...property._outputModifications].some(modificatorFunction => modificatorFunction.name === "hidden")){
                    return null;
                }

                definition[model.__model__.name].properties[propertyName] = this._propertyType(property);

                if([...property._validators].some(validatorFunction => validatorFunction.name === "required")){
                    definition[model.__model__.name].required.push(propertyName);
                }
            });

            if(!definition[model.__model__.name].required.length) {
                delete definition[model.__model__.name].required;
            }

            return definition;
        }, {});
    },

    _propertyType(property) {
        const types = {
            "none": (property) => { return {
                "type": "undefined",
                "format": "undefined",
                "example": "undefined"
            }},
            "NumberProperty": (property) => { return {
                "type": "number",
                "example": property.documentationExampleValue || 42
            }},
            "StringProperty": (property) => { return {
                "type": "string",
                "example": property.documentationExampleValue || "string literal"
            }},
            "ObjectProperty": (property) => { return {
                "type": "object",
                "example": property.documentationExampleValue || {}
            }},
            "DateProperty": (property) => { return {
                "type": "string",
                "format": "Date ISO 8601",
                "example": property.documentationExampleValue || "2018-07-30T16:52:00.192Z"
            }},
            "EnumProperty": (property) => { return {
                "type": "string",
                "enum": property.valuesList,
                "example": property.documentationExampleValue || property.valuesList[0]
            }},
            "SetProperty": (property) => { return {
                "type": "array",
                "items": {
                    "type": "string",
                    "enum": property.valuesList
                },
                "example": property.documentationExampleValue || [property.valuesList[0], property.valuesList[1]]
            }},
            "ModelProperty": (property) => { return {
                "$ref": `#/definitions/${property.modelName} Reference`
            }}
        };

        if(types[property.constructor.name]){
            return types[property.constructor.name](property);
        } else {
            return types["none"];
        }
    },

    _paths() {
        const paths = {};

        [...Controllers.get()].forEach(([controllerName, apis]) => {
            apis.reduce((paths, route) => {
                let argIndex = 0;
                let collection = true;
                let path, modelName;
                controllerName = controllerName.split("\/").map(cap => cap[0].toUpperCase() + cap.substring(1)).join('');

                if (this._models().map(model => model.__model__.name).includes(controllerName)) {
                    modelName = controllerName;
                }

                if (route.annotations.model && modelName) {
                    throw new Error(`Violation of API structure rules. Route can not return different than declared model. Route "${route.pattern}" is expected to return "${modelName}", but returns "${route.annotations.model}"`);
                }

                if (route.annotations.model) {
                    modelName = toCapitalCase(route.annotations.model);
                }

                let uri = "/" + (route.pattern.toString().split("(?:\\?")[0].replace(Config.router.urlPrefix.replace(/\//g, "\\/"), "").match(/\w+|\(\\d\+\)/g) || ["/"]).map((section, index, map)=> {
                    if((section === "(\\d+)" && index === map.length - 1) || route.method === "POST") {
                        collection = false;
                    }

                    return section === "(\\d+)" ? "{" + route.arguments.required[argIndex++].name + (Config.router.primaryKeyPattern === "\\d+" ? "Id" : "Uuid") + "}" : section;
                }).join('/');

                if(!paths[uri]) {
                    paths[uri] = {};
                }
                if(paths[uri][route.method.toLowerCase()]) {
                    uri += (route.arguments.optional.length? " [? " + route.arguments.optional.map(arg => arg.name).join("=, ") + "=]" : "");
                    paths[uri] = {};
                }

                path = paths[uri][route.method.toLowerCase()] = {
                    "tags": [
                        modelName || controllerName
                    ],
                    "deprecated": !!route.annotations.deprecated,
                    "consumes": ["application/json"],
                    "produces": ["application/json"],
                    "summary": route.annotations.summary? toCapitalCase(route.annotations.summary) :
                        ({"GET": "Get", "POST": "Create", "PUT": "Update", "DELETE": "Remove", "OPTIONS": "Ping"}[route.method] + ` ${modelName} ${collection? "collection" : "instance"}`),
                    "description": route.annotations.description,
                    "operationId": route.method + uri + route.arguments.optional.map(arg => toCapitalCase(arg.name)).join(""),
                    "parameters": [],
                    "responses": {}
                };
                route.arguments.required.forEach(arg => {
                    path["parameters"].push({
                        "name": arg.name + (Config.router.primaryKeyPattern === "\\d+" ? "Id" : "Uuid"),
                        "in": "path",
                        "required": true,
                        "type": Config.router.primaryKeyPattern === "\\d+" ? "integer" : "uid"
                    });
                });
                route.arguments.optional.forEach(arg => {
                    path["parameters"].push({
                        "name": arg.name,
                        "in": "query",
                        "required": false,
                        "type": "string"
                    });
                });

                if (modelName) {
                    if (route.method === "GET") {
                        path["responses"]["200"] = collection?
                            {
                                "description": `Collection of ${modelName} instances, empty array if not found`,
                                "schema": {
                                    "type": "array",
                                    "items": {
                                        "$ref": `#/definitions/${modelName}`
                                    }
                                }
                            }
                            :
                            {
                                "description": `Instance of ${modelName} model`,
                                "schema": {
                                    "$ref": `#/definitions/${modelName}`
                                }
                            };
                        if (!collection) {
                            path["responses"]["404"] = {
                                "description": `Instance of ${modelName} model was not found.`,
                            };
                        }
                    }

                    if (route.method === "POST") {
                        path["parameters"].push({
                            "name": "model",
                            "in": "body",
                            "description": `Instance of ${modelName} model`,
                            "required": true,
                            "schema": {
                                "$ref": `#/definitions/${modelName}`
                            }
                        });

                        path["responses"]["201"] = {
                            "description": `Created instance of ${modelName} model`,
                            "schema": {
                                "$ref": `#/definitions/${modelName}`
                            }
                        };
                    }

                    if (route.method === "PUT") {
                        path["parameters"].push({
                            "name": "model",
                            "in": "body",
                            "description": `Instance of ${modelName} model`,
                            "required": true,
                            "schema": {
                                "$ref": `#/definitions/${modelName}`
                            }
                        });

                        path["responses"]["200"] = {
                            "description": `Updated instance of ${modelName} model`,
                            "schema": {
                                "$ref": `#/definitions/${modelName}`
                            }
                        };
                    }

                    if (route.method === "DELETE") {
                        path["responses"]["204"] = {
                            "description": `Instance of ${modelName} model successfuly removed`,
                        };
                    }

                } else {
                    path["responses"]["200"] = {
                        "description": `Success`,
                    };
                }

                if (route.permission) {
                    path["responses"]["401"] = {
                        "description": `Authorization token is missing or invalid`,
                    };
                    path["responses"]["403"] = {
                        "description": `Request is authenticated but doesn't have required permissions`,
                    };

                    path["security"] = [
                        {"Permission": [route.permission] }
                    ];

                    this._permissionScopes[route.permission] = `Permission to ${route.permission.split(".")[1]} ${route.permission.split(".")[0]}`;

                    if(route.annotations.rootownerpermissions) {
                        path["security"].push(
                            {"Root permission": [route.annotations.rootownerpermissions] }
                        );
                        this._permissionRootScopes[route.annotations.rootownerpermissions] = `Root access to ${route.annotations.rootownerpermissions.split(".")[0]}`;
                    }

                }

                if(!path["parameters"].length){
                    delete paths[uri][route.method.toLowerCase()].parameters;
                }

                return paths;
            }, paths);
        });
        return paths;
    },

    _permissionScopes: {},
    _permissionRootScopes: {},

};

function toCapitalCase(str) {
    return str[0].toUpperCase() + str.slice(1);
}

module.exports = OpenApi;
<commit_msg>Update index.js<commit_after>const Config                    = use("config");
const Controllers               = use('core/controllers');
const Factories                 = use('core/factories');

const OpenApi = {

    generate() {
        return Object.values(this.sections).reduce((obj, section) => {
            return Object.assign(obj, section.apply(this, arguments));
        }, {});
    },

    sections: {
        _version:    (meta) => {return {"swagger": "2.0"}},

        _info:       (meta) => {return {"info": {
                "title": meta.title,
                "description": meta.description,
                "version": meta.version,
            }
        }},
        _host:       (meta) => {return {"host": Config.server.apiUrl.replace(/https?:\/\//,"")}},
        _basePath:   (meta) => {return {"basePath": "/" + Config.router.urlPrefix.slice(0, -1)}},
        _schemes:    (meta) => {return {"schemes": ["https"]}},
        _tags:       (meta) => {return {"tags": [...Controllers.get()].map(([tag]) => {return {"name": tag}} ).sort((a,b) => a.name.toLowerCase() < b.name.toLowerCase()? -1 : 1)}},
        _definitions:(meta) => {return {"definitions": OpenApi._definitions()}},
        _paths:      (meta) => {return {"paths": OpenApi._paths()}},
        _securityDef:(meta) => {return {"securityDefinitions": {
                "Permission": {
                    "description": "Provides access to private API's",
                    "type": "oauth2",
                    "authorizationUrl": "https://dev.friskyradio.com/auth",
                    "flow": "implicit",
                    "scopes": OpenApi._permissionScopes
                },
                "Root permission": {
                    "description": "Provides root access to private API's",
                    "type": "oauth2",
                    "authorizationUrl": "https://dev.friskyradio.com/auth",
                    "flow": "implicit",
                    "scopes": OpenApi._permissionRootScopes
                }
            }
        }}
    },

    _models() {
        return [...Controllers.get()].map(([tag, route]) => {
            try {
                const modelName = tag.split("\/").map(cap => cap[0].toUpperCase() + cap.substring(1)).join('');
                return Factories(modelName);
            }catch(e){
                return null;
            }
        }).filter(model => model);
    },

    _definitions() {
        const models = this._models();
        return models.reduce((definition, model) => {
            definition[model.__model__.name] = {
                "type": "object",
                "xml": {
                    "name": model.__model__.name
                },
                "required": [],
                "properties": {}
            };

            definition[`${model.__model__.name} Reference`] = {
                "type": "object",
                "xml": {
                    "name": `${model.__model__.name} Reference`
                },
                "required": [],
                "properties": {
                    "id": {"type": "number", "example": 42},
                    "model": {"type": "string", "example": model.__model__.name},
                    "link": {"type": "string", "example": `${model.__model__.name.toLowerCase()}/42`}
                }
            };

            Object.entries(model.__model__.prototype.scheme).forEach(([propertyName, property]) => {
                if([...property._outputModifications].some(modificatorFunction => modificatorFunction.name === "hidden")){
                    return null;
                }

                definition[model.__model__.name].properties[propertyName] = this._propertyType(property);

                if([...property._validators].some(validatorFunction => validatorFunction.name === "required")){
                    definition[model.__model__.name].required.push(propertyName);
                }
            });

            if(!definition[model.__model__.name].required.length) {
                delete definition[model.__model__.name].required;
            }

            return definition;
        }, {});
    },

    _propertyType(property) {
        const types = {
            "none": (property) => { return {
                "type": "undefined",
                "format": "undefined",
                "example": "undefined"
            }},
            "NumberProperty": (property) => { return {
                "type": "number",
                "example": property.documentationExampleValue || 42
            }},
            "StringProperty": (property) => { return {
                "type": "string",
                "example": property.documentationExampleValue || "string literal"
            }},
            "ObjectProperty": (property) => { return {
                "type": "object",
                "example": property.documentationExampleValue || {}
            }},
            "DateProperty": (property) => { return {
                "type": "string",
                "format": "Date ISO 8601",
                "example": property.documentationExampleValue || "2018-07-30T16:52:00.192Z"
            }},
            "EnumProperty": (property) => { return {
                "type": "string",
                "enum": property.valuesList,
                "example": property.documentationExampleValue || property.valuesList[0]
            }},
            "SetProperty": (property) => { return {
                "type": "array",
                "items": {
                    "type": "string",
                    "enum": property.valuesList
                },
                "example": property.documentationExampleValue || [property.valuesList[0], property.valuesList[1]]
            }},
            "ModelProperty": (property) => { return {
                "$ref": `#/definitions/${property.modelName} Reference`
            }}
        };

        if(types[property.constructor.name]){
            return types[property.constructor.name](property);
        } else {
            return types["none"];
        }
    },

    _paths() {
        const paths = {};

        [...Controllers.get()].forEach(([controllerName, apis]) => {
            apis.reduce((paths, route) => {
                let argIndex = 0;
                let collection = true;
                let path, modelName;
                controllerName = controllerName.split("\/").map(cap => cap[0].toUpperCase() + cap.substring(1)).join('');

                if (this._models().map(model => model.__model__.name).includes(controllerName)) {
                    modelName = controllerName;
                }

                if (route.annotations.model && modelName) {
                    throw new Error(`Violation of API structure rules. Route can not return different than declared model. Route "${route.pattern}" is expected to return "${modelName}", but returns "${route.annotations.model}"`);
                }

                if (route.annotations.model) {
                    modelName = toCapitalCase(route.annotations.model);
                }

                let uri = "/" + (route.pattern.toString().split("(?:\\?")[0].replace(Config.router.urlPrefix.replace(/\//g, "\\/"), "").match(/\w+|\(\\d\+\)/g) || ["/"]).map((section, index, map)=> {
                    if((section === "(\\d+)" && index === map.length - 1) || route.method === "POST") {
                        collection = false;
                    }

                    return section === "(\\d+)" ? "{" + route.arguments.required[argIndex++].name + (Config.router.primaryKeyPattern === "\\d+" ? "Id" : "Uuid") + "}" : section;
                }).join('/');

                if(!paths[uri]) {
                    paths[uri] = {};
                }
                if(paths[uri][route.method.toLowerCase()]) {
                    uri += (route.arguments.optional.length? " [? " + route.arguments.optional.map(arg => arg.name).join("=, ") + "=]" : "");
                    paths[uri] = {};
                }

                path = paths[uri][route.method.toLowerCase()] = {
                    "tags": [
                        modelName || controllerName
                    ],
                    "deprecated": !!route.annotations.deprecated,
                    "consumes": ["application/json"],
                    "produces": ["application/json"],
                    "summary": route.annotations.summary? toCapitalCase(route.annotations.summary) :
                        ({"GET": "Get", "POST": "Create", "PUT": "Update", "DELETE": "Remove", "OPTIONS": "Ping"}[route.method] + ` ${modelName} ${collection? "collection" : "instance"}`),
                    "description": route.annotations.description,
                    "operationId": route.method + uri + route.arguments.optional.map(arg => toCapitalCase(arg.name)).join(""),
                    "parameters": [],
                    "responses": {}
                };
                route.arguments.required.forEach(arg => {
                    path["parameters"].push({
                        "name": arg.name + (Config.router.primaryKeyPattern === "\\d+" ? "Id" : "Uuid"),
                        "in": "path",
                        "required": true,
                        "type": Config.router.primaryKeyPattern === "\\d+" ? "integer" : "uid"
                    });
                });
                route.arguments.optional.forEach(arg => {
                    path["parameters"].push({
                        "name": arg.name,
                        "in": "query",
                        "required": false,
                        "type": "string"
                    });
                });

                if (modelName) {
                    if (route.method === "GET") {
                        path["responses"]["200"] = collection?
                            {
                                "description": `Collection of ${modelName} instances, empty array if not found`,
                                "schema": {
                                    "type": "array",
                                    "items": {
                                        "$ref": `#/definitions/${modelName}`
                                    }
                                }
                            }
                            :
                            {
                                "description": `Instance of ${modelName} model`,
                                "schema": {
                                    "$ref": `#/definitions/${modelName}`
                                }
                            };
                        if (!collection) {
                            path["responses"]["404"] = {
                                "description": `Instance of ${modelName} model was not found.`,
                            };
                        }
                    }

                    if (route.method === "POST") {
                        path["parameters"].push({
                            "name": "model",
                            "in": "body",
                            "description": `Instance of ${modelName} model`,
                            "required": true,
                            "schema": {
                                "$ref": `#/definitions/${modelName}`
                            }
                        });

                        path["responses"]["201"] = {
                            "description": `Created instance of ${modelName} model`,
                            "schema": {
                                "$ref": `#/definitions/${modelName}`
                            }
                        };
                    }

                    if (route.method === "PUT") {
                        path["parameters"].push({
                            "name": "model",
                            "in": "body",
                            "description": `Instance of ${modelName} model`,
                            "required": true,
                            "schema": {
                                "$ref": `#/definitions/${modelName}`
                            }
                        });

                        path["responses"]["200"] = {
                            "description": `Updated instance of ${modelName} model`,
                            "schema": {
                                "$ref": `#/definitions/${modelName}`
                            }
                        };
                    }

                    if (route.method === "DELETE") {
                        path["responses"]["204"] = {
                            "description": `Instance of ${modelName} model successfuly removed`,
                        };
                    }

                } else {
                    path["responses"]["200"] = {
                        "description": `Success`,
                    };
                }

                if (route.permission) {
                    path["responses"]["401"] = {
                        "description": `Authorization token is missing or invalid`,
                    };
                    path["responses"]["403"] = {
                        "description": `Request is authenticated but doesn't have required permissions`,
                    };

                    path["security"] = [
                        {"Permission": [route.permission] }
                    ];

                    this._permissionScopes[route.permission] = `Permission to ${route.permission.split(".")[1]} ${route.permission.split(".")[0]}`;

                    if(route.annotations.rootownerpermissions) {
                        path["security"].push(
                            {"Root permission": [route.annotations.rootownerpermissions] }
                        );
                        this._permissionRootScopes[route.annotations.rootownerpermissions] = `Root access to ${route.annotations.rootownerpermissions.split(".")[0]}`;
                    }

                }

                if(!path["parameters"].length){
                    delete paths[uri][route.method.toLowerCase()].parameters;
                }

                return paths;
            }, paths);
        });
        return paths;
    },

    _permissionScopes: {},
    _permissionRootScopes: {},

};

function toCapitalCase(str) {
    return str[0].toUpperCase() + str.slice(1);
}

module.exports = OpenApi;
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('mutant-ng-translate', [])
        .factory('$translateStorage', [translateStorage])
        .factory('$translateLoader', ['$http', '$q', translateLoader])
        .factory('$translateCache', ['$window', translateCache]);

    function translateStorage() {
        var self = this;

        self.langs = {};

        self.getValues = getValues;
        self.setValues = setValues;

        return self;

        function getValues(lang) {
            if (!self.langs.hasOwnProperty(lang)) {
                self.langs[lang] = {};
            }

            return self.langs[lang];
        }

        function setValues(lang, values) {
            if (!self.langs.hasOwnProperty(lang)) {
                self.langs[lang] = {};
            }

            angular.extend(self.langs[lang], values);
        }
    };

    function translateLoader($http, $q) {
        var self = this;

        self.loadPart = loadPart;

        return self;

        function loadPart(options) {
            var url = options
                .urlTemplate
                .replace(/{part}/g, options.part)
                .replace(/{lang}/g, options.lang);

            return $q(function (resolve, reject) {
                $http
                    .get(url)
                    .then(function (response) {
                        var values = options.dataTransformation(response.data);
                        resolve(values);
                    })
                    .catch(function (error) {
                        reject(error);
                    });
            });
        }
    };

    function translateCache($window) {
        var self = this;

        self.local = {
            prefix: 'mutant-ng-translate-',
            isSupported: isSupportLocalStorage(),
            storage: $window.localStorage,
            get: getFromLocalStorage,
            put: putToLocalStorage,
            exists: existsInLocalStorage
        };

        self.cache = {
            getValues: getValuesFromCache,
            setValues: setValuesToCache,
            getLang: getLangFromCache,
            setLang: setLangToCache
        };

        return self.cache;

        // LOCAL STORAGE
        function isSupportLocalStorage() {
            try {
                $window.localStorage.setItem('test', 'test');
                $window.localStorage.removeItem('test');

                return true;
            } catch (exception) {
                return false;
            }
        }

        function getFromLocalStorage(key) {
            return JSON.parse(self.local.storage[key]);
        };

        function putToLocalStorage(key, obj) {
            self.local.storage[key] = JSON.stringify(obj);
        };

        function existsInLocalStorage(key) {
            return !!self.local.storage[key];
        };

        // CACHE
        function getValuesFromCache(lang) {
            if (!self.local.isSupported) return {};

            var lsKey = self.local.prefix + lang;

            if (!self.local.exists(lsKey)) {
                self.local.put(lsKey, {});
            }

            return self.local.get(lsKey);
        }

        function setValuesToCache(lang, values) {
            if (!self.local.isSupported) return;

            var lsKey = self.local.prefix + lang;
            var cacheValues = self.cache.getValues(lang);

            angular.extend(cacheValues, values);

            self.local.put(lsKey, cacheValues);
        }

        function getLangFromCache() {
            var lsKey = self.local.prefix + 'lang';

            return self.local.get(lsKey);
        }

        function setLangToCache(lang) {
            var lsKey = self.local.prefix + 'lang';

            self.local.put(lsKey, lang);
        }
    };
    };
})();
<commit_msg>fix get from local storage method for empty value<commit_after>(function () {
    'use strict';

    angular
        .module('mutant-ng-translate', [])
        .factory('$translateStorage', [translateStorage])
        .factory('$translateLoader', ['$http', '$q', translateLoader])
        .factory('$translateCache', ['$window', translateCache]);

    function translateStorage() {
        var self = this;

        self.langs = {};

        self.getValues = getValues;
        self.setValues = setValues;

        return self;

        function getValues(lang) {
            if (!self.langs.hasOwnProperty(lang)) {
                self.langs[lang] = {};
            }

            return self.langs[lang];
        }

        function setValues(lang, values) {
            if (!self.langs.hasOwnProperty(lang)) {
                self.langs[lang] = {};
            }

            angular.extend(self.langs[lang], values);
        }
    };

    function translateLoader($http, $q) {
        var self = this;

        self.loadPart = loadPart;

        return self;

        function loadPart(options) {
            var url = options
                .urlTemplate
                .replace(/{part}/g, options.part)
                .replace(/{lang}/g, options.lang);

            return $q(function (resolve, reject) {
                $http
                    .get(url)
                    .then(function (response) {
                        var values = options.dataTransformation(response.data);
                        resolve(values);
                    })
                    .catch(function (error) {
                        reject(error);
                    });
            });
        }
    };

    function translateCache($window) {
        var self = this;

        self.local = {
            prefix: 'mutant-ng-translate-',
            isSupported: isSupportLocalStorage(),
            storage: $window.localStorage,
            get: getFromLocalStorage,
            put: putToLocalStorage,
            exists: existsInLocalStorage
        };

        self.cache = {
            getValues: getValuesFromCache,
            setValues: setValuesToCache,
            getLang: getLangFromCache,
            setLang: setLangToCache
        };

        return self.cache;

        // LOCAL STORAGE
        function isSupportLocalStorage() {
            try {
                $window.localStorage.setItem('test', 'test');
                $window.localStorage.removeItem('test');

                return true;
            } catch (exception) {
                return false;
            }
        }

        function getFromLocalStorage(key) {
            if (!self.local.storage[key]) return undefined;
            return JSON.parse(self.local.storage[key]);
        };

        function putToLocalStorage(key, obj) {
            self.local.storage[key] = JSON.stringify(obj);
        };

        function existsInLocalStorage(key) {
            return !!self.local.storage[key];
        };

        // CACHE
        function getValuesFromCache(lang) {
            if (!self.local.isSupported) return {};

            var lsKey = self.local.prefix + lang;

            if (!self.local.exists(lsKey)) {
                self.local.put(lsKey, {});
            }

            return self.local.get(lsKey);
        }

        function setValuesToCache(lang, values) {
            if (!self.local.isSupported) return;

            var lsKey = self.local.prefix + lang;
            var cacheValues = self.cache.getValues(lang);

            angular.extend(cacheValues, values);

            self.local.put(lsKey, cacheValues);
        }

        function getLangFromCache() {
            var lsKey = self.local.prefix + 'lang';

            return self.local.get(lsKey);
        }

        function setLangToCache(lang) {
            var lsKey = self.local.prefix + 'lang';

            self.local.put(lsKey, lang);
        }
    };
    };
})();
<|endoftext|>


<commit_before>'use strict';

var should = require('chai').should();
var ItemId = require('../itemid');
var Long   = require('mongodb-core').BSON.Long;

describe('#constructor', function () {
    it('Verifies that an ItemId can be constructed from a string ID', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.getTimestamp().should.equal(1441832782709);
        id.getCounterValue().should.equal(3534);
        id.getMachineId().should.equal(61);
    });
});

describe('#compare', function () {
    it('Verifies that an ItemId is lexicographically equal to itself', function () {
        var id = new ItemId();
        id.compare(id).should.equal(0);
    });

    it('Verifies that an ItemId is not lexicographically equal to another', function () {
        var id1 = new ItemId();
        var id2 = new ItemId();
        id1.compare(id2).should.not.equal(0);
    });
});

describe('#createFromDate', function () {
    it('Verifies that an ItemId can be created from a Date object', function () {
        var dates = [new Date(), new Date(1441922517727), new Date(0), new Date(0xfffffffffff)];
        for (var ith in dates) {
            var id = ItemId.createFromDate(dates[ith]);
            id.getTimestamp().should.equal(dates[ith].getTime());
            id.getCounterValue().should.equal(0);
            id.getMachineId().should.equal(0);
       }
    });
});

describe('#createFromLong', function () {
    it('Verifies that an ItemId can be created from a MongoDB Long type', function () {
        var id1 = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id1.high_;
        l.low_ = id1.low_;
        var id2 = ItemId.createFromLong(l);
        id2.equal(id1).should.equal(true);
    });
});

describe('#createFromTime', function () {
    it('Verifies that an ItemId can be created from a timestamp', function () {
        var timestamps = [Date.now(), 1441922517727, 1441905752206, 1441905597489, 1441922437429, 0xfffffffffff];
        for (var ith in timestamps) {
            var id = ItemId.createFromTime(timestamps[ith]);
            id.getTimestamp().should.equal(timestamps[ith]);
            id.getCounterValue().should.equal(0);
            id.getMachineId().should.equal(0);
       }
    });
});

describe('#equal', function () {
    it('Verifies that an ItemId is equal to itself', function () {
        var id = new ItemId();
        id.equal(id).should.equal(true);
    });

    it('Verifies that an ItemId is not equal to another', function () {
        var id1 = new ItemId();
        var id2 = new ItemId();
        id1.equal(id2).should.equal(false);
    });
});

describe('#getCounterValue', function () {
    it('Verifies that an ItemId’s counter value can be extracted', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.getCounterValue().should.equal(3534);
    });
});

describe('#getDate', function () {
    it('Verifies that an ItemId’s date can be extracted', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.getDate().getTime().should.equal(1441832782709);
    });
});

describe('#getMachineId', function () {
    it('Verifies that an ItemId’s machine ID can be extracted', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.getMachineId().should.equal(0x3d);
    });
});

describe('#getTimestamp', function () {
    it('Verifies that an ItemId’s timestamp can be extracted', function () {
        var timestamp = Date.now();
        ItemId.createFromTime(timestamp).getTimestamp().should.equal(timestamp);
        ItemId.createFromTime(0).getTimestamp().should.equal(0);
        ItemId.createFromTime(0xfffffffffff).getTimestamp().should.equal(0xfffffffffff);
    });
});

describe('#newId', function () {
    it('Verifies that a correct new ItemId can be created', function () {
        var strId = ItemId.newId();
        ItemId.test(strId).should.equal(true);
        var id = new ItemId(strId);
        id.valueOf().should.equal(strId);
    });
});

describe('#setMachineId', function () {
    it('Verifies that ItemId machine ID can be set', function () {
        var originalMachineId = ItemId.setMachineId(0);
        new ItemId().getMachineId().should.equal(0);
        ItemId.setMachineId(42).should.equal(0);
        new ItemId().getMachineId().should.equal(42);
        ItemId.setMachineId(0xff).should.equal(42);
        new ItemId().getMachineId().should.equal(0xff);
        ItemId.setMachineId(originalMachineId).should.equal(0xff);
        new ItemId().getMachineId().should.equal(originalMachineId);
    });
});

describe('#strFromLong', function () {
    it('Verifies that a MongoDB Long type can be converted into a stringified ItemId', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        ItemId.strFromLong(l).should.equal(id.valueOf());
    });
});

describe('#test', function () {
    it('Verifies that a stringified ItemId can be verified', function () {
        ItemId.test('ffffffffffffffff').should.equal(true);
        ItemId.test('0000000000000000').should.equal(true);
        ItemId.test('14fb3ee4b75dce3d').should.equal(true);
        ItemId.test('4fb3ee4b75dce3d').should.equal(false); // Too few characters.
        ItemId.test('g4fb3ee4b75dce3').should.equal(false); // Not hexadecimal.
        ItemId.test('-4fb3ee4b75dce3').should.equal(false); // Not hexadecimal.
    });
});

describe('#toJSON', function () {
    it('Verifies that an ItemId can be converted to a hexadecimal string', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toJSON().should.equal('14fb3ee4b75dce3d');
    });
});

describe('#toMySQL', function () {
    it('Verifies that an ItemId can be converted to a MySQL casting string', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toMySQL().should.equal("CAST(X\'14fb3ee4b75dce3d\' AS UNSIGNED)");
    });
});

describe('#toPostgreSQL', function () {
    it('Verifies that an ItemId can be converted to a PostgreSQL casting string', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toPostgreSQL().should.equal("CAST(X\'14fb3ee4b75dce3d\' AS bigint)");
    });
});

describe('#toString', function () {
    it('Verifies that an ItemId will be converted to a hexadecimal string if no arguments are given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toString().should.equal('14fb3ee4b75dce3d');
    });

    it('Verifies that an ItemId will be converted to a binary string if a base of 2 is given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toString(2).should.equal('1010011111011001111101110010010110111010111011100111000111101');
    });

    it('Verifies that an ItemId will be converted to a 32 base string if an argument of 32 is given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toString(32).should.equal('19upusirlrjht');
    });
});

describe('#valueOf', function () {
    it('Verifies that an ItemId can be converted to a hexadecimal string', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.valueOf().should.equal('14fb3ee4b75dce3d');
    });
});

describe('Long.newItemId', function () {
    it('Verifies that MongoDB’s Long type’s `newItemId()` routine has been overridden', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.newItemId().equal(id).should.equal(true);
    });
});

describe('Long.strItemId', function () {
    it('Verifies that MongoDB’s Long type’s `strItemId()` routine has been overridden', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.strItemId().should.equal('14fb3ee4b75dce3d');
    });
});

describe('Long.toJSON', function () {
    it('Verifies that MongoDB’s Long type’s `toJSON()` routine has been overridden', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.toJSON().should.equal('14fb3ee4b75dce3d');
    });
});

describe('Long.toString -- Verifies that MongoDB’s Long type’s `toString()` routine has been overridden', function () {
    it('Verifies that MongoDB’s Long type will be converted to a hexadecimal string if no arguments are given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.toString().should.equal('14fb3ee4b75dce3d');
    });

    it('Verifies that MongoDB’s Long type will be converted to a binary string if a base of 2 is given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.toString(2).should.equal('1010011111011001111101110010010110111010111011100111000111101');
    });

    it('Verifies that MongoDB’s Long type will be converted to a 32 base string if an argument of 32 is given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.toString(32).should.equal('19upusirlrjht');
    });
});
<commit_msg>Updated the test's requirements to match the latest ItemId version.<commit_after>'use strict';

var should = require('chai').should();
var ItemId = require('../itemid');
var Long   = require('bson').Long;

describe('#constructor', function () {
    it('Verifies that an ItemId can be constructed from a string ID', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.getTimestamp().should.equal(1441832782709);
        id.getCounterValue().should.equal(3534);
        id.getMachineId().should.equal(61);
    });
});

describe('#compare', function () {
    it('Verifies that an ItemId is lexicographically equal to itself', function () {
        var id = new ItemId();
        id.compare(id).should.equal(0);
    });

    it('Verifies that an ItemId is not lexicographically equal to another', function () {
        var id1 = new ItemId();
        var id2 = new ItemId();
        id1.compare(id2).should.not.equal(0);
    });
});

describe('#createFromDate', function () {
    it('Verifies that an ItemId can be created from a Date object', function () {
        var dates = [new Date(), new Date(1441922517727), new Date(0), new Date(0xfffffffffff)];
        for (var ith in dates) {
            var id = ItemId.createFromDate(dates[ith]);
            id.getTimestamp().should.equal(dates[ith].getTime());
            id.getCounterValue().should.equal(0);
            id.getMachineId().should.equal(0);
       }
    });
});

describe('#createFromLong', function () {
    it('Verifies that an ItemId can be created from a MongoDB Long type', function () {
        var id1 = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id1.high_;
        l.low_ = id1.low_;
        var id2 = ItemId.createFromLong(l);
        id2.equal(id1).should.equal(true);
    });
});

describe('#createFromTime', function () {
    it('Verifies that an ItemId can be created from a timestamp', function () {
        var timestamps = [Date.now(), 1441922517727, 1441905752206, 1441905597489, 1441922437429, 0xfffffffffff];
        for (var ith in timestamps) {
            var id = ItemId.createFromTime(timestamps[ith]);
            id.getTimestamp().should.equal(timestamps[ith]);
            id.getCounterValue().should.equal(0);
            id.getMachineId().should.equal(0);
       }
    });
});

describe('#equal', function () {
    it('Verifies that an ItemId is equal to itself', function () {
        var id = new ItemId();
        id.equal(id).should.equal(true);
    });

    it('Verifies that an ItemId is not equal to another', function () {
        var id1 = new ItemId();
        var id2 = new ItemId();
        id1.equal(id2).should.equal(false);
    });
});

describe('#getCounterValue', function () {
    it('Verifies that an ItemId’s counter value can be extracted', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.getCounterValue().should.equal(3534);
    });
});

describe('#getDate', function () {
    it('Verifies that an ItemId’s date can be extracted', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.getDate().getTime().should.equal(1441832782709);
    });
});

describe('#getMachineId', function () {
    it('Verifies that an ItemId’s machine ID can be extracted', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.getMachineId().should.equal(0x3d);
    });
});

describe('#getTimestamp', function () {
    it('Verifies that an ItemId’s timestamp can be extracted', function () {
        var timestamp = Date.now();
        ItemId.createFromTime(timestamp).getTimestamp().should.equal(timestamp);
        ItemId.createFromTime(0).getTimestamp().should.equal(0);
        ItemId.createFromTime(0xfffffffffff).getTimestamp().should.equal(0xfffffffffff);
    });
});

describe('#newId', function () {
    it('Verifies that a correct new ItemId can be created', function () {
        var strId = ItemId.newId();
        ItemId.test(strId).should.equal(true);
        var id = new ItemId(strId);
        id.valueOf().should.equal(strId);
    });
});

describe('#setMachineId', function () {
    it('Verifies that ItemId machine ID can be set', function () {
        var originalMachineId = ItemId.setMachineId(0);
        new ItemId().getMachineId().should.equal(0);
        ItemId.setMachineId(42).should.equal(0);
        new ItemId().getMachineId().should.equal(42);
        ItemId.setMachineId(0xff).should.equal(42);
        new ItemId().getMachineId().should.equal(0xff);
        ItemId.setMachineId(originalMachineId).should.equal(0xff);
        new ItemId().getMachineId().should.equal(originalMachineId);
    });
});

describe('#strFromLong', function () {
    it('Verifies that a MongoDB Long type can be converted into a stringified ItemId', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        ItemId.strFromLong(l).should.equal(id.valueOf());
    });
});

describe('#test', function () {
    it('Verifies that a stringified ItemId can be verified', function () {
        ItemId.test('ffffffffffffffff').should.equal(true);
        ItemId.test('0000000000000000').should.equal(true);
        ItemId.test('14fb3ee4b75dce3d').should.equal(true);
        ItemId.test('4fb3ee4b75dce3d').should.equal(false); // Too few characters.
        ItemId.test('g4fb3ee4b75dce3').should.equal(false); // Not hexadecimal.
        ItemId.test('-4fb3ee4b75dce3').should.equal(false); // Not hexadecimal.
    });
});

describe('#toJSON', function () {
    it('Verifies that an ItemId can be converted to a hexadecimal string', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toJSON().should.equal('14fb3ee4b75dce3d');
    });
});

describe('#toMySQL', function () {
    it('Verifies that an ItemId can be converted to a MySQL casting string', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toMySQL().should.equal("CAST(X\'14fb3ee4b75dce3d\' AS UNSIGNED)");
    });
});

describe('#toPostgreSQL', function () {
    it('Verifies that an ItemId can be converted to a PostgreSQL casting string', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toPostgreSQL().should.equal("CAST(X\'14fb3ee4b75dce3d\' AS bigint)");
    });
});

describe('#toString', function () {
    it('Verifies that an ItemId will be converted to a hexadecimal string if no arguments are given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toString().should.equal('14fb3ee4b75dce3d');
    });

    it('Verifies that an ItemId will be converted to a binary string if a base of 2 is given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toString(2).should.equal('1010011111011001111101110010010110111010111011100111000111101');
    });

    it('Verifies that an ItemId will be converted to a 32 base string if an argument of 32 is given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.toString(32).should.equal('19upusirlrjht');
    });
});

describe('#valueOf', function () {
    it('Verifies that an ItemId can be converted to a hexadecimal string', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        id.valueOf().should.equal('14fb3ee4b75dce3d');
    });
});

describe('Long.newItemId', function () {
    it('Verifies that MongoDB’s Long type’s `newItemId()` routine has been overridden', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.newItemId().equal(id).should.equal(true);
    });
});

describe('Long.strItemId', function () {
    it('Verifies that MongoDB’s Long type’s `strItemId()` routine has been overridden', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.strItemId().should.equal('14fb3ee4b75dce3d');
    });
});

describe('Long.toJSON', function () {
    it('Verifies that MongoDB’s Long type’s `toJSON()` routine has been overridden', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.toJSON().should.equal('14fb3ee4b75dce3d');
    });
});

describe('Long.toString -- Verifies that MongoDB’s Long type’s `toString()` routine has been overridden', function () {
    it('Verifies that MongoDB’s Long type will be converted to a hexadecimal string if no arguments are given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.toString().should.equal('14fb3ee4b75dce3d');
    });

    it('Verifies that MongoDB’s Long type will be converted to a binary string if a base of 2 is given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.toString(2).should.equal('1010011111011001111101110010010110111010111011100111000111101');
    });

    it('Verifies that MongoDB’s Long type will be converted to a 32 base string if an argument of 32 is given', function () {
        var id = new ItemId('14fb3ee4b75dce3d');
        var l = new Long();
        l.high_ = id.high_;
        l.low_ = id.low_;
        l.toString(32).should.equal('19upusirlrjht');
    });
});
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'

import RedactedInput from './RedactedInput'

const {bool, func, shape, string} = PropTypes

const AlertaConfig = React.createClass({
  propTypes: {
    config: shape({
      options: shape({
        environment: string,
        origin: string,
        token: bool,
        url: string,
      }).isRequired,
    }).isRequired,
    onSave: func.isRequired,
  },

  handleSaveAlert(e) {
    e.preventDefault()

    const properties = {
      environment: this.environment.value,
      origin: this.origin.value,
      token: this.token.value,
      url: this.url.value,
    }

    this.props.onSave(properties)
  },

  render() {
    const {environment, origin, token, url} = this.props.config.options

    return (
      <form onSubmit={this.handleSaveAlert}>

          Environment
          <input
            className="form-control"
            id="environment"
            type="text"
            ref={r => (this.environment = r)}
            defaultValue={environment || ''}
          />

          Origin
          <input
            className="form-control"
            id="origin"
            type="text"
            ref={r => (this.origin = r)}
            defaultValue={origin || ''}
          />

          Token
          <RedactedInput
            defaultValue={token}
            id="token"
            refFunc={r => (this.token = r)}
          />

          User
          <input
            className="form-control"
            id="url"
            type="text"
            ref={r => (this.url = r)}
            defaultValue={url || ''}
          />

          <button className="btn btn-primary" type="submit">
            Update Alerta Config
          </button>

      </form>
    )
  },
})

export default AlertaConfig
<commit_msg>Refactor AlertaConfig.<commit_after>import React, {PropTypes, Component} from 'react'

import RedactedInput from './RedactedInput'

class AlertaConfig extends Component {
  constructor(props) {
    super(props)
  }

  handleSaveAlert = e => {
    e.preventDefault()

    const properties = {
      environment: this.environment.value,
      origin: this.origin.value,
      token: this.token.value,
      url: this.url.value,
    }

    this.props.onSave(properties)
  }

  handleTokenRef = r => (this.token = r)

  render() {
    const {environment, origin, token, url} = this.props.config.options

    return (
      <form onSubmit={this.handleSaveAlert}>

          Environment
          <input
            className="form-control"
            id="environment"
            type="text"
            ref={r => (this.environment = r)}
            defaultValue={environment || ''}
          />

          Origin
          <input
            className="form-control"
            id="origin"
            type="text"
            ref={r => (this.origin = r)}
            defaultValue={origin || ''}
          />

          Token
          <RedactedInput
            defaultValue={token}
            id="token"
            refFunc={this.handleTokenRef}
          />

          User
          <input
            className="form-control"
            id="url"
            type="text"
            ref={r => (this.url = r)}
            defaultValue={url || ''}
          />

          <button className="btn btn-primary" type="submit">
            Update Alerta Config
          </button>

      </form>
    )
  }
}

const {bool, func, shape, string} = PropTypes

AlertaConfig.propTypes = {
  config: shape({
    options: shape({
      environment: string,
      origin: string,
      token: bool,
      url: string,
    }).isRequired,
  }).isRequired,
  onSave: func.isRequired,
}

export default AlertaConfig
<|endoftext|>


<commit_before>import _ from 'lodash';
import estraverse from 'estraverse';

// JSX AST types, as documented in:
// https://github.com/facebook/jsx/blob/master/AST.md
const jsxExtensionKeys = {
  JSXIdentifier: [],
  JSXMemberExpression: ['object', 'property'],
  JSXNamespacedName: ['namespace', 'name'],
  JSXEmptyExpression: [],
  JSXExpressionContainer: ['expression'],
  JSXOpeningElement: ['name', 'attributes'],
  JSXClosingElement: ['name'],
  JSXAttribute: ['name', 'value'],
  JSXSpreadAttribute: ['argument'],
  JSXElement: ['openingElement', 'closingElement', 'children'],
};

const experimentalExtensionKeys = {
  ExperimentalRestProperty: ['argument'],
  ExperimentalSpreadProperty: ['argument'],
};

const extensions = {
  keys: _.assign({}, jsxExtensionKeys, experimentalExtensionKeys),
};

/**
 * Proxy for ESTraverse.
 * Providing a single place to easily extend its functionality.
 *
 * Exposes the traverse() and replace() methods just like ESTraverse,
 * plus some custom helpers.
 */
export default {
  /**
   * Traverses AST like ESTraverse.traverse()
   * @param  {Object} tree
   * @param  {Object} cfg Object with optional enter() and leave() methods.
   * @return {Object} The transformed tree
   */
  traverse(tree, cfg) {
    return estraverse.traverse(tree, _.assign(cfg, extensions));
  },

  /**
   * Traverses AST like ESTraverse.replace()
   * @param  {Object} tree
   * @param  {Object} cfg Object with optional enter() and leave() methods.
   * @return {Object} The transformed tree
   */
  replace(tree, cfg) {
    return estraverse.replace(tree, _.assign(cfg, extensions));
  },

  /**
   * Constants to return from enter()/leave() to control traversal:
   *
   * - Skip - skips walking child nodes
   * - Break - ends it all
   * - Remove - removes the current node (only with replace())
   */
  VisitorOption: estraverse.VisitorOption,

  /**
   * Searches in AST tree for node which satisfies the predicate.
   * @param  {Object} tree
   * @param  {Function|String} query Search function called with `node` and `parent`
   *   Alternatively it can be string: the node type to search for.
   * @param  {String[]} opts.skipTypes List of node types to skip (not traversing into these nodes)
   * @return {Object} The found node or undefined when not found
   */
  find(tree, query, {skipTypes = []} = {}) {
    const predicate = this.createFindPredicate(query);
    let found;

    this.traverse(tree, {
      enter(node, parent) {
        if (skipTypes.includes(node.type)) {
          return estraverse.VisitorOption.Skip;
        }
        if (predicate(node, parent)) {
          found = node;
          return estraverse.VisitorOption.Break;
        }
      }
    });

    return found;
  },

  createFindPredicate(query) {
    if (_.isString(query)) {
      return (node) => node.type === query;
    }
    else {
      return query;
    }
  }
};
<commit_msg>Use LoDash _.includes() instead of Array.includes()<commit_after>import _ from 'lodash';
import estraverse from 'estraverse';

// JSX AST types, as documented in:
// https://github.com/facebook/jsx/blob/master/AST.md
const jsxExtensionKeys = {
  JSXIdentifier: [],
  JSXMemberExpression: ['object', 'property'],
  JSXNamespacedName: ['namespace', 'name'],
  JSXEmptyExpression: [],
  JSXExpressionContainer: ['expression'],
  JSXOpeningElement: ['name', 'attributes'],
  JSXClosingElement: ['name'],
  JSXAttribute: ['name', 'value'],
  JSXSpreadAttribute: ['argument'],
  JSXElement: ['openingElement', 'closingElement', 'children'],
};

const experimentalExtensionKeys = {
  ExperimentalRestProperty: ['argument'],
  ExperimentalSpreadProperty: ['argument'],
};

const extensions = {
  keys: _.assign({}, jsxExtensionKeys, experimentalExtensionKeys),
};

/**
 * Proxy for ESTraverse.
 * Providing a single place to easily extend its functionality.
 *
 * Exposes the traverse() and replace() methods just like ESTraverse,
 * plus some custom helpers.
 */
export default {
  /**
   * Traverses AST like ESTraverse.traverse()
   * @param  {Object} tree
   * @param  {Object} cfg Object with optional enter() and leave() methods.
   * @return {Object} The transformed tree
   */
  traverse(tree, cfg) {
    return estraverse.traverse(tree, _.assign(cfg, extensions));
  },

  /**
   * Traverses AST like ESTraverse.replace()
   * @param  {Object} tree
   * @param  {Object} cfg Object with optional enter() and leave() methods.
   * @return {Object} The transformed tree
   */
  replace(tree, cfg) {
    return estraverse.replace(tree, _.assign(cfg, extensions));
  },

  /**
   * Constants to return from enter()/leave() to control traversal:
   *
   * - Skip - skips walking child nodes
   * - Break - ends it all
   * - Remove - removes the current node (only with replace())
   */
  VisitorOption: estraverse.VisitorOption,

  /**
   * Searches in AST tree for node which satisfies the predicate.
   * @param  {Object} tree
   * @param  {Function|String} query Search function called with `node` and `parent`
   *   Alternatively it can be string: the node type to search for.
   * @param  {String[]} opts.skipTypes List of node types to skip (not traversing into these nodes)
   * @return {Object} The found node or undefined when not found
   */
  find(tree, query, {skipTypes = []} = {}) {
    const predicate = this.createFindPredicate(query);
    let found;

    this.traverse(tree, {
      enter(node, parent) {
        if (_.includes(skipTypes, node.type)) {
          return estraverse.VisitorOption.Skip;
        }
        if (predicate(node, parent)) {
          found = node;
          return estraverse.VisitorOption.Break;
        }
      }
    });

    return found;
  },

  createFindPredicate(query) {
    if (_.isString(query)) {
      return (node) => node.type === query;
    }
    else {
      return query;
    }
  }
};
<|endoftext|>


<commit_before>define(function (require, exports, module) {
  var ComponentPlugin = require("ide-component-plugin");
  var BootstrapComponent = BootstrapComponent || ComponentPlugin.extend({
    init: function (options) {
      this._super(options);
      // bind ti dblclick event in order to set content editables
      var ide = this.settings.ide;
      return this;
    },
    _getDefaultColSpan: function(descriptor) {
      var colComponent = this.settings.packageInfo.components[descriptor.type];
      if (!colComponent) {
        throw "Could not find column component for bootstrap package.";
      }
      if (!colComponent.properties) {
        // we are using the component before it has been dropped/fully initialized, so we need to load its info
        colComponent.loadInfo();
      }
      return colComponent.properties["columnSpan"].defaultValue;
    },
    getMarkup: function (descriptor) {
      var code = "", i;
      //return "

";
      if (descriptor.type === "row") {
        for (i = 0; i < 3; i++) {
          code += this.getMarkup({type: "column", colSpan: 4});
        }
        return "
" + code + "
";
      } else if (descriptor.type === "column") {
        var colSpan = descriptor.colSpan;
        if (typeof (colSpan) === "undefined") {
          // get the default one
          colSpan = this._getDefaultColSpan(descriptor);
        }
        return "

Span " + colSpan + "

Contents

";
      }
    },
    getCodeEditorMarkupSnippet: function (descriptor) {
      if (descriptor.type === "column") {
        var colSpan = descriptor.colSpan, indentStr = "\t\t";
        if (descriptor.extraIndent) {
          for (var i = 0; i < descriptor.extraIndent; i++) {
            indentStr += "\t";
          }
        }
        if (typeof (colSpan) === "undefined") {
          colSpan = this._getDefaultColSpan(descriptor);
        }
        return {
          codeString: indentStr + "
\n" +
            indentStr + "\t
Span " + colSpan + "
\n" +
            indentStr + "\t
Contents
\n" +
            indentStr + "
\n",
          lineCount: 4
        };
      } else {
        return {
          codeString: descriptor.ide._tabStr(descriptor.extraIndent + 1) + "
\n" +
            "\t\t\t
\n" +
            "\t\t\t\t
Span 4
\n" +
            "\t\t\t\t
Contents
\n" +
            "\t\t\t
\n" +
            "\t\t\t
\n" +
            "\t\t\t\t
Span 4
\n" +
            "\t\t\t\t
Contents
\n" +
            "\t\t\t
\n" +
            "\t\t\t
\n" +
            "\t\t\t\t
Span 4
\n" +
            "\t\t\t\t
Contents
\n" +
            "\t\t\t
\n" +
            "\t\t
\n",
          lineCount: 14,
          // contains offsets from parent only only
          extraMarkers: [
            {
              rowOffset: 1,
              colOffset: 0,
              rowCount: 4,
              colCount: 0
            },
            {
              rowOffset: 5,
              colOffset: 0,
              rowCount: 4,
              colCount: 0
            },
            {
              rowOffset: 9,
              colOffset: 0,
              rowCount: 4,
              colCount: 0
            }
          ]
        };
      }
    },
    isContainer: function (descriptor) {
      if (typeof (descriptor) === "undefined" || descriptor === null) {
        return false;
      }
      //returns true for both  columns and rows
      if (descriptor.type === "row" || descriptor.type === "column") {
        return true;
      }
      // the descriptor can also be a DOM element
      if (descriptor.nodeName && $(descriptor).attr("data-container") === "true") {
        return true;
      }
      return false;
    },
    isDroppableChild: function (descriptor) {
      if (typeof (descriptor) === "undefined" || descriptor === null) {
        return false;
      }
      if (descriptor.nodeName && $(descriptor).attr("data-droppablechild") === "true") {
        return true;
      } else {
        if (descriptor.type === "row") {
          return false;
        } else if (descriptor.type === "column") {
          return true;
        }
      }
      return false;
    },
    hasDroppableChildren: function (descriptor) {
      if (typeof (descriptor) === "undefined" || descriptor === null) {
        return false;
      }
      if (descriptor.nodeName && $(descriptor).attr("data-hasdroppables") === "true") {
        return true;
      }
    },
    getDroppableChildren: function (descriptor) {
      if (typeof (descriptor) === "undefined" || descriptor === null) {
        return $();
      } else if (descriptor.nodeName) {
        return $(descriptor).find("div[data-droppablechild]");
      }
      return $();
    },
    discoverComponents: function (descriptor) {
        console.log("discovering bootstrap");
    }
  });
  return BootstrapComponent;
});<commit_msg> working on code view => designer sync<commit_after>define(function (require, exports, module) {
  var ComponentPlugin = require("ide-component-plugin");
  var BootstrapComponent = BootstrapComponent || ComponentPlugin.extend({
    init: function (options) {
      this._super(options);
      // bind ti dblclick event in order to set content editables
      var ide = this.settings.ide;
      return this;
    },
    _getDefaultColSpan: function(descriptor) {
      var colComponent = this.settings.packageInfo.components[descriptor.type];
      if (!colComponent) {
        throw "Could not find column component for bootstrap package.";
      }
      if (!colComponent.properties) {
        // we are using the component before it has been dropped/fully initialized, so we need to load its info
        colComponent.loadInfo();
      }
      return colComponent.properties["columnSpan"].defaultValue;
    },
    getMarkup: function (descriptor) {
      var code = "", i;
      //return "

";
      if (descriptor.type === "row") {
        for (i = 0; i < 3; i++) {
          code += this.getMarkup({type: "column", colSpan: 4});
        }
        return "
" + code + "
";
      } else if (descriptor.type === "column") {
        var colSpan = descriptor.colSpan;
        if (typeof (colSpan) === "undefined") {
          // get the default one
          colSpan = this._getDefaultColSpan(descriptor);
        }
        return "

Span " + colSpan + "

Contents

";
      }
    },
    getCodeEditorMarkupSnippet: function (descriptor) {
      if (descriptor.type === "column") {
        var colSpan = descriptor.colSpan, indentStr = "\t\t";
        if (descriptor.extraIndent) {
          for (var i = 0; i < descriptor.extraIndent; i++) {
            indentStr += "\t";
          }
        }
        if (typeof (colSpan) === "undefined") {
          colSpan = this._getDefaultColSpan(descriptor);
        }
        return {
          codeString: indentStr + "
\n" +
            indentStr + "\t
Span " + colSpan + "
\n" +
            indentStr + "\t
Contents
\n" +
            indentStr + "
\n",
          lineCount: 4
        };
      } else {
        return {
          codeString: descriptor.ide._tabStr(descriptor.extraIndent + 1) + "
\n" +
            "\t\t\t
\n" +
            "\t\t\t\t
Span 4
\n" +
            "\t\t\t\t
Contents
\n" +
            "\t\t\t
\n" +
            "\t\t\t
\n" +
            "\t\t\t\t
Span 4
\n" +
            "\t\t\t\t
Contents
\n" +
            "\t\t\t
\n" +
            "\t\t\t
\n" +
            "\t\t\t\t
Span 4
\n" +
            "\t\t\t\t
Contents
\n" +
            "\t\t\t
\n" +
            "\t\t
\n",
          lineCount: 14,
          // contains offsets from parent only only
          extraMarkers: [
            {
              rowOffset: 1,
              colOffset: 0,
              rowCount: 4,
              colCount: 0
            },
            {
              rowOffset: 5,
              colOffset: 0,
              rowCount: 4,
              colCount: 0
            },
            {
              rowOffset: 9,
              colOffset: 0,
              rowCount: 4,
              colCount: 0
            }
          ]
        };
      }
    },
    isContainer: function (descriptor) {
      if (typeof (descriptor) === "undefined" || descriptor === null) {
        return false;
      }
      //returns true for both  columns and rows
      if (descriptor.type === "row" || descriptor.type === "column") {
        return true;
      }
      // the descriptor can also be a DOM element
      if (descriptor.nodeName && $(descriptor).attr("data-container") === "true") {
        return true;
      }
      return false;
    },
    isDroppableChild: function (descriptor) {
      if (typeof (descriptor) === "undefined" || descriptor === null) {
        return false;
      }
      if (descriptor.nodeName && $(descriptor).attr("data-droppablechild") === "true") {
        return true;
      } else {
        if (descriptor.type === "row") {
          return false;
        } else if (descriptor.type === "column") {
          return true;
        }
      }
      return false;
    },
    hasDroppableChildren: function (descriptor) {
      if (typeof (descriptor) === "undefined" || descriptor === null) {
        return false;
      }
      if (descriptor.nodeName && $(descriptor).attr("data-hasdroppables") === "true") {
        return true;
      }
    },
    getDroppableChildren: function (descriptor) {
      if (typeof (descriptor) === "undefined" || descriptor === null) {
        return $();
      } else if (descriptor.nodeName) {
        return $(descriptor).find("div[data-droppablechild]");
      }
      return $();
    },
    discoverComponents: function (descriptor) {
        console.log("discovering bootstrap");
        // we are looking for DIV elements which have a "row" class applied, and have one or more DIVs marked with a "column" class
        // if we see such a structure, we assume that it's a bootstrap row.
        // since bootstrap is HTML-only, we aren't going to parse any js

    }
  });
  return BootstrapComponent;
});<|endoftext|>


<commit_before>'use strict';

const createSideBar = function() {
	const sideBar = document.getElementById('sidebar');

	const header = document.createElement('h1');
	header.textContent = 'Available visualisations';
	sideBar.appendChild(header);

	const visList = document.createElement('ul');
	sideBar.appendChild(visList);

	visualisations.forEach((item, key) => {
		const li = document.createElement('li');

		const a = document.createElement('a');
		a.href = '?' + key;
		a.textContent = item.name;
		li.appendChild(a);

		visList.appendChild(li);
	});

	const sideBarToggle = document.createElement('span');
	sideBarToggle.setAttribute('role', 'button');
	sideBarToggle.setAttribute('tabindex', '0');
	sideBarToggle.classList.add('sidebar-toggle')
	sideBarToggle.addEventListener('click', () => sideBar.classList.toggle('collapsed'));
	sideBarToggle.textContent = 'Menu';
	sideBar.appendChild(sideBarToggle);

	const self = {
		collapse: () => sideBar.classList.add('collapsed'),
		expand: () => sideBar.classList.remove('collapsed'),
	}

	return self;
}

const createInfoBar = function(fileName) {
	const infoBar = document.getElementById('infobar');

	const infoHolder = document.createElement('div');
	infoHolder.classList.add('info');
	infoBar.appendChild(infoHolder);

	const featureHolder = document.createElement('div');
	infoBar.appendChild(featureHolder);

	const header = document.createElement('h1');
	header.textContent = 'Visible features';
	featureHolder.classList.add('features');
	featureHolder.appendChild(header);

	const featList = document.createElement('ul');
	featureHolder.appendChild(featList);

	const self = {
		setInfo: (info) => {infoHolder.innerHTML = info;},
		clearInfo: () => {infoHolder.innerHTML = 'Hover a feature on the map or click on one in the list below to show information about the feature.';},
		setFeatures: (features, highlightFeature) => {
			featList.textContent = '';
			features.forEach((feature) => {
				const li = document.createElement('li');
				const highlight = () => {
					highlightFeature(feature);
				};

				li.setAttribute('role', 'button');
				li.setAttribute('tabindex', '0');
				li.feature = feature;
				li.addEventListener('click', highlight);
				li.addEventListener('keypress', (e) => {
					if (e.key == 'Spacebar' || e.key == ' ' || e.key == 'Enter') {
						e.preventDefault();
						highlight();
					}
				});

				li.textContent = visualisations.get(fileName).listInfo(feature);
				featList.appendChild(li);
			});
		}
	};

	self.clearInfo();
	return self;
}

window.onload = function() {
	const fileName = window.location.search.toString().replace(/^\?/, '');
	const sideBar = createSideBar();

	if (!fileName) {
		document.body.classList.add('front');
		sideBar.expand();
	} else if (!visualisations.has(fileName)) {
		alert('Unknown visualisation.');
		window.location.search = '';
	} else {
		const infoBar = createInfoBar(fileName);

		document.title = 'Address visualisation – ' + visualisations.get(fileName).name;
		document.body.classList.remove('front');
		sideBar.collapse();

		proj4.defs('urn:ogc:def:crs:EPSG::5514','+proj=krovak +lat_0=49.5 +lon_0=24.83333333333333 +alpha=30.28813972222222 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel +towgs84=589,76,480,0,0,0,0 +units=m +no_defs');

		function styleFunction(feature) {
			let style;
			let fillColor = 'rgba(240, 0, 0, 0.3)';
			let strokeColor = 'rgba(240, 0, 0, 1)';

			let styleProperty = feature.get('style');
			if (styleProperty) {
				if (styleProperty.fill) {
					fillColor = styleProperty.fill;
				}
				if (styleProperty.stroke) {
					strokeColor = styleProperty.stroke;
				}
			}

			if (feature.getGeometry().getType() === 'Point') {
				style = new ol.style.Style({
					image: new ol.style.Circle({
						radius: 5,
						fill: new ol.style.Fill({
							color: fillColor,
						}),
						stroke: new ol.style.Stroke({
							color: strokeColor,
							width: 10
						})
					})
				});
			} else {
				style = new ol.style.Style({
					fill: new ol.style.Fill({
						color: fillColor,
					}),
					stroke: new ol.style.Stroke({
						color: strokeColor,
						width: 10
					})
				});
			}

			return style;
		}

		const geoJsonSource = new ol.source.Vector({
			url: '../vf_visualiser/visualisations/' + fileName + '.json',
			format: new ol.format.GeoJSON()
		});

		const map = new ol.Map({
			layers: [
				new ol.layer.Tile({
					source: new ol.source.OSM()
				}),
				new ol.layer.Image({
					source: new ol.source.ImageVector({
						source: geoJsonSource,
						style: styleFunction
					})
				})
			],
			target: 'view',
			view: new ol.View({
				center: ol.proj.fromLonLat([15.5, 49.75]),
				zoom: 8,
				minZoom: 8
			})
		});

		const featureOverlay = new ol.layer.Vector({
			source: new ol.source.Vector(),
			map: map,
			style: new ol.style.Style({
				stroke: new ol.style.Stroke({
					color: '#f0f000',
					width: 10
				}),
				fill: new ol.style.Fill({
					color: 'rgba(240,240,0,0.3)'
				})
			})
		});

		function getFeatureUnderCursor(pixel) {
			return map.forEachFeatureAtPixel(pixel, function(feature) {
				return feature;
			});
		}

		let highlight;
		function highlightFeature(feature) {
			if (feature) {
				infoBar.setInfo(visualisations.get(fileName).info(feature))
			} else {
				infoBar.clearInfo();
			}

			if (feature !== highlight) {
				if (highlight) {
					featureOverlay.getSource().removeFeature(highlight);
				}
				if (feature) {
					featureOverlay.getSource().addFeature(feature);
				}
				highlight = feature;
			}

		};

		map.on('pointermove', function(evt) {
			if (evt.dragging) {
				return;
			}
			const pixel = map.getEventPixel(evt.originalEvent);
			highlightFeature(getFeatureUnderCursor(pixel));
		});

		map.on('click', function(evt) {
			highlightFeature(getFeatureUnderCursor(evt.pixel));
		});

		function updateFeatureList() {
			const extent = map.getView().calculateExtent(map.getSize());
			infoBar.setFeatures(geoJsonSource.getFeaturesInExtent(extent), highlightFeature);
		}

		map.on('postrender', updateFeatureList);
	}
};
<commit_msg>fixed viewer<commit_after>'use strict';

const createSideBar = function() {
	const sideBar = document.getElementById('sidebar');

	const header = document.createElement('h1');
	header.textContent = 'Available visualisations';
	sideBar.appendChild(header);

	const visList = document.createElement('ul');
	sideBar.appendChild(visList);

	visualisations.forEach((item, key) => {
		const li = document.createElement('li');

		const a = document.createElement('a');
		a.href = '?' + key;
		a.textContent = item.name;
		li.appendChild(a);

		visList.appendChild(li);
	});

	const sideBarToggle = document.createElement('span');
	sideBarToggle.setAttribute('role', 'button');
	sideBarToggle.setAttribute('tabindex', '0');
	sideBarToggle.classList.add('sidebar-toggle')
	sideBarToggle.addEventListener('click', () => sideBar.classList.toggle('collapsed'));
	sideBarToggle.textContent = 'Menu';
	sideBar.appendChild(sideBarToggle);

	const self = {
		collapse: () => sideBar.classList.add('collapsed'),
		expand: () => sideBar.classList.remove('collapsed'),
	}

	return self;
}

const createInfoBar = function(fileName) {
	const infoBar = document.getElementById('infobar');

	const infoHolder = document.createElement('div');
	infoHolder.classList.add('info');
	infoBar.appendChild(infoHolder);

	const featureHolder = document.createElement('div');
	infoBar.appendChild(featureHolder);

	const header = document.createElement('h1');
	header.textContent = 'Visible features';
	featureHolder.classList.add('features');
	featureHolder.appendChild(header);

	const featList = document.createElement('ul');
	featureHolder.appendChild(featList);

	const self = {
		setInfo: (info) => {infoHolder.innerHTML = info;},
		clearInfo: () => {infoHolder.innerHTML = 'Hover a feature on the map or click on one in the list below to show information about the feature.';},
		setFeatures: (features, highlightFeature) => {
			featList.textContent = '';
			features.forEach((feature) => {
				const li = document.createElement('li');
				const highlight = () => {
					highlightFeature(feature);
				};

				li.setAttribute('role', 'button');
				li.setAttribute('tabindex', '0');
				li.feature = feature;
				li.addEventListener('click', highlight);
				li.addEventListener('keypress', (e) => {
					if (e.key == 'Spacebar' || e.key == ' ' || e.key == 'Enter') {
						e.preventDefault();
						highlight();
					}
				});

				li.textContent = visualisations.get(fileName).listInfo(feature);
				featList.appendChild(li);
			});
		}
	};

	self.clearInfo();
	return self;
}

window.onload = function() {
	const fileName = window.location.search.toString().replace(/^\?/, '');
	const sideBar = createSideBar();

	if (!fileName) {
		document.body.classList.add('front');
		sideBar.expand();
	} else if (!visualisations.has(fileName)) {
		alert('Unknown visualisation.');
		window.location.search = '';
	} else {
		const infoBar = createInfoBar(fileName);

		document.title = 'Address visualisation – ' + visualisations.get(fileName).name;
		document.body.classList.remove('front');
		sideBar.collapse();

		proj4.defs('urn:ogc:def:crs:EPSG::5514','+proj=krovak +lat_0=49.5 +lon_0=24.83333333333333 +alpha=30.28813972222222 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel +towgs84=589,76,480,0,0,0,0 +units=m +no_defs');

		function styleFunction(feature) {
			let style;
			let fillColor = 'rgba(240, 0, 0, 0.3)';
			let strokeColor = 'rgba(240, 0, 0, 1)';

			let styleProperty = feature.get('style');
			if (styleProperty) {
				if (styleProperty.fill) {
					fillColor = styleProperty.fill;
				}
				if (styleProperty.stroke) {
					strokeColor = styleProperty.stroke;
				}
			}

			if (feature.getGeometry().getType() === 'Point') {
				style = new ol.style.Style({
					image: new ol.style.Circle({
						radius: 5,
						fill: new ol.style.Fill({
							color: fillColor,
						}),
						stroke: new ol.style.Stroke({
							color: strokeColor,
							width: 10
						})
					})
				});
			} else {
				style = new ol.style.Style({
					fill: new ol.style.Fill({
						color: fillColor,
					}),
					stroke: new ol.style.Stroke({
						color: strokeColor,
						width: 10
					})
				});
			}

			return style;
		}

		const geoJsonSource = new ol.source.Vector({
			url: '../vf_resources/visualisations/' + fileName + '.json',
			format: new ol.format.GeoJSON()
		});

		const map = new ol.Map({
			layers: [
				new ol.layer.Tile({
					source: new ol.source.OSM()
				}),
				new ol.layer.Image({
					source: new ol.source.ImageVector({
						source: geoJsonSource,
						style: styleFunction
					})
				})
			],
			target: 'view',
			view: new ol.View({
				center: ol.proj.fromLonLat([15.5, 49.75]),
				zoom: 8,
				minZoom: 8
			})
		});

		const featureOverlay = new ol.layer.Vector({
			source: new ol.source.Vector(),
			map: map,
			style: new ol.style.Style({
				stroke: new ol.style.Stroke({
					color: '#f0f000',
					width: 10
				}),
				fill: new ol.style.Fill({
					color: 'rgba(240,240,0,0.3)'
				})
			})
		});

		function getFeatureUnderCursor(pixel) {
			return map.forEachFeatureAtPixel(pixel, function(feature) {
				return feature;
			});
		}

		let highlight;
		function highlightFeature(feature) {
			if (feature) {
				infoBar.setInfo(visualisations.get(fileName).info(feature))
			} else {
				infoBar.clearInfo();
			}

			if (feature !== highlight) {
				if (highlight) {
					featureOverlay.getSource().removeFeature(highlight);
				}
				if (feature) {
					featureOverlay.getSource().addFeature(feature);
				}
				highlight = feature;
			}

		};

		map.on('pointermove', function(evt) {
			if (evt.dragging) {
				return;
			}
			const pixel = map.getEventPixel(evt.originalEvent);
			highlightFeature(getFeatureUnderCursor(pixel));
		});

		map.on('click', function(evt) {
			highlightFeature(getFeatureUnderCursor(evt.pixel));
		});

		function updateFeatureList() {
			const extent = map.getView().calculateExtent(map.getSize());
			infoBar.setFeatures(geoJsonSource.getFeaturesInExtent(extent), highlightFeature);
		}

		map.on('postrender', updateFeatureList);
	}
};
<|endoftext|>


<commit_before>module.exports.player = (player, serv) => {
  player.commands.add({
    base: 'teleport',
    aliases: ['tp'],
    info: 'to teleport a player',
    usage: '/teleport [target player] <destination player or x> [x] [y]',
    parse(str) {
      return str.match(/^(((\w* )?\d* \d* \d*)|(\w* \w*))$/) ? str.split(' ') : false;
    },
    action(args) {
      if(args.length === 2 && args[0] !== args[1]) {
        let player_from;
        let player_to;

        if(!(player_from = serv.getPlayer(args[0])) || !(player_to = serv.getPlayer(args[1])))
          return false;

        player_from._client.write('position', {
          x: player_to.position.x/32,
          y: player_to.position.x/32,
          z: player_to.position.x/32,
          yaw: player_to.yaw,
          pitch: player_to.pitch,
          flags: 0x00
        });
      } else if(args.length === 3) {
        player._client.write('position', {
          x: args[0],
          y: args[1],
          z: args[2],
          yaw: player.yaw,
          pitch: player.pitch,
          flags: 0x00
        });
      } else if(args.length === 4) {
        let player_from;

        if(!(player_from = serv.getPlayer(args[0])))
          return false;

        player_from._client.write('position', {
          x: args[1],
          y: args[2],
          z: args[3],
          yaw: player_from.yaw,
          pitch: player_from.pitch,
          flags: 0x00
        });
      }
    }
  });
};
<commit_msg>Fix a very bad bug.<commit_after>module.exports.player = (player, serv) => {
  player.commands.add({
    base: 'teleport',
    aliases: ['tp'],
    info: 'to teleport a player',
    usage: '/teleport [target player] <destination player or x> [x] [y]',
    parse(str) {
      return str.match(/^(((\w* )?\d* \d* \d*)|(\w* \w*))$/) ? str.split(' ') : false;
    },
    action(args) {
      if(args.length === 2 && args[0] !== args[1]) {
        let player_from;
        let player_to;

        if(!(player_from = serv.getPlayer(args[0])) || !(player_to = serv.getPlayer(args[1])))
          return false;

        player_from.position = new Vec3(player_to.position.x/32, player_to.position.y/32, player_to.position.z/32);
        player_from.sendPosition();
      } else if(args.length === 3) {
        player.position = new Vec3(args[0], args[1], args[2]);
        player.sendPosition();
      } else if(args.length === 4) {
        let player_from;

        if(!(player_from = serv.getPlayer(args[0])))
          return false;

        player_from.position = new Vec3(args[1], args[2], args[3]);
        player_from.sendPosition();
      }
    }
  });
};
<|endoftext|>