<commit_before>(function(){

    "use strict";

    XMOT.namespace("XMOT.util");

    var u = XMOT.util;

    /** Returns the xml3d element in which the given element is contained.
     * If none is found, null is returned.
     *
     * @param {!Object} el
     * @return {Object}
     */
    u.getXml3dRoot = function(el)
    {
        if(!el) {
            throw new Error("XMOT.util.getXml3dRoot(): given element is not defined.");
        }
        if(!el.parentNode) {
            throw new Error("XMOT.util.getXml3dRoot(): given element has no parent node.");
        }

        if(el.tagName.toLowerCase() === "xml3d")
            return el;

        if(el.parentNode)
            return u.getXml3dRoot(el.parentNode);

        return null;
    };

    /** Internal helper method. Gets and/or sets a reference pointed to by attrName
     *  of the element el. For more information see XMOT.util.transform()
     *  or XMOT.util.shader().
     *
     *  @param {!Object} el
     *  @param {!string} attrName
     *  @param {Object} newRefNode
     *
     *  @return {Object}
     */
    function getOrSetRefNode(el, attrName, newRefNode)
    {
        var oldRefNode = null;

        var oldRef = el.getAttribute(attrName);
        if(oldRef && oldRef.length > 0)
            oldRefNode = XML3D.URIResolver.resolveLocal(oldRef);

        if(newRefNode)
        {
            var newRef = newRefNode.getAttribute("id");
            if(newRef && newRef.length > 0)
            {
                newRef = "#" + newRef;
                el.setAttribute(attrName, newRef);
            }
        }

        return oldRefNode;
    };

    /**
     * Retrieve or set the transform node of a given group node.
     *
     * @param {!Object} grp the desired group node
     * @param {Object} xfm (optional) the transform element to which grp's
     *  transform attribute should be set. The transform has to have an
     *  id attribute.
     *
     * @return {Object} if one argument is given, it returns the current transform
     *  element of el. If two arguments are given, it returns the transform element set
     *  before it was overridden by xfm.
     */
    u.transform = function(grp, xfm)
    {
        if(grp.tagName.toLowerCase() !== "group")
            throw "XMOT.util.transform(): given element is not a group.";

        return getOrSetRefNode(grp, "transform", xfm);
    };

    /** Retrieve or set the shader of the given group node.
     *
     * @param {!Object} grp the group of which to retrieve the shader.
     * @param {Object} sh (optional) the shader element to which el's shader
     *  attribute should be set. The shader has to have an id attribute.
     *
     * @return {Object} if one argument is given, it returns the current shader of el. If
     *  two arguments are given, it returns the shader set before it was overridden by sh.
     */
    u.shader = function(grp, sh)
    {
        if(grp.tagName.toLowerCase() !== "group")
            throw "XMOT.util.shader(): given element is not a group.";

        return getOrSetRefNode(grp, "shader", sh);
    };

    /**
     * Returns the first defs element of the given xml3d element. If none exists,
     * a corresponding element is created, appended to xml3d and returned.
     *
     * @param {!Object} xml3d the xml3d element of which to return the defs element
     *
     * @return {Object} the first defs element of the given xml3d element
     */
    u.getOrCreateDefs = function(xml3d)
    {
        var defs = XML3D.util.evaluateXPathExpr(
            xml3d, './/xml3d:defs[1]').singleNodeValue;

        if(!defs)
        {
            defs = XMOT.creation.element("defs");
            xml3d.appendChild(defs);
        }

        return defs;
    };

    /**
     * Returns the transform element corresponding to the given
     * group. If it doesn't exist, one will be created with the
     * id newId, appended to the defs section and targetGrp's
     * transform reference will be set to the newly created
     * element.
     *
     * @param {!Object} targetGrp the group to retrieve the transform from
     * @param {string} newId the id attribute of the transform to be created
     *
     * @return {Object} the transform corresponding to targetGrp
     */
    u.getOrCreateTransform = function(targetGrp, newId)
    {
        var t = XMOT.util.transform(targetGrp);

        if(t) // found it, just return
            return t;

        var xml3d = u.getXml3dRoot(targetGrp);
        var defs = u.getOrCreateDefs(xml3d);

        // create transform
        t = XMOT.creation.element("transform", {id: newId});
        defs.appendChild(t);
        targetGrp.setAttribute("transform", "#" + newId);

        return t;
    };

    /** Return the first child element of tarNode, whose "name" attribute
     * is equal to the given one. Useful for retrieving shader attributes.
     *
     * @param {!Object} tarNode
     * @param {string} name
     * @return {Object} the found node
     */
    u.getNamedChild = function(tarNode, name)
    {
        var nodes = document.getElementsByName(name);

        for(var i = 0; i < nodes.length; i++)
        {
            if(nodes[i].parentNode === tarNode)
                return nodes[i];
        }

        return null;
    };

    /** Get the children of the given node that reside in the XML3D namespace
     *
     *  @param {!Object} node
     *  @return {Array.<Object>}
     */
    u.getXML3DChildren = function(node)
    {
        var children = [];

        var n = node.firstChild;
        while(n)
        {
            if(n.namespaceURI === XML3D.xml3dNS)
                children.push(n);

            n = n.nextSibling;
        }

        return children;
    };

    /** Traverses the Subgraph of the given node and returns all mesh nodes
     * 	within it.
     *
     * 	@param {Object} node
     *	@return {Array.<Object>} array of mesh nodes contained in the subgraph of node.
     */
    u.getMeshNodes = function(node)
    {
        var meshNodes = [];
        var traverseFn = function(currentNode) {

            if(currentNode.tagName.toLowerCase() === "mesh")
                meshNodes.push(currentNode);

            return true;
        };

        XMOT.util.traverseGraph(node, traverseFn);
        return meshNodes;
    };
}());
<commit_msg>util.NodeGetter: fixed bug<commit_after>(function(){

    "use strict";

    XMOT.namespace("XMOT.util");

    var u = XMOT.util;

    /** Returns the xml3d element in which the given element is contained.
     * If none is found, null is returned.
     *
     * @param {!Object} el
     * @return {Object}
     */
    u.getXml3dRoot = function(el)
    {
        if(!el) {
            throw new Error("XMOT.util.getXml3dRoot(): given element is not defined.");
        }
        if(!el.parentNode) {
            throw new Error("XMOT.util.getXml3dRoot(): given element has no parent node.");
        }

        if(el.tagName.toLowerCase() === "xml3d")
            return el;

        if(el.parentNode)
            return u.getXml3dRoot(el.parentNode);

        return null;
    };

    /** Internal helper method. Gets and/or sets a reference pointed to by attrName
     *  of the element el. For more information see XMOT.util.transform()
     *  or XMOT.util.shader().
     *
     *  @param {!Object} el
     *  @param {!string} attrName
     *  @param {Object} newRefNode
     *
     *  @return {Object}
     */
    function getOrSetRefNode(el, attrName, newRefNode)
    {
        var oldRefNode = null;

        var oldRef = el.getAttribute(attrName);
        if(oldRef && oldRef.length > 0)
            oldRefNode = XML3D.URIResolver.resolveLocal(oldRef);

        if(newRefNode)
        {
            var newRef = newRefNode.getAttribute("id");
            if(newRef && newRef.length > 0)
            {
                newRef = "#" + newRef;
                el.setAttribute(attrName, newRef);
            }
        }

        return oldRefNode;
    };

    /**
     * Retrieve or set the transform node of a given group node.
     *
     * @param {!Object} grp the desired group node
     * @param {Object} xfm (optional) the transform element to which grp's
     *  transform attribute should be set. The transform has to have an
     *  id attribute.
     *
     * @return {Object} if one argument is given, it returns the current transform
     *  element of el. If two arguments are given, it returns the transform element set
     *  before it was overridden by xfm.
     */
    u.transform = function(grp, xfm)
    {
        if(grp.tagName.toLowerCase() !== "group")
            throw "XMOT.util.transform(): given element is not a group.";

        return getOrSetRefNode(grp, "transform", xfm);
    };

    /** Retrieve or set the shader of the given group node.
     *
     * @param {!Object} grp the group of which to retrieve the shader.
     * @param {Object} sh (optional) the shader element to which el's shader
     *  attribute should be set. The shader has to have an id attribute.
     *
     * @return {Object} if one argument is given, it returns the current shader of el. If
     *  two arguments are given, it returns the shader set before it was overridden by sh.
     */
    u.shader = function(grp, sh)
    {
        if(grp.tagName.toLowerCase() !== "group")
            throw "XMOT.util.shader(): given element is not a group.";

        return getOrSetRefNode(grp, "shader", sh);
    };

    /**
     * Returns the first defs element of the given xml3d element. If none exists,
     * a corresponding element is created, appended to xml3d and returned.
     *
     * @param {!Object} xml3d the xml3d element of which to return the defs element
     *
     * @return {Object} the first defs element of the given xml3d element
     */
    u.getOrCreateDefs = function(xml3d)
    {
        var defs = XML3D.util.evaluateXPathExpr(
            xml3d, './/xml3d:defs[1]').singleNodeValue;

        if(!defs)
        {
            defs = XMOT.creation.element("defs");
            xml3d.appendChild(defs);
        }

        return defs;
    };

    /**
     * Returns the transform element corresponding to the given
     * group. If it doesn't exist, one will be created with the
     * id newId, appended to the defs section and targetGrp's
     * transform reference will be set to the newly created
     * element.
     *
     * @param {!Object} targetGrp the group to retrieve the transform from
     * @param {string} newId the id attribute of the transform to be created
     *
     * @return {Object} the transform corresponding to targetGrp
     */
    u.getOrCreateTransform = function(targetGrp, newId)
    {
        var t = XMOT.util.transform(targetGrp);

        if(t) // found it, just return
            return t;

        var xml3d = u.getXml3dRoot(targetGrp);
        var defs = u.getOrCreateDefs(xml3d);

        // create transform
        t = XMOT.creation.element("transform", {id: newId});
        defs.appendChild(t);
        targetGrp.setAttribute("transform", "#" + newId);

        return t;
    };

    /** Return the first child element of tarNode, whose "name" attribute
     * is equal to the given one. Useful for retrieving shader attributes.
     *
     * @param {!Object} tarNode
     * @param {string} name
     * @return {Object} the found node
     */
    u.getNamedChild = function(tarNode, name)
    {
        var nodes = document.getElementsByName(name);

        for(var i = 0; i < nodes.length; i++)
        {
            if(nodes[i].parentNode === tarNode)
                return nodes[i];
        }

        return null;
    };

    /** Get the children of the given node that reside in the XML3D namespace
     *
     *  @param {!Object} node
     *  @return {Array.<Object>}
     */
    u.getXML3DChildren = function(node)
    {
        var children = [];

        var n = node.firstChild;
        while(n)
        {
            if(n.namespaceURI === XML3D.xml3dNS)
                children.push(n);

            n = n.nextSibling;
        }

        return children;
    };

    /** Traverses the Subgraph of the given node and returns all mesh nodes
     * 	within it.
     *
     * 	@param {Object} node
     *	@return {Array.<Object>} array of mesh nodes contained in the subgraph of node.
     */
    u.getMeshNodes = function(node)
    {
        var meshNodes = [];
        var traverseFn = function(currentNode) {

            if(currentNode.tagName !== undefined
            && currentNode.tagName.toLowerCase() === "mesh")
                meshNodes.push(currentNode);

            return true;
        };

        XMOT.util.traverseGraph(node, traverseFn);
        return meshNodes;
    };
}());
<|endoftext|>


<commit_before>/**
 * Created by harry on 16/6/13.
 */

(function () {
    'use strict';

    angular.module('BlurAdmin.cms.reservation.booking')
        .controller('bookingCtrl', bookingCtrl);

    /** @ngInject */
    function bookingCtrl($scope, $state, $filter, $http, util, toastr) {

        $scope.search = {};

        $scope.departments = [];
        $scope.loadDepartments = function() {
            $http.get(util.baseApiUrl + 'departments', {})
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.departments = [];
                    }
                    else {
                        $scope.departments = response;
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        }
        $scope.loadDepartments();

        $scope.doctors = [];
        $scope.loadDoctors = function() {
            $http.get(util.baseApiUrl + 'doctors/1000', {})
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.doctors = [];
                    }
                    else {
                        $scope.doctors = response;
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        }
        $scope.loadDoctors();

        $scope.showDoctor = function(item) {
            if(item.doctor && $scope.doctors.length) {
                var selected = $filter('filter')($scope.doctors, {_id: item.doctor});
                return selected.length ? selected[0].name : '未设置';
            } else {
                return '未设置';
            }
        };

        $scope.schedules = [];
        $scope.loadSchedules = function() {
            $http.get(util.baseApiUrl + 'schedules/cms/populated')
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.schedules = [];
                    }
                    else {
                        $scope.schedules = response;
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        }
        $scope.loadSchedules();

        $scope.showSchedule = function(item) {
            if(item.schedule && $scope.schedules.length) {
                var selected = $filter('filter')($scope.schedules, {_id: item.schedule});
                return selected.length ? ((new Date(selected[0].date)).toISOString().slice(0,10) + ' ' + selected[0].period.name) : '未设置';
            } else {
                return '未设置';
            }
        };

        $scope.users = [];
        $scope.loadUsers = function() {
            $http.get(util.baseApiUrl + 'users/1000', {})
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.users = [];
                    }
                    else {
                        $scope.users = response;
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        }
        $scope.loadUsers();

        $scope.showUser = function(item) {
            if(item.user && $scope.users.length) {
                var selected = $filter('filter')($scope.users, {_id: item.user});
                return selected.length ? selected[0].name : '未设置';
            } else {
                return '未设置';
            }
        };

        // data
        $scope.bookings = [];
        $scope.getBookings = function() {
            $scope.myPromise = $http.get(util.baseApiUrl + 'bookings', {})
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.bookings = [];
                    }
                    else {
                        $scope.bookings = response;
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        }

        $scope.getBookings();

        $scope.$on('$viewContentLoaded', function(){
            //Here your view content is fully loaded !!
            if ($state.params.schedule) {
                // toastr.info($state.params.schedule);

                $scope.search.schedule = $state.params.schedule;
            }
        });

        //===========================================================

        $scope.addBooking = function() {
            //todo:
            // $scope.search.doctor = null; // reset
            // $scope.$apply();

            $scope.inserted = {
                doctor: $scope.search.doctor || null,
                schedule: $scope.search.schedule || null,
                user: null,
                status: '',
                score: 0,
                created: ''
            };

            $scope.bookings.push($scope.inserted);
        }

        $scope.removeBooking = function(id) {

            $http.delete(util.baseApiUrl + 'booking/' + id)
                .success(function (response) {
                    $scope.bookings = $filter('filter')($scope.bookings, {_id: '!'+id});

                    toastr.success('成功删除');
                })
                .error(function(err){
                    toastr.error(err.messageFormatted)
                });

        }

        $scope.validate = function(item) {
            if (!item){
                return false;
            }
            if (!item.doctor){
                toastr.error('药师 不能为空!');
                return false;
            }
            if (!item.schedule){
                toastr.error('预约不能为空!');
                return false;
            }
            if (!item.user){
                toastr.error('用户不能为空!');
                return false;
            }
            if (!item.status){
                toastr.error('状态不能为空!');
                return false;
            }
            return true;
        }

        $scope.saveBooking = function(data) {

            //validate
            if (!$scope.validate(data)){
                return;
            }

            // get schedule
            $http.get(util.baseApiUrl + 'schedule/' + data.schedule)
                .success(function(rsp) {
                    if (util.getErrorMessage(rsp)) {
                        return toastr.error(util.getErrorMessage(rsp));
                    };
                    data.date = rsp.date;

                    // 更新数据库
                    if (!data._id) { // create
                        $http.post(util.baseApiUrl + 'booking', data)
                            .success(function (response) {
                                if (util.getErrorMessage(response)) {
                                    $scope.bookings.pop();
                                    return toastr.error(util.getErrorMessage(response));
                                };
                                $scope.inserted = response;

                                $scope.bookings.push($scope.inserted);
                                toastr.success('成功创建');

                                // remove
                                $scope.bookings.splice($scope.bookings.length - 1, 1);

                            });
                    }
                    else{ // update
                        //angular.extend(data, {_id: id});
                        $http.patch(util.baseApiUrl + 'booking/' + data._id, data)
                            .success(function (response) {
                                //console.log(JSON.stringify(response))
                                if (!response) {
                                    toastr.error("no data");
                                }
                                else{
                                    toastr.success('成功更新');
                                }
                            });
                    }
                })

            //$scope.inserted = null;
        }

    }
})();<commit_msg>partly fixed booking.<commit_after>/**
 * Created by harry on 16/6/13.
 */

(function () {
    'use strict';

    angular.module('BlurAdmin.cms.reservation.booking')
        .controller('bookingCtrl', bookingCtrl);

    /** @ngInject */
    function bookingCtrl($scope, $state, $filter, $http, util, toastr) {

        $scope.search = {};

        $scope.departments = [];
        $scope.loadDepartments = function() {
            $http.get(util.baseApiUrl + 'departments', {})
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.departments = [];
                    }
                    else {
                        $scope.departments = response;
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        }
        $scope.loadDepartments();

        $scope.doctors = [];
        $scope.loadDoctors = function() {
            $http.get(util.baseApiUrl + 'doctors/1000', {})
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.doctors = [];
                    }
                    else {
                        $scope.doctors = response;
                        populateDepartmentDoctorSchedule();// tricky
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        }
        $scope.loadDoctors();

        $scope.showDoctor = function(item) {
            if(item.doctor && $scope.doctors.length) {
                var selected = $filter('filter')($scope.doctors, {_id: item.doctor});
                return selected.length ? selected[0].name : '未设置';
            } else {
                return '未设置';
            }
        };

        $scope.schedules = [];
        $scope.loadSchedules = function() {
            $http.get(util.baseApiUrl + 'schedules/cms/populated')
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.schedules = [];
                    }
                    else {
                        $scope.schedules = response;
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        }
        $scope.loadSchedules();

        $scope.showSchedule = function(item) {
            if(item.schedule && $scope.schedules.length) {
                var selected = $filter('filter')($scope.schedules, {_id: item.schedule});
                return selected.length ? ((new Date(selected[0].date)).toISOString().slice(0,10) + ' ' + selected[0].period.name) : '未设置';
            } else {
                return '未设置';
            }
        };

        $scope.users = [];
        $scope.loadUsers = function() {
            $http.get(util.baseApiUrl + 'users/1000', {})
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.users = [];
                    }
                    else {
                        $scope.users = response;
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        }
        $scope.loadUsers();

        $scope.showUser = function(item) {
            if(item.user && $scope.users.length) {
                var selected = $filter('filter')($scope.users, {_id: item.user});
                return selected.length ? selected[0].name : '未设置';
            } else {
                return '未设置';
            }
        };

        // data
        $scope.bookings = [];
        $scope.getBookings = function() {
            $scope.myPromise = $http.get(util.baseApiUrl + 'bookings', {})
                .success(function (response) {
                    // check if return null
                    if (response.return && response.return == 'null'){
                        $scope.bookings = [];
                    }
                    else {
                        $scope.bookings = response;
                    }

                })
                .error(function(error){
                    toastr.error(error.messageFormatted);
                });
        };
        $scope.getBookings();

        var populateDepartmentDoctorSchedule = function() {
            //Here your view content is fully loaded !!
            if ($state.params.schedule) {
                // toastr.info($state.params.schedule);

                $scope.search = {
                    schedule: $state.params.schedule
                };

                $scope.myPromise = $http.get(util.baseApiUrl + 'schedule/' + $state.params.schedule).then(
                    function(response) {
                        // check if return null
                        if (response.return && response.return == 'null'){
                        }
                        else {
                            $scope.search.doctor = response.data.doctor;

                            // get department id by doctor
                            $scope.doctors.some(function(doctor) {
                                if (doctor._id == $scope.search.doctor) {
                                    $scope.pre = {
                                        department: doctor.department
                                    };
                                    return true;
                                }
                            });

                        }
                    },
                    function(err) {
                        toastr.error(err.messageFormatted);
                    }
                );

            }
        }

        //===========================================================

        $scope.addBooking = function() {
            //todo:
            // $scope.search.doctor = null; // reset
            // $scope.$apply();

            $scope.inserted = {
                doctor: $scope.search.doctor || null,
                schedule: $scope.search.schedule || null,
                user: null,
                status: '',
                score: 0,
                created: ''
            };

            $scope.bookings.push($scope.inserted);
        }

        $scope.removeBooking = function(id) {

            $http.delete(util.baseApiUrl + 'booking/' + id)
                .success(function (response) {
                    $scope.bookings = $filter('filter')($scope.bookings, {_id: '!'+id});

                    toastr.success('成功删除');
                })
                .error(function(err){
                    toastr.error(err.messageFormatted)
                });

        }

        $scope.validate = function(item) {
            if (!item){
                return false;
            }
            if (!item.doctor){
                toastr.error('药师 不能为空!');
                return false;
            }
            if (!item.schedule){
                toastr.error('预约不能为空!');
                return false;
            }
            if (!item.user){
                toastr.error('用户不能为空!');
                return false;
            }
            if (!item.status){
                toastr.error('状态不能为空!');
                return false;
            }
            return true;
        }

        $scope.saveBooking = function(data) {

            //validate
            if (!$scope.validate(data)){
                return;
            }

            // get schedule
            $http.get(util.baseApiUrl + 'schedule/' + data.schedule)
                .success(function(rsp) {
                    if (util.getErrorMessage(rsp)) {
                        return toastr.error(util.getErrorMessage(rsp));
                    };
                    data.date = rsp.date;

                    // 更新数据库
                    if (!data._id) { // create
                        $http.post(util.baseApiUrl + 'booking', data)
                            .success(function (response) {
                                if (util.getErrorMessage(response)) {
                                    $scope.bookings.pop();
                                    return toastr.error(util.getErrorMessage(response));
                                };
                                $scope.inserted = response;

                                $scope.bookings.push($scope.inserted);
                                toastr.success('成功创建');

                                // remove
                                $scope.bookings.splice($scope.bookings.length - 1, 1);

                            });
                    }
                    else{ // update
                        //angular.extend(data, {_id: id});
                        $http.patch(util.baseApiUrl + 'booking/' + data._id, data)
                            .success(function (response) {
                                //console.log(JSON.stringify(response))
                                if (!response) {
                                    toastr.error("no data");
                                }
                                else{
                                    toastr.success('成功更新');
                                }
                            });
                    }
                })

            //$scope.inserted = null;
        }

    }
})();<|endoftext|>


<commit_before>/*!
 * Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file.
 */

import {WebexPlugin} from '@webex/webex-core';

const Flag = WebexPlugin.extend({
  namespace: 'Flag',

  /**
  * Archive a flag
  * @param {Object} flag
  * @param {Object} options
  * @returns {Promise<Object>} Resolves with the flag archival
  */
  archive(flag, options) {
    if (!flag.url) {
      return Promise.reject(new Error('`flag.url` is required'));
    }
    options = options || {};
    const params = {
      method: 'PUT',
      uri: flag.url,
      options,
      body: {
        state: 'archived'
      }
    };

    return this.webex.request(params)
      .then((res) => res.body);
  },

  /**
  * Flags an activity
  * @param {Object} activity
  * @param {Object} options
  * @returns {Promise<Object>} Resolves with the flag creation
  */
  create(activity, options) {
    if (!activity.url) {
      return Promise.reject(new Error('`activity.url` is required'));
    }
    options = options || {};
    const params = {
      method: 'POST',
      service: 'userApps',
      resource: '/flags',
      options,
      body: {
        'flag-item': activity.url,
        state: 'flagged'
      }
    };

    return this.webex.request(params)
      .then((res) => res.body);
  },

  /**
  * Gets a list of Flags for a user
  * @param {Object} options
  * @returns {Promise} Resolves with the fetched flags
  */
  list(options) {
    options = options || {};
    const params = {
      method: 'GET',
      service: 'userApps',
      resource: '/flags',
      options,
      qs: {
        state: 'flagged'
      }
    };

    return this.webex.request(params)
      .then((res) => res.body.items);
  },

  /**
  * Gets an array of activities where the status is 200
  * @param {Object} flags
  * @returns {Promise<Object>} Resolves with the activities
  * TODO: this should be implemented as a batched request when migrating to the modular sdk
  */
  async mapToActivities(flags) {
    const mapUrlActivities = new Map();

    for (const flag of flags) {
      const convoUrlRegex = /(.*)\/activities\//;
      const activity = flag['flag-item'];
      const match = convoUrlRegex.exec(activity);

      if (match) {
        const url = match[1];
        let activities = mapUrlActivities.get(url);

        if (!activities) {
          activities = [];
          mapUrlActivities.set(url, activities);
        }
        activities.push(activity);
      }
      else {
        this.logger.warn(
          `The activity URL has a strange format (${activity}). Ignoring it.`
        );
      }
    }

    const responses = await Promise.all(
      Array.from(mapUrlActivities, async ([convoUrl, activityUrls]) => {
        const params = {
          method: 'POST',
          url: `${convoUrl}/bulk_activities_fetch`,
          body: {
            activityUrls
          }
        };

        const res = await this.webex.request(params);

        return res.body.multistatus.reduce((activitiesArr, statusData) => {
          if (statusData.status === '200') {
            activitiesArr.push(statusData.data.activity);
          }

          return activitiesArr;
        }, []);
      })
    );

    return responses.flat();
  },

  /**
  * Delete a flag
  * @param {Object} flag
  * @param {Object} options
  * @returns {Promise<Object>} Resolves with the flag deletion
  */
  delete(flag, options) {
    if (!flag.url) {
      return Promise.reject(new Error('`flag.url` is required'));
    }
    options = options || {};
    const params = {
      method: 'DELETE',
      options,
      uri: flag.url
    };

    return this.request(params)
      .then((res) => res.body);
  },

  /**
  * UnFlags an activity
  * @param {Object} flag
  * @param {Object} options
  * @returns {Promise<Object>} Resolves with the flag removal
  */
  unflag(flag, options) {
    if (!flag.url) {
      return Promise.reject(new Error('`flag.url` is required'));
    }
    options = options || {};
    const params = {
      method: 'PUT',
      uri: flag.url,
      options,
      body: {
        state: 'unflagged'
      }
    };

    return this.webex.request(params)
      .then((res) => res.body);
  }

});

export default Flag;
<commit_msg>fix(flag): 'flat' isn't available everywhere<commit_after>/*!
 * Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file.
 */
import {flatten} from 'lodash';
import {WebexPlugin} from '@webex/webex-core';

const Flag = WebexPlugin.extend({
  namespace: 'Flag',

  /**
  * Archive a flag
  * @param {Object} flag
  * @param {Object} options
  * @returns {Promise<Object>} Resolves with the flag archival
  */
  archive(flag, options) {
    if (!flag.url) {
      return Promise.reject(new Error('`flag.url` is required'));
    }
    options = options || {};
    const params = {
      method: 'PUT',
      uri: flag.url,
      options,
      body: {
        state: 'archived'
      }
    };

    return this.webex.request(params)
      .then((res) => res.body);
  },

  /**
  * Flags an activity
  * @param {Object} activity
  * @param {Object} options
  * @returns {Promise<Object>} Resolves with the flag creation
  */
  create(activity, options) {
    if (!activity.url) {
      return Promise.reject(new Error('`activity.url` is required'));
    }
    options = options || {};
    const params = {
      method: 'POST',
      service: 'userApps',
      resource: '/flags',
      options,
      body: {
        'flag-item': activity.url,
        state: 'flagged'
      }
    };

    return this.webex.request(params)
      .then((res) => res.body);
  },

  /**
  * Gets a list of Flags for a user
  * @param {Object} options
  * @returns {Promise} Resolves with the fetched flags
  */
  list(options) {
    options = options || {};
    const params = {
      method: 'GET',
      service: 'userApps',
      resource: '/flags',
      options,
      qs: {
        state: 'flagged'
      }
    };

    return this.webex.request(params)
      .then((res) => res.body.items);
  },

  /**
  * Gets an array of activities where the status is 200
  * @param {Object} flags
  * @returns {Promise<Object>} Resolves with the activities
  * TODO: this should be implemented as a batched request when migrating to the modular sdk
  */
  async mapToActivities(flags) {
    const mapUrlActivities = new Map();

    for (const flag of flags) {
      const convoUrlRegex = /(.*)\/activities\//;
      const activity = flag['flag-item'];
      const match = convoUrlRegex.exec(activity);

      if (match) {
        const url = match[1];
        let activities = mapUrlActivities.get(url);

        if (!activities) {
          activities = [];
          mapUrlActivities.set(url, activities);
        }
        activities.push(activity);
      }
      else {
        this.logger.warn(
          `The activity URL has a strange format (${activity}). Ignoring it.`
        );
      }
    }

    const responses = await Promise.all(
      Array.from(mapUrlActivities, async ([convoUrl, activityUrls]) => {
        const params = {
          method: 'POST',
          url: `${convoUrl}/bulk_activities_fetch`,
          body: {
            activityUrls
          }
        };

        const res = await this.webex.request(params);

        return res.body.multistatus.reduce((activitiesArr, statusData) => {
          if (statusData.status === '200') {
            activitiesArr.push(statusData.data.activity);
          }

          return activitiesArr;
        }, []);
      })
    );

    return flatten(responses);
  },

  /**
  * Delete a flag
  * @param {Object} flag
  * @param {Object} options
  * @returns {Promise<Object>} Resolves with the flag deletion
  */
  delete(flag, options) {
    if (!flag.url) {
      return Promise.reject(new Error('`flag.url` is required'));
    }
    options = options || {};
    const params = {
      method: 'DELETE',
      options,
      uri: flag.url
    };

    return this.request(params)
      .then((res) => res.body);
  },

  /**
  * UnFlags an activity
  * @param {Object} flag
  * @param {Object} options
  * @returns {Promise<Object>} Resolves with the flag removal
  */
  unflag(flag, options) {
    if (!flag.url) {
      return Promise.reject(new Error('`flag.url` is required'));
    }
    options = options || {};
    const params = {
      method: 'PUT',
      uri: flag.url,
      options,
      body: {
        state: 'unflagged'
      }
    };

    return this.webex.request(params)
      .then((res) => res.body);
  }

});

export default Flag;
<|endoftext|>


<commit_before>// TODO LIST:
// 1. Replace main js object from ES Class
// 2. Replace forms and arrays for ES Map

var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
// -----------------------
// BuilderProvider
// -----------------------

import { Utils }         from './builder.classes';
import { Component }     from './builder.classes';
import { FormObject }    from './builder.classes';
import { Page }          from './builder.classes';
import { Tag }           from './builder.classes';

export function BuilderProvider() {

  // Constants
  const displayTypes = Object.freeze({
    SINGLE: 'SINGLE',
    WIZARD: 'WIZARD'
  });

  var $injector = null, $http = null, $log = null, $templateCache = null;
  this.components = {};
  this.forms = { 'default': [] }; // replace for map
  this.pages = [];
  this.tags = [];
  this.groups = [];
  this.dependencies = [];
  this.broadcastChannel = {
    selectPage: '$selectPage',
    selectInput: '$selectInput',
    updateInput: '$updateInput',
    saveInput: '$saveInput',
    changeWizardStep: '$changeWizardStep',
    changeFormInputEvent: '$changeFormInputEvent'
  };

  let display = displayTypes.SINGLE;
  let current = {
    formObject: null,
    formObjectScope: null,
    formObjectElement: null,
    formName: null,
    page: null,
    form: this.forms['default']
  }

  this.convertComponent = (name, component) => {
    let result = new Component(name, component);

    if (!result.template && !result.templateUrl)
      $log.error("The template is empty.");

    if (!result.popoverTemplate && !result.popoverTemplateUrl)
      $log.error("The popoverTemplate is empty.");

    return result;
  };

  this.convertFormObject = (name, formObject) => {
    formObject = formObject || {};
    let component = this.components[formObject.component];
    if (component == null) {
      throw "The component " + formObject.component + " was not registered.";
    }

    let result = new FormObject(name, formObject, component)
    return result;
  };

  this.reindexFormObject = (name) => {
    var formObjects, i, index, ref;
    formObjects = this.forms[name];
    for (index = i = 0, ref = formObjects.length; i < ref; index = i += 1) {
      formObjects[index].index = index;
    }
  };

  this.setupProviders = (injector) => {
    $injector = injector;
    $http = $injector.get('$http');
    $templateCache = $injector.get('$templateCache');
    $log = $injector.get('$log');
  };

  this.loadTemplate = (component) => {
    if (component.template == null) {
      $http.get(component.templateUrl, {
        cache: $templateCache
      }).success((template) => {
        component.template = template;
      });
    }
    if (component.popoverTemplate == null) {
      $http.get(component.popoverTemplateUrl, {
        cache: $templateCache
      }).success((template) => {
        component.popoverTemplate = template;
      });
    }
  };

  this.copyObjectToScope = (object, scope) => {
    // Copy object (ng-repeat="object in objects") to scope without `hashKey`.
    var key, value;
    for (key in object) {
      value = object[key];
      if (key !== '$$hashKey') {
        scope[key] = value;
      }
    }
  }

  this.registerComponent = (name, component) => {
    if (component == null)
      component = {};

    /*
    Register the component for form-builder.
    @param name: The component name.
    @param component: The component object.
        group: {string} The component group.
        label: {string} The label of the input.
        description: {string} The description of the input.
        placeholder: {string} The placeholder of the input.
        editable: {bool} Is the form object editable?
        required: {bool} Is the form object required?
        validation: {string} angular-validator. "/regex/" or "[rule1, rule2]". (default is RegExp(.*))
        validationOptions: {array} [{rule: angular-validator, label: 'option label'}] the options for the validation. (default is [])
        options: {array} The input options.
        multipeChoice: {bool} checkbox could use this to convert input (default is no)
        template: {string} html template
        templateUrl: {string} The url of the template.
        popoverTemplate: {string} html template
        popoverTemplateUrl: {string} The url of the popover template.
     */
    if (this.components[name] == null) {
      let newComponent = this.convertComponent(name, component);
      this.components[name] = newComponent;

      if ($injector != null)
        this.loadTemplate(newComponent);
      if (newComponent.group, indexOf.call(this.groups, newComponent.group) < 0)
        this.groups.push(newComponent.group);

    } else {
      // $log.info("The component " + name + " was registered.");
    }
  };

  this.addFormObject = (name, formObject) => {
    if (formObject == null)
        formObject = {};
    // insert the form object into the form at last.
    let base;
    if ((base = this.forms)[name] == null)
      base[name] = [];

    return this.insertFormObject(name, this.forms[name].length, formObject);
  };

  this.getCurrentFormObject = () => {
    return current.formObject;
  }

  this.selectCurrentFormObject = (formName, formObject, element, objectScope) => {
    current.formName = formName;
    current.form = this.forms[formName];
    current.formObject = angular.copy(formObject);
    current.formObjectScope = objectScope;

    if(current.formObjectElement)
      current.formObjectElement.removeClass('active');

    current.formObjectElement = element
    current.formObjectElement.addClass('active');
  }

  this.updateFormObjectScope = (formObject, objectScope) => {
    objectScope = objectScope || current.formObjectScope;
    this.copyObjectToScope(formObject, objectScope);
  }

  this.addForm = (name) => {
    if(!this.forms[name])
      this.forms[name] = [];
    return this.forms[name];
  }

  this.getCurrentPage = () => {
    return current.page;
  }

  this.selectCurrentPage = (index) => {
    return current.page = this.pages[index];
  }

  this.addPage = (page) => {
    let pageNumber = this.pages.length;

    page = page || {};
    page.index = page.index || pageNumber;
    page.formReference = page.formReference || ('form' + pageNumber);
    page.components = this.addForm('form' + pageNumber);

    this.insertPage(page, pageNumber);
  }

  this.removePage = function(pageKey) {
    var index = this.pages.findIndex(function (page) {
      return page.key == pageKey;
    });
    if(this.pages.length > 1) {
      this.pages.splice(index, 1);
      if(index > this.getCurrentPage().index)
        this.selectCurrentPage(index-1);
      else
        this.selectCurrentPage(index+1);
    } else {
      $log.error("Cant delete the first page.");
    }
  };

  this.insertPage = (page, pageNumber) => {
    page = new Page(page);
    this.pages.push(page);
    this.selectCurrentPage(pageNumber);
    return page;
  }

  this.insertFormObject = (name, index, formObject) => {

    if (formObject == null)
      formObject = {};

    /*
    Insert the form object into the form at {index}.
    @param name: The form name.
    @param index: The form object index.
    @param form: The form object.
        id: The form object id.
        component: {string} The component name
        editable: {bool} Is the form object editable? (default is yes)
        label: {string} The form object label.
        description: {string} The form object description.
        placeholder: {string} The form object placeholder.
        options: {array} The form object options.
        required: {bool} Is the form object required? (default is no)
        validation: {string} angular-validator. "/regex/" or "[rule1, rule2]".
        [index]: {int} The form object index. It will be updated by $builder.
    @return: The form object.
     */
    let base;
    if ((base = this.forms)[name] == null)
      base[name] = [];

    if (index > this.forms[name].length) {
      index = this.forms[name].length;
    } else if (index < 0) {
      index = 0;
    }

    this.forms[name].splice(index, 0, this.convertFormObject(name, formObject));
    this.reindexFormObject(name);
    // this.addAnswerDependency(formObject, answer);
    return this.forms[name][index];
  };

  this.removeFormObject = (name, index) => {
    /*
    Remove the form object by the index.
    @param name: The form name.
    @param index: The form object index.
     */
    name = name || current.formName
    index = index || current.formObject.index;
    let formObjects = this.forms[name];
    formObjects.splice(index, 1);

    if(!formObjects.length)
      if(current.page)
        if(current.page.form.name == current.formName)
          current.formObject = undefined;

    return this.reindexFormObject(name);
  };

  this.duplicateFormObject = (name, formObject) => {
    name = name || current.formName
    formObject = formObject || current.formObject

    let index = formObject.index
    let formObjects = this.forms[name];
    formObjects.splice(index, 0, angular.copy(formObject));

    return this.reindexFormObject(name);
  }

  this.updateFormObjectIndex = (name, oldIndex, newIndex) => {
    /*
    Update the index of the form object.
    @param name: The form name.
    @param oldIndex: The old index.
    @param newIndex: The new index.
     */
    if (oldIndex == newIndex)
      return;

    let formObjects = this.forms[name];
    let formObject = formObjects.splice(oldIndex, 1)[0];
    formObjects.splice(newIndex, 0, formObject);
    return this.reindexFormObject(name);
  };

  this.addTag = (tag) => {
    tag = new Tag(tag);
    this.tags.push(new Tag(tag));
    return tag;
  }

  this.removeTag = (tagKey) => {
    let index = this.tags.findIndex(tag => tag.key == tagKey)
    this.tags.splice(index, 1);
  }

  this.addAnswerDependency = (formObject, formObjectHandler, formAnswer) => {
    this.removeAnswerDependency(formObject);
    formObject.display = false;
    this.dependencies.push({
      formObjectTargetKey: formObject.key,
      formObjectKey: formObjectHandler,
      formAnswerKey: formAnswer
    });
  };

  this.removeAnswerDependency = (formObject, deepDestroy = false) => {
    formObject.display = true;
    this.dependencies.forEach((d, index) => {
      if(d.formObjectTargetKey == formObject.key) {
        this.dependencies.splice(index, 1);
        if(deepDestroy) formObject.dependentFrom = {};
      }
    });
  }

  this.removeAnswerDependencybyTarget = (formObject) => {
    let dependentTargets = this.findDependencyTargets(formObject.key)
    if(!dependentTargets.length) return false;

    dependentTargets.forEach( dependentFormObject => {
      this.removeAnswerDependency(dependentFormObject, true);
    });
  }

  this.findDependencyTargets = (formObjectKey) => {
    return this.dependencies.filter( d => {
      return d.formObjectKey == formObjectKey;
    }).map( d => {
      return this.findFormObjectByKey(d.formObjectTargetKey)
    });
  }

  this.findFormObjectByKey = (key) => {
    let selectedFormObject = Object.keys(this.forms).reduce((sum, key) => {
      sum = sum.concat(this.forms[key]);
      return sum;
    }, []).filter(fo => { return fo.key == key; })[0];
    return selectedFormObject || false
  }

  this.findPageByFormObjectKey = (key) => {
    let selectedPage = this.pages.find((page) => {
      let selectedComponent = page.components.find((component) => {
        return component.key == key;
      });
      return selectedComponent;
    });
    return selectedPage || false;
  }

  this.setDisplay = (displayType) => {
    if(displayType == displayTypes.SINGLE || displayType == displayTypes.WIZARD) {
      display = displayType
      if(display == displayTypes.SINGLE)
        this.selectCurrentPage(0);
    }
    else
      $log.error("The display type is not permited");
  }

  this.getDisplay = () => {
    return display;
  }

  this.setupDefaults = (defaultValues) => {
    this.pages.length = 0;
    this.dependencies.length = 0;
    this.forms = {};

    display = defaultValues.display || display;
    this.tags = defaultValues.tags || this.tags;

    if(defaultValues.components) {
      if(display == displayTypes.WIZARD) {
        defaultValues.components.forEach((page) => {
          let formObjects = angular.copy(page.components);
          this.addPage(page);
          formObjects.forEach((formObject) => {
            this.addFormObject(page.formReference, formObject);
          });
        });
      }
      if(display == displayTypes.SINGLE) {
        this.addPage();
        defaultValues.components.forEach((formObject) => {
          this.addFormObject(this.pages[0].formReference, formObject);
        });
      }
    }
  }

  this.$get = [
    '$injector', function($injector) {
      this.setupProviders($injector);
      let components = this.components;
      for (let name in components) {
        let component = components[name];
        this.loadTemplate(component);
      }
      return {
        // Objects & Arrays
        forms: this.forms,
        pages: this.pages,
        groups: this.groups,
        tags: this.tags,
        dependencies: this.dependencies,
        components: this.components,
        // Pages handlers
        addPage: this.addPage,
        removePage: this.removePage,
        getCurrentPage: this.getCurrentPage,
        selectCurrentPage: this.selectCurrentPage,
        findPageByFormObjectKey: this.findPageByFormObjectKey,
        // Form Objects handlers
        addForm: this.addForm,
        getCurrentFormObject: this.getCurrentFormObject,
        selectCurrentFormObject: this.selectCurrentFormObject,
        updateFormObjectScope: this.updateFormObjectScope,
        addFormObject: this.addFormObject,
        insertFormObject: this.insertFormObject,
        removeFormObject: this.removeFormObject,
        duplicateFormObject: this.duplicateFormObject,
        updateFormObjectIndex: this.updateFormObjectIndex,
        findFormObjectByKey: this.findFormObjectByKey,
        // Tags handlers
        addTag: this.addTag,
        removeTag: this.removeTag,
        // Dependencies hadlers
        addAnswerDependency: this.addAnswerDependency,
        removeAnswerDependency: this.removeAnswerDependency,
        removeAnswerDependencybyTarget: this.removeAnswerDependencybyTarget,
        findDependencyTargets: this.findDependencyTargets,
        // Display handlers
        setDisplay: this.setDisplay,
        getDisplay: this.getDisplay,
        displayTypes: displayTypes,
        // Components HANDLERS
        registerComponent: this.registerComponent,
        // Other utils functions
        broadcastChannel: this.broadcastChannel,
        copyObjectToScope: this.copyObjectToScope,
        generateKey: new Utils().generateKey(),
        setupDefaults: this.setupDefaults
      };
    }
  ];
}
<commit_msg>feat(): adds dependencies on setup method<commit_after>// TODO LIST:
// 1. Replace main js object from ES Class
// 2. Replace forms and arrays for ES Map

var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
// -----------------------
// BuilderProvider
// -----------------------

import { Utils }         from './builder.classes';
import { Component }     from './builder.classes';
import { FormObject }    from './builder.classes';
import { Page }          from './builder.classes';
import { Tag }           from './builder.classes';

export function BuilderProvider() {

  // Constants
  const displayTypes = Object.freeze({
    SINGLE: 'SINGLE',
    WIZARD: 'WIZARD'
  });

  var $injector = null, $http = null, $log = null, $templateCache = null;
  this.components = {};
  this.forms = { 'default': [] }; // replace for map
  this.pages = [];
  this.tags = [];
  this.groups = [];
  this.dependencies = [];
  this.broadcastChannel = {
    selectPage: '$selectPage',
    selectInput: '$selectInput',
    updateInput: '$updateInput',
    saveInput: '$saveInput',
    changeWizardStep: '$changeWizardStep',
    changeFormInputEvent: '$changeFormInputEvent'
  };

  let display = displayTypes.SINGLE;
  let current = {
    formObject: null,
    formObjectScope: null,
    formObjectElement: null,
    formName: null,
    page: null,
    form: this.forms['default']
  }

  this.convertComponent = (name, component) => {
    let result = new Component(name, component);

    if (!result.template && !result.templateUrl)
      $log.error("The template is empty.");

    if (!result.popoverTemplate && !result.popoverTemplateUrl)
      $log.error("The popoverTemplate is empty.");

    return result;
  };

  this.convertFormObject = (name, formObject) => {
    formObject = formObject || {};
    let component = this.components[formObject.component];
    if (component == null) {
      throw "The component " + formObject.component + " was not registered.";
    }

    let result = new FormObject(name, formObject, component)
    return result;
  };

  this.reindexFormObject = (name) => {
    var formObjects, i, index, ref;
    formObjects = this.forms[name];
    for (index = i = 0, ref = formObjects.length; i < ref; index = i += 1) {
      formObjects[index].index = index;
    }
  };

  this.setupProviders = (injector) => {
    $injector = injector;
    $http = $injector.get('$http');
    $templateCache = $injector.get('$templateCache');
    $log = $injector.get('$log');
  };

  this.loadTemplate = (component) => {
    if (component.template == null) {
      $http.get(component.templateUrl, {
        cache: $templateCache
      }).success((template) => {
        component.template = template;
      });
    }
    if (component.popoverTemplate == null) {
      $http.get(component.popoverTemplateUrl, {
        cache: $templateCache
      }).success((template) => {
        component.popoverTemplate = template;
      });
    }
  };

  this.copyObjectToScope = (object, scope) => {
    // Copy object (ng-repeat="object in objects") to scope without `hashKey`.
    var key, value;
    for (key in object) {
      value = object[key];
      if (key !== '$$hashKey') {
        scope[key] = value;
      }
    }
  }

  this.registerComponent = (name, component) => {
    if (component == null)
      component = {};

    /*
    Register the component for form-builder.
    @param name: The component name.
    @param component: The component object.
        group: {string} The component group.
        label: {string} The label of the input.
        description: {string} The description of the input.
        placeholder: {string} The placeholder of the input.
        editable: {bool} Is the form object editable?
        required: {bool} Is the form object required?
        validation: {string} angular-validator. "/regex/" or "[rule1, rule2]". (default is RegExp(.*))
        validationOptions: {array} [{rule: angular-validator, label: 'option label'}] the options for the validation. (default is [])
        options: {array} The input options.
        multipeChoice: {bool} checkbox could use this to convert input (default is no)
        template: {string} html template
        templateUrl: {string} The url of the template.
        popoverTemplate: {string} html template
        popoverTemplateUrl: {string} The url of the popover template.
     */
    if (this.components[name] == null) {
      let newComponent = this.convertComponent(name, component);
      this.components[name] = newComponent;

      if ($injector != null)
        this.loadTemplate(newComponent);
      if (newComponent.group, indexOf.call(this.groups, newComponent.group) < 0)
        this.groups.push(newComponent.group);

    } else {
      // $log.info("The component " + name + " was registered.");
    }
  };

  this.addFormObject = (name, formObject) => {
    if (formObject == null)
        formObject = {};
    // insert the form object into the form at last.
    let base;
    if ((base = this.forms)[name] == null)
      base[name] = [];

    return this.insertFormObject(name, this.forms[name].length, formObject);
  };

  this.getCurrentFormObject = () => {
    return current.formObject;
  }

  this.selectCurrentFormObject = (formName, formObject, element, objectScope) => {
    current.formName = formName;
    current.form = this.forms[formName];
    current.formObject = angular.copy(formObject);
    current.formObjectScope = objectScope;

    if(current.formObjectElement)
      current.formObjectElement.removeClass('active');

    current.formObjectElement = element
    current.formObjectElement.addClass('active');
  }

  this.updateFormObjectScope = (formObject, objectScope) => {
    objectScope = objectScope || current.formObjectScope;
    this.copyObjectToScope(formObject, objectScope);
  }

  this.addForm = (name) => {
    if(!this.forms[name])
      this.forms[name] = [];
    return this.forms[name];
  }

  this.getCurrentPage = () => {
    return current.page;
  }

  this.selectCurrentPage = (index) => {
    return current.page = this.pages[index];
  }

  this.addPage = (page) => {
    let pageNumber = this.pages.length;

    page = page || {};
    page.index = page.index || pageNumber;
    page.formReference = page.formReference || ('form' + pageNumber);
    page.components = this.addForm('form' + pageNumber);

    this.insertPage(page, pageNumber);
  }

  this.removePage = function(pageKey) {
    var index = this.pages.findIndex(function (page) {
      return page.key == pageKey;
    });
    if(this.pages.length > 1) {
      this.pages.splice(index, 1);
      if(index > this.getCurrentPage().index)
        this.selectCurrentPage(index-1);
      else
        this.selectCurrentPage(index+1);
    } else {
      $log.error("Cant delete the first page.");
    }
  };

  this.insertPage = (page, pageNumber) => {
    page = new Page(page);
    this.pages.push(page);
    this.selectCurrentPage(pageNumber);
    return page;
  }

  this.insertFormObject = (name, index, formObject) => {

    if (formObject == null)
      formObject = {};

    /*
    Insert the form object into the form at {index}.
    @param name: The form name.
    @param index: The form object index.
    @param form: The form object.
        id: The form object id.
        component: {string} The component name
        editable: {bool} Is the form object editable? (default is yes)
        label: {string} The form object label.
        description: {string} The form object description.
        placeholder: {string} The form object placeholder.
        options: {array} The form object options.
        required: {bool} Is the form object required? (default is no)
        validation: {string} angular-validator. "/regex/" or "[rule1, rule2]".
        [index]: {int} The form object index. It will be updated by $builder.
    @return: The form object.
     */
    let base;
    if ((base = this.forms)[name] == null)
      base[name] = [];

    if (index > this.forms[name].length) {
      index = this.forms[name].length;
    } else if (index < 0) {
      index = 0;
    }

    this.forms[name].splice(index, 0, this.convertFormObject(name, formObject));
    this.reindexFormObject(name);
    // this.addAnswerDependency(formObject, answer);
    return this.forms[name][index];
  };

  this.removeFormObject = (name, index) => {
    /*
    Remove the form object by the index.
    @param name: The form name.
    @param index: The form object index.
     */
    name = name || current.formName
    index = index || current.formObject.index;
    let formObjects = this.forms[name];
    formObjects.splice(index, 1);

    if(!formObjects.length)
      if(current.page)
        if(current.page.form.name == current.formName)
          current.formObject = undefined;

    return this.reindexFormObject(name);
  };

  this.duplicateFormObject = (name, formObject) => {
    name = name || current.formName
    formObject = formObject || current.formObject

    let index = formObject.index
    let formObjects = this.forms[name];
    formObjects.splice(index, 0, angular.copy(formObject));

    return this.reindexFormObject(name);
  }

  this.updateFormObjectIndex = (name, oldIndex, newIndex) => {
    /*
    Update the index of the form object.
    @param name: The form name.
    @param oldIndex: The old index.
    @param newIndex: The new index.
     */
    if (oldIndex == newIndex)
      return;

    let formObjects = this.forms[name];
    let formObject = formObjects.splice(oldIndex, 1)[0];
    formObjects.splice(newIndex, 0, formObject);
    return this.reindexFormObject(name);
  };

  this.addTag = (tag) => {
    tag = new Tag(tag);
    this.tags.push(new Tag(tag));
    return tag;
  }

  this.removeTag = (tagKey) => {
    let index = this.tags.findIndex(tag => tag.key == tagKey)
    this.tags.splice(index, 1);
  }

  this.addAnswerDependency = (formObject, formObjectHandler, formAnswer) => {
    this.removeAnswerDependency(formObject);
    formObject.display = false;
    this.dependencies.push({
      formObjectTargetKey: formObject.key,
      formObjectKey: formObjectHandler,
      formAnswerKey: formAnswer
    });
  };

  this.removeAnswerDependency = (formObject, deepDestroy = false) => {
    formObject.display = true;
    this.dependencies.forEach((d, index) => {
      if(d.formObjectTargetKey == formObject.key) {
        this.dependencies.splice(index, 1);
        if(deepDestroy) formObject.dependentFrom = {};
      }
    });
  }

  this.removeAnswerDependencybyTarget = (formObject) => {
    let dependentTargets = this.findDependencyTargets(formObject.key)
    if(!dependentTargets.length) return false;

    dependentTargets.forEach( dependentFormObject => {
      this.removeAnswerDependency(dependentFormObject, true);
    });
  }

  this.findDependencyTargets = (formObjectKey) => {
    return this.dependencies.filter( d => {
      return d.formObjectKey == formObjectKey;
    }).map( d => {
      return this.findFormObjectByKey(d.formObjectTargetKey)
    });
  }

  this.findFormObjectByKey = (key) => {
    let selectedFormObject = Object.keys(this.forms).reduce((sum, key) => {
      sum = sum.concat(this.forms[key]);
      return sum;
    }, []).filter(fo => { return fo.key == key; })[0];
    return selectedFormObject || false
  }

  this.findPageByFormObjectKey = (key) => {
    let selectedPage = this.pages.find((page) => {
      let selectedComponent = page.components.find((component) => {
        return component.key == key;
      });
      return selectedComponent;
    });
    return selectedPage || false;
  }

  this.setDisplay = (displayType) => {
    if(displayType == displayTypes.SINGLE || displayType == displayTypes.WIZARD) {
      display = displayType
      if(display == displayTypes.SINGLE)
        this.selectCurrentPage(0);
    }
    else
      $log.error("The display type is not permited");
  }

  this.getDisplay = () => {
    return display;
  }

  this.setupDefaults = (defaultValues) => {
    this.pages.length = 0;
    this.dependencies.length = 0;
    this.forms = {};

    display = defaultValues.display || display;
    this.tags = defaultValues.tags || this.tags;

    if(defaultValues.components) {
      if(display == displayTypes.WIZARD) {
        defaultValues.components.forEach((page) => {
          let formObjects = angular.copy(page.components);
          this.addPage(page);
          formObjects.forEach((formObject) => {
            this.addFormObject(page.formReference, formObject);
          });
        });
      }
      if(display == displayTypes.SINGLE) {
        this.addPage();
        defaultValues.components.forEach((formObject) => {
          this.addFormObject(this.pages[0].formReference, formObject);
        });
      }
    }

    if (defaultValues.dependencies.length)
      defaultValues.dependencies.forEach(function (d) {
        let formObject = _this.findFormObjectByKey(d.formObjectTargetKey);
        _this.addAnswerDependency(formObject, d.formObjectKey, d.formAnswerKey);
      });
  }

  this.$get = [
    '$injector', function($injector) {
      this.setupProviders($injector);
      let components = this.components;
      for (let name in components) {
        let component = components[name];
        this.loadTemplate(component);
      }
      return {
        // Objects & Arrays
        forms: this.forms,
        pages: this.pages,
        groups: this.groups,
        tags: this.tags,
        dependencies: this.dependencies,
        components: this.components,
        // Pages handlers
        addPage: this.addPage,
        removePage: this.removePage,
        getCurrentPage: this.getCurrentPage,
        selectCurrentPage: this.selectCurrentPage,
        findPageByFormObjectKey: this.findPageByFormObjectKey,
        // Form Objects handlers
        addForm: this.addForm,
        getCurrentFormObject: this.getCurrentFormObject,
        selectCurrentFormObject: this.selectCurrentFormObject,
        updateFormObjectScope: this.updateFormObjectScope,
        addFormObject: this.addFormObject,
        insertFormObject: this.insertFormObject,
        removeFormObject: this.removeFormObject,
        duplicateFormObject: this.duplicateFormObject,
        updateFormObjectIndex: this.updateFormObjectIndex,
        findFormObjectByKey: this.findFormObjectByKey,
        // Tags handlers
        addTag: this.addTag,
        removeTag: this.removeTag,
        // Dependencies hadlers
        addAnswerDependency: this.addAnswerDependency,
        removeAnswerDependency: this.removeAnswerDependency,
        removeAnswerDependencybyTarget: this.removeAnswerDependencybyTarget,
        findDependencyTargets: this.findDependencyTargets,
        // Display handlers
        setDisplay: this.setDisplay,
        getDisplay: this.getDisplay,
        displayTypes: displayTypes,
        // Components HANDLERS
        registerComponent: this.registerComponent,
        // Other utils functions
        broadcastChannel: this.broadcastChannel,
        copyObjectToScope: this.copyObjectToScope,
        generateKey: new Utils().generateKey(),
        setupDefaults: this.setupDefaults
      };
    }
  ];
}
<|endoftext|>


<commit_before>/**
 *
 * @param {String[]|Number[]} values
 * @param maxThreshold
 * @constructor
 */
export default class Vocab {
  constructor(values, maxThreshold = 0) {
    if (values === undefined) return;

    this.values = values;
    // go over all characters and keep track of all unique ones seen
    // count up all characters
    this.indexTable = {};
    this.characterTable = {};
    this.characters = [];
    this.buildCharactersFromIterable(values);
    this.buildTables(maxThreshold);
  }

  buildCharactersFromIterable(values) {
    let tempCharactersTable = {};
    for (let vocabIndex = 0, vocabLength = values.length; vocabIndex < vocabLength; vocabIndex++) {
      let characters = values[vocabIndex];

      if (characters.hasOwnProperty('length')) {
        for (let characterIndex = 0, charactersLength = characters.length; characterIndex < charactersLength; characterIndex++) {
          let character = characters[characterIndex];
          if (tempCharactersTable.hasOwnProperty(character)) continue;
          tempCharactersTable[character] = true;
          this.characters.push(character);
        }
      } else {
        let character = values[vocabIndex];
        if (tempCharactersTable.hasOwnProperty(character)) continue;
        tempCharactersTable[vocabIndex] = true;
        this.characters.push(character);
      }
    }
  }

  buildTables(maxThreshold) {
    // filter by count threshold and create pointers
    let charactersLength = this.characters.length;
    for(let characterIndex = 0; characterIndex < charactersLength; characterIndex++) {
      let character = this.characters[characterIndex];
      if(characterIndex >= maxThreshold) {
        // add character to vocab
        this.indexTable[character] = characterIndex;
        this.characterTable[characterIndex] = character;
      }
    }
  }

  toIndexes(value, maxThreshold = 0) {
    let result = [];
    let indexTable = this.indexTable;

    for (let i = 0, max = value.length; i < max; i++) {
      let character = value[i];
      let index = indexTable[character];
      if (index === undefined) {
        throw new Error(`unrecognized character "${ character }"`);
      }
      if (index < maxThreshold) continue;
      result.push(index);
    }

    return result;
  }

  toIndexesInputOutput(value1, value2 = null, maxThreshold = 0) {
    let result;
    if (typeof value1 === 'string') {
      result = this.toIndexes(value1.split('').concat(['stop-input', 'start-output']), maxThreshold);
    } else {
      result = this.toIndexes(value1.concat(['stop-input', 'start-output']), maxThreshold);
    }

    if (value2 === null) return result;

    if (typeof value2 === 'string') {
      return result.concat(this.toIndexes(value2.split(''), maxThreshold));
    } else {
      return result.concat(this.toIndexes(value2, maxThreshold));
    }
  }

  toCharacters(indices, maxThreshold = 0) {
    let result = [];
    let characterTable = this.characterTable;

    for (let i = 0, max = indices.length; i < max; i++) {
      let index = indices[i];
      if (index < maxThreshold) continue;
      let character = characterTable[index];
      if (character === undefined) {
        throw new Error(`unrecognized index "${ index }"`);
      }
      result.push(character);
    }

    return result;
  }

  toString(indices, maxThreshold) {
    return this.toCharacters(indices, maxThreshold).join('');
  }

  static fromAllPrintable(maxThreshold, values = ['\n']) {
    for(let i = 32; i <= 126; i++) {
      values.push(String.fromCharCode(i));
    }
    return new Vocab(values, maxThreshold);
  }

  static fromAllPrintableInputOutput(maxThreshold, values = ['\n']) {
    const vocab = Vocab.fromAllPrintable(maxThreshold, values);
    vocab.addSpecial('stop-input');
    vocab.addSpecial('start-output');
    return vocab;
  }

  static fromStringInputOutput(string, maxThreshold) {
    const values = String.prototype.concat(...new Set(string));
    const vocab = new Vocab(values, maxThreshold);
    vocab.addSpecial('stop-input');
    vocab.addSpecial('start-output');
    return vocab;
  }

  static fromArrayInputOutput(array, maxThreshold) {
    const vocab = new Vocab(array.filter((v, i, a) => a.indexOf(v) === i).sort(), maxThreshold);
    vocab.addSpecial('stop-input');
    vocab.addSpecial('start-output');
    return vocab;
  }

  static fromString(string, maxThreshold) {
    const values = String.prototype.concat(...new Set(string));
    return new Vocab(values, maxThreshold);
  }

  static fromJSON(json) {
    const vocab = new Vocab();
    vocab.indexTable = json.indexTable;
    vocab.characterTable = json.characterTable;
    vocab.values = json.values;
    vocab.characters = json.characters;
    return vocab;
  }

  addSpecial(special) {
    let i = this.indexTable[special] = this.characters.length;
    this.characterTable[i] = special;
    this.characters.push(special);
  }

  toFunctionString(vocabVariableName) {
    return `
${ this.toIndexes.toString().replace('this', vocabVariableName) }
${ this.toIndexesInputOutput.toString().replace('this', vocabVariableName) }
${ this.toCharacters.toString().replace('this', vocabVariableName) }
`;
  }
}
<commit_msg>add addInputOutput method as reusable helper<commit_after>/**
 *
 * @param {String[]|Number[]} values
 * @param maxThreshold
 * @constructor
 */
export default class Vocab {
  constructor(values, maxThreshold = 0) {
    if (values === undefined) return;

    this.values = values;
    // go over all characters and keep track of all unique ones seen
    // count up all characters
    this.indexTable = {};
    this.characterTable = {};
    this.characters = [];
    this.buildCharactersFromIterable(values);
    this.buildTables(maxThreshold);
  }

  buildCharactersFromIterable(values) {
    let tempCharactersTable = {};
    for (let vocabIndex = 0, vocabLength = values.length; vocabIndex < vocabLength; vocabIndex++) {
      let characters = values[vocabIndex];

      if (characters.hasOwnProperty('length')) {
        for (let characterIndex = 0, charactersLength = characters.length; characterIndex < charactersLength; characterIndex++) {
          let character = characters[characterIndex];
          if (tempCharactersTable.hasOwnProperty(character)) continue;
          tempCharactersTable[character] = true;
          this.characters.push(character);
        }
      } else {
        let character = values[vocabIndex];
        if (tempCharactersTable.hasOwnProperty(character)) continue;
        tempCharactersTable[vocabIndex] = true;
        this.characters.push(character);
      }
    }
  }

  buildTables(maxThreshold) {
    // filter by count threshold and create pointers
    let charactersLength = this.characters.length;
    for(let characterIndex = 0; characterIndex < charactersLength; characterIndex++) {
      let character = this.characters[characterIndex];
      if(characterIndex >= maxThreshold) {
        // add character to vocab
        this.indexTable[character] = characterIndex;
        this.characterTable[characterIndex] = character;
      }
    }
  }

  toIndexes(value, maxThreshold = 0) {
    let result = [];
    let indexTable = this.indexTable;

    for (let i = 0, max = value.length; i < max; i++) {
      let character = value[i];
      let index = indexTable[character];
      if (index === undefined) {
        throw new Error(`unrecognized character "${ character }"`);
      }
      if (index < maxThreshold) continue;
      result.push(index);
    }

    return result;
  }

  toIndexesInputOutput(value1, value2 = null, maxThreshold = 0) {
    let result;
    if (typeof value1 === 'string') {
      result = this.toIndexes(value1.split('').concat(['stop-input', 'start-output']), maxThreshold);
    } else {
      result = this.toIndexes(value1.concat(['stop-input', 'start-output']), maxThreshold);
    }

    if (value2 === null) return result;

    if (typeof value2 === 'string') {
      return result.concat(this.toIndexes(value2.split(''), maxThreshold));
    } else {
      return result.concat(this.toIndexes(value2, maxThreshold));
    }
  }

  toCharacters(indices, maxThreshold = 0) {
    let result = [];
    let characterTable = this.characterTable;

    for (let i = 0, max = indices.length; i < max; i++) {
      let index = indices[i];
      if (index < maxThreshold) continue;
      let character = characterTable[index];
      if (character === undefined) {
        throw new Error(`unrecognized index "${ index }"`);
      }
      result.push(character);
    }

    return result;
  }

  toString(indices, maxThreshold) {
    return this.toCharacters(indices, maxThreshold).join('');
  }

  addInputOutput() {
    this.addSpecial('stop-input');
    this.addSpecial('start-output');
  }

  static fromAllPrintable(maxThreshold, values = ['\n']) {
    for(let i = 32; i <= 126; i++) {
      values.push(String.fromCharCode(i));
    }
    return new Vocab(values, maxThreshold);
  }

  static fromAllPrintableInputOutput(maxThreshold, values = ['\n']) {
    const vocab = Vocab.fromAllPrintable(maxThreshold, values);
    vocab.addInputOutput();
    return vocab;
  }

  static fromStringInputOutput(string, maxThreshold) {
    const values = String.prototype.concat(...new Set(string));
    const vocab = new Vocab(values, maxThreshold);
    vocab.addInputOutput();
    return vocab;
  }

  static fromArrayInputOutput(array, maxThreshold) {
    const vocab = new Vocab(array.filter((v, i, a) => a.indexOf(v) === i).sort(), maxThreshold);
    vocab.addInputOutput();
    return vocab;
  }

  static fromString(string, maxThreshold) {
    const values = String.prototype.concat(...new Set(string));
    return new Vocab(values, maxThreshold);
  }

  static fromJSON(json) {
    const vocab = new Vocab();
    vocab.indexTable = json.indexTable;
    vocab.characterTable = json.characterTable;
    vocab.values = json.values;
    vocab.characters = json.characters;
    return vocab;
  }

  addSpecial() {
    for (let i = 0; i < arguments.length; i++) {
      const special = arguments[i];
      let specialIndex = this.indexTable[special] = this.characters.length;
      this.characterTable[specialIndex] = special;
      this.characters.push(special);
    }
  }

  toFunctionString(vocabVariableName) {
    return `
${ this.toIndexes.toString().replace('this', vocabVariableName) }
${ this.toIndexesInputOutput.toString().replace('this', vocabVariableName) }
${ this.toCharacters.toString().replace('this', vocabVariableName) }
`;
  }
}
<|endoftext|>


<commit_before>const ModeInterface = require('./mode_interface');

module.exports = function(modeObject) {
  const modeObjectKeys = Object.keys(modeObject);

  return function(ctx, startOpts = {}) {
    let state = {};

    const mode = modeObjectKeys.reduce((m, k) => {
      m[k] = modeObject[k];
      return m;
    }, new ModeInterface(ctx));

    function wrapper(eh) {
      return function(e) {
        mode[eh](state, e);
      };
    }

    return {
      start: function() {
        state = mode.onSetup(startOpts); // this should set ui buttons
        this.on('drag', () => true, wrapper('onDrag'));
        this.on('click', () => true, wrapper('onClick'));
        this.on('mousemove', () => true, wrapper('onMouseMove'));
        this.on('mousedown', () => true, wrapper('onMouseDown'));
        this.on('mouseup', () => true, wrapper('onMouseUp'));
        this.on('mouseout', () => true, wrapper('onMouseOut'));
        this.on('keyup', () => true, wrapper('onKeyUp'));
        this.on('keydown', () => true, wrapper('onKeyDown'));
        this.on('touchstart', () => true, wrapper('onTouchStart'));
        this.on('touchmove', () => true, wrapper('onTouchMove'));
        this.on('touchend', () => true, wrapper('onTouchEnd'));
        this.on('tap', () => true, wrapper('onTap'));
      },
      stop: function() {
        mode.onStop(state);
      },
      trash: function() {
        mode.onTrash(state);
      },
      combineFeatures: function() {
        mode.onCombineFeatures(state);
      },
      uncombineFeatures: function() {
        mode.onUncombineFeatures(state);
      },
      render: function(geojson, push) {
        mode.toDisplayFeatures(state, geojson, push);
      }
    };
  };
};
<commit_msg>don't run render on unused event handlers (#783)<commit_after>const ModeInterface = require('./mode_interface');

const eventMapper = {
  drag: 'onDrag',
  click: 'onClick',
  mousemove: 'onMouseMove',
  mousedown: 'onMouseDown',
  mouseup: 'onMouseUp',
  mouseout: 'onMouseOut',
  keyup: 'onKeyUp',
  keydown: 'onKeyDown',
  touchstart: 'onTouchStart',
  touchmove: 'onTouchMove',
  touchend: 'onTouchEnd',
  tap: 'onTap'
};

const eventKeys = Object.keys(eventMapper);

module.exports = function(modeObject) {
  const modeObjectKeys = Object.keys(modeObject);

  return function(ctx, startOpts = {}) {
    let state = {};

    const mode = modeObjectKeys.reduce((m, k) => {
      m[k] = modeObject[k];
      return m;
    }, new ModeInterface(ctx));

    function wrapper(eh) {
      return function(e) {
        mode[eh](state, e);
      };
    }

    return {
      start: function() {
        state = mode.onSetup(startOpts); // this should set ui buttons

        // Adds event handlers for all event options
        // add sets the selector to false for all
        // handlers that are not present in the mode
        // to reduce on render calls for functions that
        // have no logic
        eventKeys.forEach(key => {
          const modeHandler = eventMapper[key];
          let selector = () => false;
          if (modeObject[modeHandler]) {
            selector = () => true;
          }
          this.on(key, selector, wrapper(modeHandler));
        });

      },
      stop: function() {
        mode.onStop(state);
      },
      trash: function() {
        mode.onTrash(state);
      },
      combineFeatures: function() {
        mode.onCombineFeatures(state);
      },
      uncombineFeatures: function() {
        mode.onUncombineFeatures(state);
      },
      render: function(geojson, push) {
        mode.toDisplayFeatures(state, geojson, push);
      }
    };
  };
};
<|endoftext|>


<commit_before>'use strict'

const CID = require('cids')

module.exports = function (cid) {
  if (Buffer.isBuffer(cid)) {
    return new CID(cid).toString()
  }
  if (CID.isCID(cid)) {
    return cid.toString()
  }
  if (typeof cid !== 'string') {
    throw new Error('unexpected cid type: ' + typeof cid)
  }
  new CID(cid.split('/')[0]) // eslint-disable-line
  return cid
}
<commit_msg>fix: disable just the rule we're breaking<commit_after>'use strict'

const CID = require('cids')

module.exports = function (cid) {
  if (Buffer.isBuffer(cid)) {
    return new CID(cid).toString()
  }
  if (CID.isCID(cid)) {
    return cid.toString()
  }
  if (typeof cid !== 'string') {
    throw new Error('unexpected cid type: ' + typeof cid)
  }
  new CID(cid.split('/')[0]) // eslint-disable-line no-new
  return cid
}
<|endoftext|>


<commit_before>import { HEX_REGEX } from './constants';
import { rgbToHsv, rgbToRgbString } from './rgb';

/* eslint-disable-next-line import/prefer-default-export */
export function hexStringToRgb(hex) {
    const components = hex.match(HEX_REGEX);
    const a = parseInt(components[1].substring(6, 8), 16) / 255;

    return {
        r: parseInt(components[1].substring(0, 2), 16),
        g: parseInt(components[1].substring(2, 4), 16),
        b: parseInt(components[1].substring(4, 6), 16),
        a: typeof a === 'number' && !isNaN(a) ? a : 1, /* eslint-disable-line no-restricted-globals */
    };
}

export function hexStringToHsv(hex) {
    return rgbToHsv(hexStringToRgb(hex));
}

export function hexStringToRgbString(hex) {
    return rgbToRgbString(hexStringToRgb(hex));
}
<commit_msg>:sparkles: Add transparency to hexStringToRgbString<commit_after>import { HEX_REGEX } from './constants';
import { rgbToHsv, rgbToRgbString } from './rgb';

/* eslint-disable-next-line import/prefer-default-export */
export function hexStringToRgb(hex) {
    const components = hex.match(HEX_REGEX);
    const a = parseInt(components[1].substring(6, 8), 16) / 255;

    return {
        r: parseInt(components[1].substring(0, 2), 16),
        g: parseInt(components[1].substring(2, 4), 16),
        b: parseInt(components[1].substring(4, 6), 16),
        a: typeof a === 'number' && !isNaN(a) ? a : 1, /* eslint-disable-line no-restricted-globals */
    };
}

export function hexStringToHsv(hex) {
    return rgbToHsv(hexStringToRgb(hex));
}

export function hexStringToRgbString(hex, transparency = false) {
    return rgbToRgbString(hexStringToRgb(hex), transparency);
}
<|endoftext|>


<commit_before>const { MOVE, ROTATE } = require('./types')
const pathfinder = require('./pathfinder')

module.exports = {
  namespace: 'robot',
  globals: {
    pathfinder
  },
  actions: {
    move: (direction) => ['game:movable.move', { direction: MOVE[direction] }],
    rotate: (direction) => ['game:movable.rotate', { direction: ROTATE[direction] }],
    placeMarker: () => ['game:spawner.spawn'],
    collectResource: () => ['game:collector.collectResource']
  },
  functions: {
    moveTo: function (xPos, yPos) {
      const entityPos = this.getPosition()
      const path = pathfinder.getMovementCommands({ x: entityPos.x, y: entityPos.y }, { x: xPos, y: yPos })

      for (let i = 0; i < path.length; i++) {
        this.move(path[i])
      }
    }
  },
  sensors: {
    getPosition: (state, game) => state.position
  }
}
<commit_msg>rebased on develpp<commit_after>const { MOVE, ROTATE } = require('./types')
const pathfinder = require('./pathfinder')

module.exports = {
  namespace: 'robot',
  globals: {
    pathfinder
  },
  actions: {
    move: (direction) => ['game:movable.move', { direction: MOVE[direction] }],
    rotate: (direction) => ['game:movable.rotate', { direction: ROTATE[direction] }],
    setRotation: (direction) => ['game:movable.setRotation', { direction: ROTATE[direction] }],
    placeMarker: () => ['game:spawner.spawn'],
    collectResource: () => ['game:collector.collectResource']
  },
  functions: {
    moveTo: function (xPos, yPos) {
      var entityPos = this.getPosition()
      var path = pathfinder.getMovementCommands(
        { x: entityPos.x, y: entityPos.y },
        { x: xPos, y: yPos },
        entityPos.rotation)

      for (var i = 0; i < path.length; i++) {
        var command = path[i]

        if (command.move) {
          this.move(command.move)
        }

        if (command.setRotate) {
          this.setRotation(command.setRotate)
        }
      }
    }
  },
  sensors: {
    getPosition: (state, game) => state.position
  }
}
<|endoftext|>