<commit_before>/**
 * (c) 2016 Tieto Finland Oy
 * Licensed under the MIT license.
 */
'use strict';

/**
 * @ngdoc function
 * @name dashboard.controller:signitemCtrl
 * @description
 * # signitemCtrl
 * Controller of the dashboard
 */
angular.module('dashboard')
    .controller('signitemCtrl', function($log, $scope, $state, $stateParams, SigningAttApi, $sce, $timeout, $uibModal, ENV, SigningOpenApi, SigningPersonInfoApi, CONST, $rootScope, SigningDocSignaturesApi) {
        $log.debug("signitemCtrl.config");

        var self = this;
        self.item = $stateParams.signItem;
        if (!self.item || !self.item.ProcessGuid || !self.item.ProcessGuid.length) {
            $log.error("signitemCtrl: item missing");
            $state.go(CONST.APPSTATE.HOME);
            return;
        } else {
            $log.debug("signItemCtrl: name: " + self.item.Name);
        }

        self.blob = null;
        self.displayUrl = {};
        self.fileUrl = {};
        self.fileName = {};
        self.remoteUrl = null;
        self.docUrl = {};
        self.hideEmbObj = false; // Workaround for IE which displays embedded object always topmost.
        self.ongoing = false;
        self.alerts = [];
        self.isMobile = $rootScope.isMobile;
        // self.attModel = ListData.signingAttachmentList('STR_ATTACHMENTS', self.item.AttachmentInfos);
        self.btnModel = {
            doc: { id: 'doc', disabled: false, active: false, hide: false },
            acc: { id: 'acc', disabled: false, active: false },
            rej: { id: 'rej', disabled: false, active: false },
            sta: { id: 'sta', disabled: false, active: false },
            com: { id: 'com', disabled: false, active: false },
            att: { id: 'att', disabled: false, active: false, count: self.item.AttachmentInfos ? self.item.AttachmentInfos.length : 0 }
        };
        self.displayStatus = true;
        self.requestorName = self.item.RequestorName ? self.item.RequestorName : null;
        self.requestorId = self.item.RequestorId ? self.item.RequestorId : null;
        self.fileName = self.item.Name;
        self.docSignings = null;

        // PRIVATE FUNCTIONS

        function setBtnActive(id) {
            if (typeof id !== 'string' && id.length <= 0) {
                $log.error("signingItemCtrl.setBtnActive: bad args");
                return;
            }

            for (var i in self.btnModel) {
                self.btnModel[i].active = id === i ? true : false;
                // $log.debug("btn: " + self.btnModel[i].id + " active: " + self.btnModel[i].active);
            }
        }

        function initBtns(btnModel, status) {
            if (status !== CONST.ESIGNSTATUS.UNSIGNED.value) {
                btnModel.acc.disabled = true;
                btnModel.rej.disabled = true;
            }
            if (!self.isMobile) {
                setBtnActive(self.btnModel.doc.id); // On desktop document is displayed by default
            }
        }

        function clearAlerts() {
            self.alerts.length = 0;
        }

        function setDisplayUrl(url) {
            $log.debug("signitemCtrl.setDisplayUrl: " + url);
            self.displayUrl = url;
            setBtnActive(self.btnModel.doc.id);
        }

        function drawBlob(blob, delayExpired) {
            if (blob && !self.blob) {
                self.blob = blob;
            }

            if (delayExpired) {
                self.fileDrawDelayExpired = delayExpired;
            }

            if (self.blob && self.fileDrawDelayExpired) {
                setDisplayUrl(URL.createObjectURL(self.blob));
                //self.fileContent = $sce.trustAsResourceUrl(self.displayUrl);
                $log.debug("signitemCtrl.drawBlob: set fileUrl: " + self.displayUrl);
            }
        }

        function fetchBlob(item) {
            $log.debug("signitemCtrl.fetchBlob: SigningAttApi.getPdfBlob guid=" + item.ProcessGuid);

            SigningAttApi.getPdfBlob({ reqId: item.ProcessGuid }).$promise
                .then(
                function(response) {
                    var blob = new Blob([(response.pdfBlob)], { type: 'application/pdf' });
                    drawBlob(blob, false);
                },
                function(err) {
                    $log.error("signitemCtrl.fetchBlob: SigningAttApi.getPdfBlob " + JSON.stringify(err));
                    self.errCode = err.status;
                })
                .finally(function() {
                });
        }

        function fetchUrl(item) {
            self.docUrl = ENV.SignApiUrl_GetAttachment.replace(":reqId", item.ProcessGuid);
            $log.debug("signitemCtrl.fetchUrl: " + self.docUrl);
        }

        function saveStatus(item, status) {
            if (!item || !(item instanceof Object) || !("Status" in item)) {
                $log.debug(item);
                throw new Error("signitemCtrl.saveStatus: bad arguments");
            }
            $log.log("signitemCtrl.saveStatus: " + item.Name + ", current status: " + item.Status);
            clearAlerts();

            self.ongoing = true;
            self.displayStatus = false;
            var oldStatus = item.Status;
            item.Status = status; // This must be reverted if status change op fails
            self.responseOpen = SigningOpenApi.save(item, function(value) {
                $log.debug("adOpenSignreqs.saveStatus: SigningOpenApi.save done. New object: ");
                $log.debug(value);
                self.item = value;
            }, function(error) {
                $log.error("adOpenSignreqs.saveStatus: SigningOpenApi.save error: " + JSON.stringify(error));
                self.alerts.push({ type: 'danger', locId: 'STR_FAIL_OP', resCode: error.status, resTxt: error.statusText });
                item.Status = oldStatus;
            });
            self.responseOpen.$promise.finally(function() {
                $log.debug("adOpenSignreqs.saveStatus: SigningOpenApi.save finally");
                self.ongoing = null;
                self.displayStatus = true;
                initBtns(self.btnModel, self.item.Status);
            });
        }

        function displayRequestor(person) {
            if (person && "email" in person) {
                self.requestorEmail = person.email;
                self.alerts.push({ type: 'info', locId: 'STR_SIGNING_COMMENT_INFO', linkMailto: person.email });
            } else {
                $log.error("signItemCtrl.displayRequestor: bad args");
            }
        }

        function personInfo() {
            $log.debug("signitemCtrl.personInfo");

            if (!self.personInfo) {
                self.ongoing = true;
                self.personInfo = SigningPersonInfoApi.get({ userId: self.requestorId }, function(/*data*/) {
                    $log.debug("signitemCtrl.personInfo: api query done");
                    displayRequestor(self.personInfo);
                }, function(error) {
                    $log.error("signitemCtrl.personInfo: api query error: " + JSON.stringify(error));
                    self.alerts.push({ type: 'danger', locId: 'STR_FAIL_OP', resCode: error.status, resTxt: error.statusText });
                });
                self.personInfo.$promise.finally(function() {
                    self.ongoing = false;
                });
            } else {
                displayRequestor(self.personInfo);
            }
        }
        // rooli nimi tila aika dd.mm.yyy hh:mm, vanassa status myös värikoodilla
        function displaySignings(sgn) {
            if (!sgn || !("Signers" in sgn)) {
                $log.error("signItemCtrl.displaySignings: bad args");
                return;
            }
            $log.debug("signItemCtrl.displaySignings: " + sgn.Signers.length);
            if (!$rootScope.isMobile) {
                self.btnModel.doc.hide = true;
                setBtnActive(self.btnModel.sta.id);
                self.listMdl = sgn.Signers;
            }
            else {
                $state.go(CONST.APPSTATE.DOCSIGNERS, { 'signers': sgn.Signers });
            }
        }

        function docSignings(item) {
            $log.debug("signitemCtrl.docSignings");
            self.listMdl = null;
            if (!item || !("Guid" in item) || !item.Guid || self.ongoing) {
                $log.error("signItemCtrl.docSignings: bad args");
                return;
            }

            self.ongoing = true;
            self.docSignings = SigningDocSignaturesApi.get({ reqId: item.ProcessGuid }, function(/*data*/) {
                $log.debug("signitemCtrl.docSignings: api query done");
                displaySignings(self.docSignings);
            }, function(error) {
                $log.error("signitemCtrl.docSignings: api query error: " + JSON.stringify(error));
                self.alerts.push({ type: 'danger', locId: 'STR_FAIL_OP', resCode: error.status, resTxt: error.statusText });
            });
            self.docSignings.$promise.finally(function() {
                self.ongoing = false;
            });
        }
        // PUBLIC FUNCTIONS

        self.actionDoc = function() {
            if (self.isMobile) {
                self.openFileModal(self.displayUrl);
            } else {
                setDisplayUrl(self.docUrl);
            }
            self.btnModel.doc.hide = false;
            self.listMdl = null;
        };

        self.actionAttListCb = function() {
            $log.debug("signitemCtrl.actionAttListCb");
        };

        self.actionSign = function() {
            saveStatus(self.item, CONST.ESIGNSTATUS.SIGNED.value);
        };

        self.actionReject = function() {
            saveStatus(self.item, CONST.ESIGNSTATUS.REJECTED.value);
        };

        self.actionComment = function() {
            clearAlerts();
            personInfo();
        };

        self.actionSignings = function() {
            docSignings(self.item);
        };

        self.closeAlert = function(index) {
            $log.debug("signitemCtrl.closeAlert " + index);
            self.alerts.splice(index, 1);
        };

        self.openFileModal = function(fileUrl, fileBlob, fileHeading) {
            $log.debug("signitemCtrl.openFileModal: f: " + fileUrl + " b: " + fileBlob + " h: " + fileHeading);
            self.ongoing = true;
            var modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'views/modalfile.html',
                controller: 'modalFileCtrl',
                controllerAs: 'mfc',
                windowTopClass: 'db-large-modal',
                resolve: {
                    aUrl: function() {
                        return fileUrl;
                    },
                    aBlob: function() {
                        return fileBlob;
                    },
                    aHeading: function() {
                        return fileHeading;
                    }
                }
            });
            self.hideEmbObj = true;
            modalInstance.result.then(function(/* arg here passed from controller */) {
            }, function(arg) {
                $log.debug("signitemCtrl: Modal dismissed: " + arg);
                self.hideEmbObj = false;
                self.ongoing = false;
            });
        };

        self.isDisabled = function(id) {
            // $log.debug("signingItemCtrl.isDisabled: " + id);
            var res = false;
            if (self.ongoing) {
                res = true;
            }
            else {
                switch (id) {
                    case self.btnModel.att.id:
                        res = self.btnModel.att.disabled || !self.btnModel.att.count;
                        break;
                    default:
                        res = self.btnModel[id].disabled;
                        break;
                }
            }
            return res;
        };
        self.isActive = function(id) {
            //$log.debug("signingItemCtrl.isActive: " + id + "=" +self.btnModel[id].active);
            return !self.isMobile && self.btnModel[id].active;
        };

        /* Resolve css class for signing status */
        self.statusStyle = function(status) {
            var s = $rootScope.objWithVal(CONST.ESIGNSTATUS, 'value', status);
            return s ? s.badgeClass : 'label-default';
        };

        /* Resolve display text for item status */
        self.statusStrId = function(value) {
            var s = $rootScope.objWithVal(CONST.ESIGNSTATUS, 'value', value);
            return s ? s.stringId : '';
        };

        self.goHome = function() {
            self.ongoing = true;
            $rootScope.goHome();
        };

        initBtns(self.btnModel, self.item.Status);

        // Both blob and remote url implementations kept, but only one used.
        // Remove later when sure other one won't be needed.
        if (!ENV.app_useBlob) {
            fetchUrl(self.item);
            setDisplayUrl(self.docUrl);
        } else {
            fetchBlob(self.item);
            drawBlob();
        }
    });
<commit_msg>Esign: display signitem doc filename on mobile<commit_after>/**
 * (c) 2016 Tieto Finland Oy
 * Licensed under the MIT license.
 */
'use strict';

/**
 * @ngdoc function
 * @name dashboard.controller:signitemCtrl
 * @description
 * # signitemCtrl
 * Controller of the dashboard
 */
angular.module('dashboard')
    .controller('signitemCtrl', function($log, $scope, $state, $stateParams, SigningAttApi, $sce, $timeout, $uibModal, ENV, SigningOpenApi, SigningPersonInfoApi, CONST, $rootScope, SigningDocSignaturesApi) {
        $log.debug("signitemCtrl.config");

        var self = this;
        self.item = $stateParams.signItem;
        if (!self.item || !self.item.ProcessGuid || !self.item.ProcessGuid.length) {
            $log.error("signitemCtrl: item missing");
            $state.go(CONST.APPSTATE.HOME);
            return;
        } else {
            $log.debug("signItemCtrl: name: " + self.item.Name);
        }

        self.blob = null;
        self.displayUrl = {};
        self.fileUrl = {};
        self.fileName = {};
        self.remoteUrl = null;
        self.docUrl = {};
        self.hideEmbObj = false; // Workaround for IE which displays embedded object always topmost.
        self.ongoing = false;
        self.alerts = [];
        self.isMobile = $rootScope.isMobile;
        // self.attModel = ListData.signingAttachmentList('STR_ATTACHMENTS', self.item.AttachmentInfos);
        self.btnModel = {
            doc: { id: 'doc', disabled: false, active: false, hide: false },
            acc: { id: 'acc', disabled: false, active: false },
            rej: { id: 'rej', disabled: false, active: false },
            sta: { id: 'sta', disabled: false, active: false },
            com: { id: 'com', disabled: false, active: false },
            att: { id: 'att', disabled: false, active: false, count: self.item.AttachmentInfos ? self.item.AttachmentInfos.length : 0 }
        };
        self.displayStatus = true;
        self.requestorName = self.item.RequestorName ? self.item.RequestorName : null;
        self.requestorId = self.item.RequestorId ? self.item.RequestorId : null;
        self.fileName = self.item.Name;
        self.docSignings = null;

        // PRIVATE FUNCTIONS

        function setBtnActive(id) {
            if (typeof id !== 'string' && id.length <= 0) {
                $log.error("signingItemCtrl.setBtnActive: bad args");
                return;
            }

            for (var i in self.btnModel) {
                self.btnModel[i].active = id === i ? true : false;
                // $log.debug("btn: " + self.btnModel[i].id + " active: " + self.btnModel[i].active);
            }
        }

        function initBtns(btnModel, status) {
            if (status !== CONST.ESIGNSTATUS.UNSIGNED.value) {
                btnModel.acc.disabled = true;
                btnModel.rej.disabled = true;
            }
            if (!self.isMobile) {
                setBtnActive(self.btnModel.doc.id); // On desktop document is displayed by default
            }
        }

        function clearAlerts() {
            self.alerts.length = 0;
        }

        function setDisplayUrl(url) {
            $log.debug("signitemCtrl.setDisplayUrl: " + url);
            self.displayUrl = url;
            setBtnActive(self.btnModel.doc.id);
        }

        function drawBlob(blob, delayExpired) {
            if (blob && !self.blob) {
                self.blob = blob;
            }

            if (delayExpired) {
                self.fileDrawDelayExpired = delayExpired;
            }

            if (self.blob && self.fileDrawDelayExpired) {
                setDisplayUrl(URL.createObjectURL(self.blob));
                //self.fileContent = $sce.trustAsResourceUrl(self.displayUrl);
                $log.debug("signitemCtrl.drawBlob: set fileUrl: " + self.displayUrl);
            }
        }

        function fetchBlob(item) {
            $log.debug("signitemCtrl.fetchBlob: SigningAttApi.getPdfBlob guid=" + item.ProcessGuid);

            SigningAttApi.getPdfBlob({ reqId: item.ProcessGuid }).$promise
                .then(
                function(response) {
                    var blob = new Blob([(response.pdfBlob)], { type: 'application/pdf' });
                    drawBlob(blob, false);
                },
                function(err) {
                    $log.error("signitemCtrl.fetchBlob: SigningAttApi.getPdfBlob " + JSON.stringify(err));
                    self.errCode = err.status;
                })
                .finally(function() {
                });
        }

        function fetchUrl(item) {
            self.docUrl = ENV.SignApiUrl_GetAttachment.replace(":reqId", item.ProcessGuid);
            $log.debug("signitemCtrl.fetchUrl: " + self.docUrl);
        }

        function saveStatus(item, status) {
            if (!item || !(item instanceof Object) || !("Status" in item)) {
                $log.debug(item);
                throw new Error("signitemCtrl.saveStatus: bad arguments");
            }
            $log.log("signitemCtrl.saveStatus: " + item.Name + ", current status: " + item.Status);
            clearAlerts();

            self.ongoing = true;
            self.displayStatus = false;
            var oldStatus = item.Status;
            item.Status = status; // This must be reverted if status change op fails
            self.responseOpen = SigningOpenApi.save(item, function(value) {
                $log.debug("adOpenSignreqs.saveStatus: SigningOpenApi.save done. New object: ");
                $log.debug(value);
                self.item = value;
            }, function(error) {
                $log.error("adOpenSignreqs.saveStatus: SigningOpenApi.save error: " + JSON.stringify(error));
                self.alerts.push({ type: 'danger', locId: 'STR_FAIL_OP', resCode: error.status, resTxt: error.statusText });
                item.Status = oldStatus;
            });
            self.responseOpen.$promise.finally(function() {
                $log.debug("adOpenSignreqs.saveStatus: SigningOpenApi.save finally");
                self.ongoing = null;
                self.displayStatus = true;
                initBtns(self.btnModel, self.item.Status);
            });
        }

        function displayRequestor(person) {
            if (person && "email" in person) {
                self.requestorEmail = person.email;
                self.alerts.push({ type: 'info', locId: 'STR_SIGNING_COMMENT_INFO', linkMailto: person.email });
            } else {
                $log.error("signItemCtrl.displayRequestor: bad args");
            }
        }

        function personInfo() {
            $log.debug("signitemCtrl.personInfo");

            if (!self.personInfo) {
                self.ongoing = true;
                self.personInfo = SigningPersonInfoApi.get({ userId: self.requestorId }, function(/*data*/) {
                    $log.debug("signitemCtrl.personInfo: api query done");
                    displayRequestor(self.personInfo);
                }, function(error) {
                    $log.error("signitemCtrl.personInfo: api query error: " + JSON.stringify(error));
                    self.alerts.push({ type: 'danger', locId: 'STR_FAIL_OP', resCode: error.status, resTxt: error.statusText });
                });
                self.personInfo.$promise.finally(function() {
                    self.ongoing = false;
                });
            } else {
                displayRequestor(self.personInfo);
            }
        }
        // rooli nimi tila aika dd.mm.yyy hh:mm, vanassa status myös värikoodilla
        function displaySignings(sgn) {
            if (!sgn || !("Signers" in sgn)) {
                $log.error("signItemCtrl.displaySignings: bad args");
                return;
            }
            $log.debug("signItemCtrl.displaySignings: " + sgn.Signers.length);
            if (!$rootScope.isMobile) {
                self.btnModel.doc.hide = true;
                setBtnActive(self.btnModel.sta.id);
                self.listMdl = sgn.Signers;
            }
            else {
                $state.go(CONST.APPSTATE.DOCSIGNERS, { 'signers': sgn.Signers });
            }
        }

        function docSignings(item) {
            $log.debug("signitemCtrl.docSignings");
            self.listMdl = null;
            if (!item || !("Guid" in item) || !item.Guid || self.ongoing) {
                $log.error("signItemCtrl.docSignings: bad args");
                return;
            }

            self.ongoing = true;
            self.docSignings = SigningDocSignaturesApi.get({ reqId: item.ProcessGuid }, function(/*data*/) {
                $log.debug("signitemCtrl.docSignings: api query done");
                displaySignings(self.docSignings);
            }, function(error) {
                $log.error("signitemCtrl.docSignings: api query error: " + JSON.stringify(error));
                self.alerts.push({ type: 'danger', locId: 'STR_FAIL_OP', resCode: error.status, resTxt: error.statusText });
            });
            self.docSignings.$promise.finally(function() {
                self.ongoing = false;
            });
        }
        // PUBLIC FUNCTIONS

        self.actionDoc = function() {
            if (self.isMobile) {
                self.openFileModal(self.displayUrl, null, self.fileName);
            } else {
                setDisplayUrl(self.docUrl);
            }
            self.btnModel.doc.hide = false;
            self.listMdl = null;
        };

        self.actionAttListCb = function() {
            $log.debug("signitemCtrl.actionAttListCb");
        };

        self.actionSign = function() {
            saveStatus(self.item, CONST.ESIGNSTATUS.SIGNED.value);
        };

        self.actionReject = function() {
            saveStatus(self.item, CONST.ESIGNSTATUS.REJECTED.value);
        };

        self.actionComment = function() {
            clearAlerts();
            personInfo();
        };

        self.actionSignings = function() {
            docSignings(self.item);
        };

        self.closeAlert = function(index) {
            $log.debug("signitemCtrl.closeAlert " + index);
            self.alerts.splice(index, 1);
        };

        self.openFileModal = function(fileUrl, fileBlob, fileHeading) {
            $log.debug("signitemCtrl.openFileModal: f: " + fileUrl + " b: " + fileBlob + " h: " + fileHeading);
            self.ongoing = true;
            var modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'views/modalfile.html',
                controller: 'modalFileCtrl',
                controllerAs: 'mfc',
                windowTopClass: 'db-large-modal',
                resolve: {
                    aUrl: function() {
                        return fileUrl;
                    },
                    aBlob: function() {
                        return fileBlob;
                    },
                    aHeading: function() {
                        return fileHeading;
                    }
                }
            });
            self.hideEmbObj = true;
            modalInstance.result.then(function(/* arg here passed from controller */) {
            }, function(arg) {
                $log.debug("signitemCtrl: Modal dismissed: " + arg);
                self.hideEmbObj = false;
                self.ongoing = false;
            });
        };

        self.isDisabled = function(id) {
            // $log.debug("signingItemCtrl.isDisabled: " + id);
            var res = false;
            if (self.ongoing) {
                res = true;
            }
            else {
                switch (id) {
                    case self.btnModel.att.id:
                        res = self.btnModel.att.disabled || !self.btnModel.att.count;
                        break;
                    default:
                        res = self.btnModel[id].disabled;
                        break;
                }
            }
            return res;
        };
        self.isActive = function(id) {
            //$log.debug("signingItemCtrl.isActive: " + id + "=" +self.btnModel[id].active);
            return !self.isMobile && self.btnModel[id].active;
        };

        /* Resolve css class for signing status */
        self.statusStyle = function(status) {
            var s = $rootScope.objWithVal(CONST.ESIGNSTATUS, 'value', status);
            return s ? s.badgeClass : 'label-default';
        };

        /* Resolve display text for item status */
        self.statusStrId = function(value) {
            var s = $rootScope.objWithVal(CONST.ESIGNSTATUS, 'value', value);
            return s ? s.stringId : '';
        };

        self.goHome = function() {
            self.ongoing = true;
            $rootScope.goHome();
        };

        initBtns(self.btnModel, self.item.Status);

        // Both blob and remote url implementations kept, but only one used.
        // Remove later when sure other one won't be needed.
        if (!ENV.app_useBlob) {
            fetchUrl(self.item);
            setDisplayUrl(self.docUrl);
        } else {
            fetchBlob(self.item);
            drawBlob();
        }
    });
<|endoftext|>


<commit_before>'use strict';

app.directive ('ghRepos', function () {
    return {
        restrict: 'E' ,
        templateUrl: '../../views/partials/Repos.html' ,
        link: function (scope, element, attr) {
            scope.$on ('repos', function (event) {
                if (event.currentScope.repos) {
                    scope.repos = event.currentScope.repos;

                    $('.repo').fadeOut (1000, function () {
                        $('.repos').fadeIn ();
                    });
                }
                else {
                    $('.repos').fadeOut (1000, function () {
                        $('.repo').fadeIn ();
                    });
                }
            });
        }
    };
});<commit_msg>used element in the right way<commit_after>'use strict';

app.directive ('ghRepos', function () {
    return {
        restrict: 'E' ,
        templateUrl: '../../views/partials/Repos.html' ,
        link: function (scope, element, attr) {
            scope.$on ('repos', function (event) {
                if (event.currentScope.repos) {
                    scope.repos = event.currentScope.repos;

                    $('gh-repo').fadeOut (500, function () {
                        element.fadeIn ();
                    });
                }
                else {
                    element.fadeOut (500, function () {
                        $('.gh-repo').fadeIn ();
                    });
                }
            });
        }
    };
});<|endoftext|>


<commit_before>'use strict';

// var directives = directives || {};

directives.directive('buttonDropdown', ['$location', 'GeoData', function ($location, GeoData) {

    return {
      templateUrl: 'partials/buttondropdown.html',
      restrict: 'E',
      // scope: {
      //   //'GeoData': GeoData
      // },
      controller: directives.buttonDropdown,
      controllerAs: 'buttonDropdown',
      link: function postLink(scope, element, attrs) {
        scope.mapView = false;
        scope.hideDropDown = function () {
          element.find('.dropdown-menu').removeClass('show');
        };

        scope.loadArea = function (area, $event) {
          $event.preventDefault();
          $location.path('/' + area.type + '/' + area.identifier);
          scope.hideDropDown();
        };

        scope.loadMain = function() {
          $location.path('/');
        };

        //parenttype is optional.
        scope.openDropDown = function (type, level, isLeaf, $event, parentType) {
          $event.preventDefault();
          var $$target = $($event.target);
          var $$dropdown;

          $('.dropdown-menu a').removeClass('active');
          if(element.find('.dropdown-menu.' + type + '.' + level).hasClass('show')) {
            element.find('.dropdown-menu.' + level).removeClass('show flip');
          } else {
            element.find('.dropdown-menu.' + level).removeClass('show flip');
            if (parentType) {
              $$target.addClass('active');
              $$dropdown = element.find('.dropdown-menu.' + type + '.' + level + '.' + parentType);
              $$dropdown.toggleClass('show');
              if($$dropdown.width() + $$dropdown.offset().left > $(window).width()) {
                $$dropdown.toggleClass('flip');
              }
            } else {
              $$dropdown = element.find('.dropdown-menu.' + type + '.' + level);
              $$dropdown.toggleClass('show');
              if($$dropdown.width() + $$dropdown.offset().left > $(window).width()) {
                $$dropdown.toggleClass('flip');
              }
            }
          }
        };

        scope.showMap = function() {
          document.querySelector('#crashMap').classList.add('show');
          document.querySelector('#factors').classList.remove('show');
          // $('#crashMap').show();
          // $('#factors').hide();
          scope.mapView = !scope.mapView;
          var type = {type: 'city', year: new Date().getFullYear() };
          scope.$broadcast('loadMap', type);
        };

        scope.showFactors = function() {
          document.querySelector('#crashMap').classList.remove('show');
          document.querySelector('#factors').classList.add('show');
          scope.mapView = !scope.mapView;
        };
      }
    };
  }]);

directives.buttonDropdown = function (GeoData, $scope, $location) {
  // $scope.$watch('menuData', function (oldVal, newVal) {
  //   $scope.data = newVal;
  // });

  var getAllShapes = function () {
    GeoData('/all').then(function (data) {

      _.forEach(data, function (shape) {
        shape.name = getDisplayValue(shape.type, shape.identifier, false);
      });

      // $scope.shapes = data;

      $scope.data = buildMenu(data);
    });
  };

  var buildMenu = function (data) {
    var types = _.uniq(_.pluck(data, 'type'));
    var menuData = {};

    _.forEach(types, function (type) {
      menuData[type] = {
        'name': getDisplayValue(type, null, false),
        'children': null,
        'isLeaf': true,
        'type': type
      };

      var filteredVals = _.filter(data,  { 'type': type });

      // console.log(filteredVals);

      var boroughLevelData = {};

      _.forEach(filteredVals, function (val) {
        _.assign(val, {'isLeaf': true});

        if (val.type === 'community') {
          _.assign(val, {'borough': getDistrictBorough(parseInt(val.identifier, 10))});
        }
      });

      if (filteredVals[0].hasOwnProperty('borough') && filteredVals[0].type !== 'borough') {
        boroughLevelData = groupByBorough(filteredVals);
      }

      if (_.keys(boroughLevelData).length > 0) {
        menuData[type].children = boroughLevelData;
        menuData[type].isLeaf = false;
      } else {
        var sortedVals = _.sortBy(filteredVals, sortVals);
        menuData[type].children = sortedVals;
        menuData[type].isLeaf = false;
      }
    });
    // console.log('menuData : ', menuData);
    return menuData;
  };

  var getDistrictBorough = function (districtId) {
    if (districtId > 500) {
      return 'Staten Island';
    } else if (districtId > 400) {
      return 'Queens';
    } else if (districtId > 300) {
      return 'Brooklyn';
    } else if (districtId > 200) {
      return 'Bronx';
    } else if (districtId > 100) {
      return 'Manhattan';
    } else {
      return '';
    }
  };

  var groupByBorough = function (data) {
    var boroughs = _.uniq(_.pluck(data, 'borough'));
    var boroughData = {};

    _.forEach(boroughs, function (borough) {
      boroughData[borough] = {
        'name': borough,
        'children': null,
        'isLeaf': false,
        'type': borough.toLowerCase().replace(' ', '')
      };

      var filteredVals = _.filter(data,  { 'borough': borough });

      _.forEach(filteredVals, function (val) {
        _.assign(val, {'isLeaf': true});
      });

      var sortedVals = _.sortBy(filteredVals, sortVals);

      boroughData[borough].children = sortedVals;

    });

    return boroughData;
  };

  var sortVals = function (val) {
    if (isNaN(parseInt(val.identifier, 10))) {
      return val.identifier;
    } else {
      return parseInt(val.identifier, 10);
    }
  };

  var translateCommunityBoardDistrict = function (districtId) {
    if (districtId > 500) {
      return 'Staten Island Community Board ' + (districtId - 500);
    } else if (districtId > 400) {
      return 'Queens Community Board ' + (districtId - 400);
    } else if (districtId > 300) {
      return 'Brooklyn Community Board ' + (districtId - 300);
    } else if (districtId > 200) {
      return 'Bronx Community Board ' + (districtId - 200);
    } else if (districtId > 100) {
      return 'Manhattan Community Board ' + (districtId - 100);
    } else {
      return '';
    }
  };

  var addOrdinal = function (i) {
    var j = i % 10;
    if (j === 1 && i !== 11) {
      return i + 'st';
    }
    if (j === 2 && i !== 12) {
      return i + 'nd';
    }
    if (j === 3 && i !== 13) {
      return i + 'rd';
    }
    return i + 'th';
  };

  var communityBoardDisplay = function (id) {
    return translateCommunityBoardDistrict(parseInt(id, 10));
  };

  var precinctDisplay = function (id) {
    var precinct = parseInt(id, 10);
    if(precinct === 14) { return 'Midtown South Police Precinct'; }
    if(precinct === 18) { return 'Midtown North Police Precinct'; }
    if(precinct === 22) { return 'Central Park Police Precinct'; }
    return addOrdinal(precinct) + ' Police Precinct';
  };

  var getMenuName = function (type) {
    switch (type) {
      case 'citycouncil':
        return 'City Council';
      case 'community':
        return 'Community Board';
      case 'zipcode':
        return 'Zip Code';
      case 'precinct':
        return 'Police Precinct';
      case 'neighborhood':
        return 'Neighborhood';
      case 'borough':
        return 'Borough';
    }
  };

  var getDisplayValue = function (type, value, isTitle) {
    if(!value) {
      return getMenuName(type);
    }

    switch (type) {
      case 'zipcode':
        return (isTitle) ? ' in zip code ' + value + '.' : 'Zip Code ' + value;
      case 'neighborhood':
        return (isTitle) ? ' in ' + value + '.' : value;
      case 'citycouncil':
        return (isTitle) ? ' in city council district ' + value + '.' : 'City Council District ' + value;
      case 'community':
        return (isTitle) ? ' in ' + communityBoardDisplay(value) + '.' : communityBoardDisplay(value);
      case 'borough':
        return (isTitle) ? ' in ' + value + '.' : value + '';
      case 'precinct':
        return (isTitle) ? ' in the ' + precinctDisplay(value) + '.' : precinctDisplay(value) + '';
      default:
        return 'City Wide';
    }
  };

  var getTitle = function (path, isGraphTitle) {
    if(path === '/') { return 'City Wide'; }

    var parts = path.split('/');
    var type = parts[1];
    var value = parts[2];

    return getDisplayValue(type, value, isGraphTitle);
  };

  getAllShapes();
  $scope.title = getTitle($location.$$path, false);
};
<commit_msg>dependency injection<commit_after>'use strict';

// var directives = directives || {};

directives.directive('buttonDropdown', ['$location', 'GeoData', function ($location, GeoData) {

    return {
      templateUrl: 'partials/buttondropdown.html',
      restrict: 'E',
      // scope: {
      //   //'GeoData': GeoData
      // },
      controller: directives.buttonDropdown,
      controllerAs: 'buttonDropdown',
      link: function postLink(scope, element, attrs) {
        scope.mapView = false;
        scope.hideDropDown = function () {
          element.find('.dropdown-menu').removeClass('show');
        };

        scope.loadArea = function (area, $event) {
          $event.preventDefault();
          $location.path('/' + area.type + '/' + area.identifier);
          scope.hideDropDown();
        };

        scope.loadMain = function() {
          $location.path('/');
        };

        //parenttype is optional.
        scope.openDropDown = function (type, level, isLeaf, $event, parentType) {
          $event.preventDefault();
          var $$target = $($event.target);
          var $$dropdown;

          $('.dropdown-menu a').removeClass('active');
          if(element.find('.dropdown-menu.' + type + '.' + level).hasClass('show')) {
            element.find('.dropdown-menu.' + level).removeClass('show flip');
          } else {
            element.find('.dropdown-menu.' + level).removeClass('show flip');
            if (parentType) {
              $$target.addClass('active');
              $$dropdown = element.find('.dropdown-menu.' + type + '.' + level + '.' + parentType);
              $$dropdown.toggleClass('show');
              if($$dropdown.width() + $$dropdown.offset().left > $(window).width()) {
                $$dropdown.toggleClass('flip');
              }
            } else {
              $$dropdown = element.find('.dropdown-menu.' + type + '.' + level);
              $$dropdown.toggleClass('show');
              if($$dropdown.width() + $$dropdown.offset().left > $(window).width()) {
                $$dropdown.toggleClass('flip');
              }
            }
          }
        };

        scope.showMap = function() {
          document.querySelector('#crashMap').classList.add('show');
          document.querySelector('#factors').classList.remove('show');
          // $('#crashMap').show();
          // $('#factors').hide();
          scope.mapView = !scope.mapView;
          var type = {type: 'city', year: new Date().getFullYear() };
          scope.$broadcast('loadMap', type);
        };

        scope.showFactors = function() {
          document.querySelector('#crashMap').classList.remove('show');
          document.querySelector('#factors').classList.add('show');
          scope.mapView = !scope.mapView;
        };
      }
    };
  }]);

directives.buttonDropdown = function (GeoData, $scope, $location) {
  // $scope.$watch('menuData', function (oldVal, newVal) {
  //   $scope.data = newVal;
  // });

  var getAllShapes = function () {
    GeoData('/all').then(function (data) {

      _.forEach(data, function (shape) {
        shape.name = getDisplayValue(shape.type, shape.identifier, false);
      });

      // $scope.shapes = data;

      $scope.data = buildMenu(data);
    });
  };

  var buildMenu = function (data) {
    var types = _.uniq(_.pluck(data, 'type'));
    var menuData = {};

    _.forEach(types, function (type) {
      menuData[type] = {
        'name': getDisplayValue(type, null, false),
        'children': null,
        'isLeaf': true,
        'type': type
      };

      var filteredVals = _.filter(data,  { 'type': type });

      // console.log(filteredVals);

      var boroughLevelData = {};

      _.forEach(filteredVals, function (val) {
        _.assign(val, {'isLeaf': true});

        if (val.type === 'community') {
          _.assign(val, {'borough': getDistrictBorough(parseInt(val.identifier, 10))});
        }
      });

      if (filteredVals[0].hasOwnProperty('borough') && filteredVals[0].type !== 'borough') {
        boroughLevelData = groupByBorough(filteredVals);
      }

      if (_.keys(boroughLevelData).length > 0) {
        menuData[type].children = boroughLevelData;
        menuData[type].isLeaf = false;
      } else {
        var sortedVals = _.sortBy(filteredVals, sortVals);
        menuData[type].children = sortedVals;
        menuData[type].isLeaf = false;
      }
    });
    // console.log('menuData : ', menuData);
    return menuData;
  };

  var getDistrictBorough = function (districtId) {
    if (districtId > 500) {
      return 'Staten Island';
    } else if (districtId > 400) {
      return 'Queens';
    } else if (districtId > 300) {
      return 'Brooklyn';
    } else if (districtId > 200) {
      return 'Bronx';
    } else if (districtId > 100) {
      return 'Manhattan';
    } else {
      return '';
    }
  };

  var groupByBorough = function (data) {
    var boroughs = _.uniq(_.pluck(data, 'borough'));
    var boroughData = {};

    _.forEach(boroughs, function (borough) {
      boroughData[borough] = {
        'name': borough,
        'children': null,
        'isLeaf': false,
        'type': borough.toLowerCase().replace(' ', '')
      };

      var filteredVals = _.filter(data,  { 'borough': borough });

      _.forEach(filteredVals, function (val) {
        _.assign(val, {'isLeaf': true});
      });

      var sortedVals = _.sortBy(filteredVals, sortVals);

      boroughData[borough].children = sortedVals;

    });

    return boroughData;
  };

  var sortVals = function (val) {
    if (isNaN(parseInt(val.identifier, 10))) {
      return val.identifier;
    } else {
      return parseInt(val.identifier, 10);
    }
  };

  var translateCommunityBoardDistrict = function (districtId) {
    if (districtId > 500) {
      return 'Staten Island Community Board ' + (districtId - 500);
    } else if (districtId > 400) {
      return 'Queens Community Board ' + (districtId - 400);
    } else if (districtId > 300) {
      return 'Brooklyn Community Board ' + (districtId - 300);
    } else if (districtId > 200) {
      return 'Bronx Community Board ' + (districtId - 200);
    } else if (districtId > 100) {
      return 'Manhattan Community Board ' + (districtId - 100);
    } else {
      return '';
    }
  };

  var addOrdinal = function (i) {
    var j = i % 10;
    if (j === 1 && i !== 11) {
      return i + 'st';
    }
    if (j === 2 && i !== 12) {
      return i + 'nd';
    }
    if (j === 3 && i !== 13) {
      return i + 'rd';
    }
    return i + 'th';
  };

  var communityBoardDisplay = function (id) {
    return translateCommunityBoardDistrict(parseInt(id, 10));
  };

  var precinctDisplay = function (id) {
    var precinct = parseInt(id, 10);
    if(precinct === 14) { return 'Midtown South Police Precinct'; }
    if(precinct === 18) { return 'Midtown North Police Precinct'; }
    if(precinct === 22) { return 'Central Park Police Precinct'; }
    return addOrdinal(precinct) + ' Police Precinct';
  };

  var getMenuName = function (type) {
    switch (type) {
      case 'citycouncil':
        return 'City Council';
      case 'community':
        return 'Community Board';
      case 'zipcode':
        return 'Zip Code';
      case 'precinct':
        return 'Police Precinct';
      case 'neighborhood':
        return 'Neighborhood';
      case 'borough':
        return 'Borough';
    }
  };

  var getDisplayValue = function (type, value, isTitle) {
    if(!value) {
      return getMenuName(type);
    }

    switch (type) {
      case 'zipcode':
        return (isTitle) ? ' in zip code ' + value + '.' : 'Zip Code ' + value;
      case 'neighborhood':
        return (isTitle) ? ' in ' + value + '.' : value;
      case 'citycouncil':
        return (isTitle) ? ' in city council district ' + value + '.' : 'City Council District ' + value;
      case 'community':
        return (isTitle) ? ' in ' + communityBoardDisplay(value) + '.' : communityBoardDisplay(value);
      case 'borough':
        return (isTitle) ? ' in ' + value + '.' : value + '';
      case 'precinct':
        return (isTitle) ? ' in the ' + precinctDisplay(value) + '.' : precinctDisplay(value) + '';
      default:
        return 'City Wide';
    }
  };

  var getTitle = function (path, isGraphTitle) {
    if(path === '/') { return 'City Wide'; }

    var parts = path.split('/');
    var type = parts[1];
    var value = parts[2];

    return getDisplayValue(type, value, isGraphTitle);
  };

  getAllShapes();
  $scope.title = getTitle($location.$$path, false);
};

directives.buttonDropdown.$inject = ['GeoData', '$scope', '$location'];
<|endoftext|>


<commit_before>/* jshint maxlen:false */
define([
    'dojo/has',
    'dojo/request/xhr',

    'esri/config'
], function (
    has,
    xhr,

    esriConfig
) {
    // force api to use CORS on mapserv thus removing the test request on app load
    // e.g. http://mapserv.utah.gov/ArcGIS/rest/info?f=json
    esriConfig.request.corsEnabledServers.push('mapserv.utah.gov');
    esriConfig.request.corsEnabledServers.push('basemaps.utah.gov');
    esriConfig.request.corsEnabledServers.push('api.mapserv.utah.gov');
    esriConfig.request.corsEnabledServers.push('discover.agrc.utah.gov');
    esriConfig.request.corsEnabledServers.push('gis.trustlands.utah.gov');

    const config = {
        // app: app.App
        //      global reference to App
        app: null,

        // version.: String
        //      The version number.
        version: '3.2.1',

        // apiKey: String
        //      The api key used for services on api.mapserv.utah.gov
        // acquire at developer.mapserv.utah.gov
        apiKey: '',

        // wkt26912: String
        //      The well known text for utm zone 12 nad83 for use with proj4
        /* eslint-disable max-len */
        wkt26912: 'PROJCS["NAD83 / UTM zone 12N",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-111],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],AUTHORITY["EPSG","26912"],AXIS["Easting",EAST],AXIS["Northing",NORTH]]',

        // wkt4326: String
        //      The well known text for wgs 84 (lat/long) for use with proj4
        wkt4326: 'GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]]',

        // wkt3857: String
        //      The well known text for wgs 84 for use with proj4
        wkt3857: 'PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Mercator_Auxiliary_Sphere"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",0.0],PARAMETER["Auxiliary_Sphere_Type",0.0],UNIT["Meter",1.0]]',
        /* eslint-enable max-len */

        urls: {
            search: 'https://api.mapserv.utah.gov/api/v1/search/{0}/{1}',
            reverseGeocode: 'https://api.mapserv.utah.gov/api/v1/geocode/reverse/{0}/{1}',
            landown: 'https://gis.trustlands.utah.gov/server/' +
                     '/rest/services/Ownership/UT_SITLA_Ownership_LandOwnership_WM/FeatureServer/0',
            exportWebMap: 'https://mapserv.utah.gov/arcgis/rest/services/Utilities/' +
                          'PrintingTools/GPServer/Export%20Web%20Map%20Task'
        },

        fieldNames: {
            // counties & municipalities
            NAME: 'NAME',
            // state
            STATE_LGD: 'STATE_LGD',
            GRID1Mil: 'GRID1Mil',
            GRIS100K: 'GRID100K',
            FEET: 'feet',
            METERS: 'value',
            ZIP5: 'ZIP5'
        },

        featureClassNames: {
            counties: 'SGID10.BOUNDARIES.Counties',
            municipalities: 'SGID10.BOUNDARIES.Municipalities',
            landOwnership: 'SGID10.CADASTRE.LandOwnership',
            nationalGrid: 'SGID10.INDICES.NationalGrid',
            dem: 'SGID10.RASTER.USGS_DEM_10METER',
            gnis: 'SGID10.LOCATION.PlaceNamesGNIS2010',
            zip: 'SGID10.BOUNDARIES.ZipCodes'
        }
    };

    if (has('agrc-build') === 'prod') {
        // atlas.utah.gov
        config.apiKey = 'AGRC-A94B063C533889';
        config.quadWord = 'career-exhibit-panel-stadium';
    } else if (has('agrc-build') === 'stage') {
        // test.mapserv.utah.gov
        config.quadWord = 'opera-event-little-pinball';
        config.apiKey = 'AGRC-AC122FA9671436';
    } else {
        // localhost
        xhr(require.baseUrl + 'secrets.json', {
            handleAs: 'json',
            sync: true
        }).then(function (secrets) {
            config.quadWord = secrets.quadWord;
            config.apiKey = secrets.apiKey;
        }, function () {
            throw 'Error getting secrets!';
        });
    }

    return config;
});
<commit_msg>switch to serverless-print-proxy<commit_after>/* jshint maxlen:false */
define([
    'dojo/has',
    'dojo/request/xhr',

    'esri/config'
], function (
    has,
    xhr,

    esriConfig
) {
    // force api to use CORS on mapserv thus removing the test request on app load
    // e.g. http://mapserv.utah.gov/ArcGIS/rest/info?f=json
    esriConfig.request.corsEnabledServers.push('mapserv.utah.gov');
    esriConfig.request.corsEnabledServers.push('basemaps.utah.gov');
    esriConfig.request.corsEnabledServers.push('api.mapserv.utah.gov');
    esriConfig.request.corsEnabledServers.push('discover.agrc.utah.gov');
    esriConfig.request.corsEnabledServers.push('gis.trustlands.utah.gov');

    const config = {
        // app: app.App
        //      global reference to App
        app: null,

        // version.: String
        //      The version number.
        version: '3.2.1',

        // apiKey: String
        //      The api key used for services on api.mapserv.utah.gov
        // acquire at developer.mapserv.utah.gov
        apiKey: '',

        // wkt26912: String
        //      The well known text for utm zone 12 nad83 for use with proj4
        /* eslint-disable max-len */
        wkt26912: 'PROJCS["NAD83 / UTM zone 12N",GEOGCS["NAD83",DATUM["North_American_Datum_1983",SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4269"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-111],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],AUTHORITY["EPSG","26912"],AXIS["Easting",EAST],AXIS["Northing",NORTH]]',

        // wkt4326: String
        //      The well known text for wgs 84 (lat/long) for use with proj4
        wkt4326: 'GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]]',

        // wkt3857: String
        //      The well known text for wgs 84 for use with proj4
        wkt3857: 'PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Mercator_Auxiliary_Sphere"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",0.0],PARAMETER["Auxiliary_Sphere_Type",0.0],UNIT["Meter",1.0]]',
        /* eslint-enable max-len */

        urls: {
            search: 'https://api.mapserv.utah.gov/api/v1/search/{0}/{1}',
            reverseGeocode: 'https://api.mapserv.utah.gov/api/v1/geocode/reverse/{0}/{1}',
            landown: 'https://gis.trustlands.utah.gov/server/' +
                     '/rest/services/Ownership/UT_SITLA_Ownership_LandOwnership_WM/FeatureServer/0',
            exportWebMap: 'https://us-central1-utahkoopserver.cloudfunctions.net/printproxy/2' +
                '7/arcgis/rest/services/GPServer/export'
        },

        fieldNames: {
            // counties & municipalities
            NAME: 'NAME',
            // state
            STATE_LGD: 'STATE_LGD',
            GRID1Mil: 'GRID1Mil',
            GRIS100K: 'GRID100K',
            FEET: 'feet',
            METERS: 'value',
            ZIP5: 'ZIP5'
        },

        featureClassNames: {
            counties: 'SGID10.BOUNDARIES.Counties',
            municipalities: 'SGID10.BOUNDARIES.Municipalities',
            landOwnership: 'SGID10.CADASTRE.LandOwnership',
            nationalGrid: 'SGID10.INDICES.NationalGrid',
            dem: 'SGID10.RASTER.USGS_DEM_10METER',
            gnis: 'SGID10.LOCATION.PlaceNamesGNIS2010',
            zip: 'SGID10.BOUNDARIES.ZipCodes'
        }
    };

    if (has('agrc-build') === 'prod') {
        // atlas.utah.gov
        config.apiKey = 'AGRC-A94B063C533889';
        config.quadWord = 'career-exhibit-panel-stadium';
    } else if (has('agrc-build') === 'stage') {
        // test.mapserv.utah.gov
        config.quadWord = 'opera-event-little-pinball';
        config.apiKey = 'AGRC-AC122FA9671436';
    } else {
        // localhost
        xhr(require.baseUrl + 'secrets.json', {
            handleAs: 'json',
            sync: true
        }).then(function (secrets) {
            config.quadWord = secrets.quadWord;
            config.apiKey = secrets.apiKey;
        }, function () {
            throw 'Error getting secrets!';
        });
    }

    return config;
});
<|endoftext|>


<commit_before>'use strict';
const request          = require('../comum/tago_request.js');
const paramsSerializer = require('../comum/paramsSerializer.js');
const config           = require('../config.js');
const default_headers  = require('../comum/default_headers.js');
const share            = require('./_share.js');

class Buckets {
  constructor(acc_token) {
    this.token = acc_token;
    this.default_options = {
      'json':    true,
      'headers': default_headers(this)
    };
  }

  /** List Buckets
     * @param  {Number} page
     * Page of list starting from 1
     * Default: 1
     * @param  {Array} fields
     * Array of field names
     * Default: ['id', 'name']
     * Example: ['id', 'name', 'visible']
     *
     * Values allowed:
     * id, name, description, visible, backup, data_retention, last_backup,
     * account, tags, created_at, updated_at.
     * @param  {JSON} filter
     * JSON of filter
     * Without default
     * Example: {name: 'Motor'}
     * Values allowed: same of fields parameter.
     *
     * TIP: On name you can use * (asterisk) as wildcard.
     * @param {Number} amount
     * Amount of items will return
     * Default is 20
     * @param {String} orderBy
     * Order by a field
     * Examples:
     *  'name,asc'
     *  'name,desc'
     *  'name' [default: asc]
     * @return {Promise}
     * Array of buckets in alphabetically order.
    */
  list(page = 1, fields = ['id', 'name'], filter = {}, amount = 20, orderBy = 'name,asc') {
    if (!arguments.length) return this._list(); // @deprecated
    let url    = `${config.api_url}/bucket`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {
      url,
      method,
      paramsSerializer,
      params: {
        page,
        filter,
        fields,
        amount,
        orderBy,
      },
    });
    return request(options);
  }

  /**
     * It return old api style
     * @deprecated
     */
  _list() {
    const parameters = [
      1,
      ['account', 'backup', 'created_at', 'id', 'name', 'tags', 'visible'],
      {},
      1000,
      'name'
    ];
    return this.list.call(this, ...parameters);
  }

  /** Create a Bucket
    * @param  {object} data
    * @param  {string} data.name - Name of the bucket
    * @param  {string} data.description - description of the bucket
    * @param  {boolean} data.active - Set if bucket is active or not
    * @param  {object[]} tags - bucket tags for categorization
    * @param  {string} tags[].key - key of the tag
    * @param  {string} tags[].value - value of the tag
    * @return {Promise}
     */
  create(data) {
    data       = data || {};
    let url    = `${config.api_url}/bucket`;
    let method = 'POST';

    let options = Object.assign({}, this.default_options, {url, method, data});
    return request(options);
  }

  /** Edit the Bucket
    * @param  {String} bucket id
    * @param  {object} data
    * @param  {string} data.name - Name of the bucket
    * @param  {string} data.description - description of the bucket
    * @param  {boolean} data.active - Set if bucket is active or not
    * @param  {object[]} tags - bucket tags for categorization
    * @param  {string} tags[].key - key of the tag
    * @param  {string} tags[].value - value of the tag
    * @return {Promise}
     */
  edit(bkt_id, data) {
    data       = data || {};
    let url    = `${config.api_url}/bucket/${bkt_id}`;
    let method = 'PUT';

    let options = Object.assign({}, this.default_options, {url, method, data});
    return request(options);
  }

  /** Delete the Bucket
    * @param  {String} bucket id
    * @return {Promise}
     */
  delete(bkt_id) {
    let url    = `${config.api_url}/bucket/${bkt_id}`;
    let method = 'DELETE';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** DeleteVariable the variables inside the bucket
    * @param  {String} bucket id
    * @param  {object} data
    * @param  {string} data.variable - Name of the variable
    * @param  {string} data.origin - Name of the origin
    * @return {Promise}
    */
  deleteVariable(bkt_id, data) {
    data = data || {};
    let url = `${config.api_url}/bucket/${bkt_id}/variable`;
    let method = 'DELETE';

    let options = Object.assign({}, this.default_options, { url, method, data });
    return request(options);
  }

  /** listVariables the variables inside the bucket
    * @param  {String} bucket id
    * @param  {Boolean} showAmount return amount of each variable
    * @param  {Boolean} showDeleted return array of async deleted
    * @param  {Boolean} resolveOriginName
    * Change origins to array of object with id and name
    * @return {Promise}
    */
  listVariables(bkt_id, show_amount = false, show_deleted = false, resolveOriginName = false) {
    let url = `${config.api_url}/bucket/${bkt_id}/variable`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {
      url,
      method,
      params: {
        amount: show_amount,
        deleted: show_deleted,
        resolveOriginName,
      },
    });
    return request(options);
  }

  /** Get Amount of data on the Bucket
    * @param  {String} Bucket id
    * @return {Promise} With number of amount
    */
  amount(bkt_id) {
    if (!bkt_id || bkt_id == '') {
      return Promise.reject('Bucket ID parameter is obrigatory.');
    }
    let url = `${config.api_url}/bucket/${bkt_id}/data_amount`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, { url, method });
    return request(options);
  }

  /** Get Info of the Bucket
    * @param  {String} bucket id
    * @return {Promise}
    */
  info(bkt_id) {
    if (!bkt_id || bkt_id == '') {
      //If ID is send with null, it will get List instead info.
      return new Promise((resolve,reject) => reject('Bucket ID parameter is obrigatory.'));
    }
    let url    = `${config.api_url}/bucket/${bkt_id}`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** Get Info of the Backup
    * @param  {String} backup id
    * @return {Promise}
     */
  backupInfo(backup_id) {
    if (!backup_id || backup_id == '') {
      return new Promise((resolve,reject) => reject('Backup ID parameter is obrigatory.'));
    }
    let url    = `${config.api_url}/backup/${backup_id}`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** List all backups of the account
    * @return {Promise}
     */
  backupList() {
    let url    = `${config.api_url}/backup`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** Delete the Backup
    * @param  {String} backup_id id
    * @return {Promise}
     */
  backupDelete(backup_id) {
    if (!backup_id || backup_id == '') {
      return new Promise((resolve,reject) => reject('Backup ID parameter is obrigatory.'));
    }
    let url    = `${config.api_url}/backup/${backup_id}`;
    let method = 'DELETE';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** Recover the Backup
    * @param  {JSON} data object with parameters for recover
    * @param  {String} data.id backup id to be recovered
    * @param  {Array} data.ids multiple id's to be recovered
    * @return {Promise}
     */
  backupRecover(data) {
    data       = data || {};
    let url    = `${config.api_url}/backup/recover`;
    let method = 'POST';

    let options = Object.assign({}, this.default_options, {url, method, data});
    return request(options);
  }

  /** Get share list of the dashboard
    * @param  {String} dashboard id
    * @return {Promise}
     */
  shareList(bucket_id) {
    if (!bucket_id || bucket_id == '') {
      //If ID is send with null, it will get List instead info.
      return new Promise((resolve,reject) => reject('Bucket ID parameter is obrigatory.'));
    }
    return share.list('bucket', bucket_id, this.default_options);
  }

  /** Share the bucket with another person
    * @param  {String} bucket id
    * @param  {JSON} data -
    * @param  {String} data.email - Email to receive invitation
    * @param  {String} data.message - Scope message for the email
    * @param  {String} data.permission - Permission to be applied
    * @param  {boolean} data.copy_me - true to send a copy to yourself
    * @return {Promise}
     */
  shareSendInvite(bucket_id, data) {
    data = data || {};
    if (!bucket_id || bucket_id == '') {
      return new Promise((resolve,reject) => reject('Bucket ID parameter is obrigatory.'));
    } else if (!data.email) {
      return new Promise((resolve,reject) => reject('data.email parameter is obrigatory.'));
    }
    return share.invite('bucket', bucket_id, data, this.default_options);
  }

  /** Change permissions of the bucket
    * @param  {String} share id
    * @param  {JSON} data -
    * @param  {String} data.email - Email to change permissions
    * @param  {String} data.permission - New Permission to be applied
    * @param  {String} data.everyone
    * @return {Promise}
     */
  shareEdit(share_id, data) {
    data = data || {};
    if (!share_id || share_id == '') {
      return new Promise((resolve,reject) => reject('Share ID parameter is obrigatory.'));
    } else if (!data.email) {
      return new Promise((resolve,reject) => reject('data.email parameter is obrigatory.'));
    }
    return share.edit('bucket', share_id, data, this.default_options);
  }

  /** Remove share of the bucket
    * @param  {String} share id
    * @return {Promise}
     */
  shareDelete(share_id) {
    if (!share_id || share_id == '') {
      return new Promise((resolve,reject) => reject('Share ID parameter is obrigatory.'));
    }
    return share.remove('bucket', share_id, this.default_options);
  }

  /** Share the bucket with another person
    * @param  {String} output csv/json/xml
    * @param  {Object[]} buckets -
    * @param  {String} buckets[].id - bucket id to be filtred
    * @param  {String} buckets[].origin - variable origin to be filtred
    * @param  {Object[]} buckets[].variables - Array with variables name to be exported
    * @param  {Object} options -
    * @param  {String} options.start_date - start date to be filtred
    * @param  {String} options.end_date - end date to be filtred
    * @return {Promise}
     */
  exportData(output, buckets, options) {
    buckets = buckets || [];
    options = options || {};
    if (!output || output == '') {
      return new Promise((resolve,reject) => reject('Output parameter is obrigatory.'));
    } else if (!buckets || !buckets[0]) {
      return new Promise((resolve,reject) => reject('Buckets parameter is obrigatory.'));
    }

    const data = Object.assign({ buckets }, options);

    let url    = `${config.api_url}/data/export?output=${output}`;
    let method = 'POST';

    let request_options = Object.assign({}, this.default_options, {url, method, data});
    return request(request_options);
  }
}

module.exports = Buckets;
<commit_msg>added new method, Get all device associated with bucket<commit_after>'use strict';
const request          = require('../comum/tago_request.js');
const paramsSerializer = require('../comum/paramsSerializer.js');
const config           = require('../config.js');
const default_headers  = require('../comum/default_headers.js');
const share            = require('./_share.js');

class Buckets {
  constructor(acc_token) {
    this.token = acc_token;
    this.default_options = {
      'json':    true,
      'headers': default_headers(this)
    };
  }

  /** List Buckets
     * @param  {Number} page
     * Page of list starting from 1
     * Default: 1
     * @param  {Array} fields
     * Array of field names
     * Default: ['id', 'name']
     * Example: ['id', 'name', 'visible']
     *
     * Values allowed:
     * id, name, description, visible, backup, data_retention, last_backup,
     * account, tags, created_at, updated_at.
     * @param  {JSON} filter
     * JSON of filter
     * Without default
     * Example: {name: 'Motor'}
     * Values allowed: same of fields parameter.
     *
     * TIP: On name you can use * (asterisk) as wildcard.
     * @param {Number} amount
     * Amount of items will return
     * Default is 20
     * @param {String} orderBy
     * Order by a field
     * Examples:
     *  'name,asc'
     *  'name,desc'
     *  'name' [default: asc]
     * @return {Promise}
     * Array of buckets in alphabetically order.
    */
  list(page = 1, fields = ['id', 'name'], filter = {}, amount = 20, orderBy = 'name,asc') {
    if (!arguments.length) return this._list(); // @deprecated
    let url    = `${config.api_url}/bucket`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {
      url,
      method,
      paramsSerializer,
      params: {
        page,
        filter,
        fields,
        amount,
        orderBy,
      },
    });
    return request(options);
  }

  /**
     * It return old api style
     * @deprecated
     */
  _list() {
    const parameters = [
      1,
      ['account', 'backup', 'created_at', 'id', 'name', 'tags', 'visible'],
      {},
      1000,
      'name'
    ];
    return this.list.call(this, ...parameters);
  }

  /** Create a Bucket
    * @param  {object} data
    * @param  {string} data.name - Name of the bucket
    * @param  {string} data.description - description of the bucket
    * @param  {boolean} data.active - Set if bucket is active or not
    * @param  {object[]} tags - bucket tags for categorization
    * @param  {string} tags[].key - key of the tag
    * @param  {string} tags[].value - value of the tag
    * @return {Promise}
     */
  create(data) {
    data       = data || {};
    let url    = `${config.api_url}/bucket`;
    let method = 'POST';

    let options = Object.assign({}, this.default_options, {url, method, data});
    return request(options);
  }

  /** Edit the Bucket
    * @param  {String} bucket id
    * @param  {object} data
    * @param  {string} data.name - Name of the bucket
    * @param  {string} data.description - description of the bucket
    * @param  {boolean} data.active - Set if bucket is active or not
    * @param  {object[]} tags - bucket tags for categorization
    * @param  {string} tags[].key - key of the tag
    * @param  {string} tags[].value - value of the tag
    * @return {Promise}
     */
  edit(bkt_id, data) {
    data       = data || {};
    let url    = `${config.api_url}/bucket/${bkt_id}`;
    let method = 'PUT';

    let options = Object.assign({}, this.default_options, {url, method, data});
    return request(options);
  }

  /** Delete the Bucket
    * @param  {String} bucket id
    * @return {Promise}
     */
  delete(bkt_id) {
    let url    = `${config.api_url}/bucket/${bkt_id}`;
    let method = 'DELETE';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** DeleteVariable the variables inside the bucket
    * @param  {String} bucket id
    * @param  {object} data
    * @param  {string} data.variable - Name of the variable
    * @param  {string} data.origin - Name of the origin
    * @return {Promise}
    */
  deleteVariable(bkt_id, data) {
    data = data || {};
    let url = `${config.api_url}/bucket/${bkt_id}/variable`;
    let method = 'DELETE';

    let options = Object.assign({}, this.default_options, { url, method, data });
    return request(options);
  }

  /** listVariables the variables inside the bucket
    * @param  {String} bucket id
    * @param  {Boolean} showAmount return amount of each variable
    * @param  {Boolean} showDeleted return array of async deleted
    * @param  {Boolean} resolveOriginName
    * Change origins to array of object with id and name
    * @return {Promise}
    */
  listVariables(bkt_id, show_amount = false, show_deleted = false, resolveOriginName = false) {
    let url = `${config.api_url}/bucket/${bkt_id}/variable`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {
      url,
      method,
      params: {
        amount: show_amount,
        deleted: show_deleted,
        resolveOriginName,
      },
    });
    return request(options);
  }

  /**
   * Get all device associated with bucket
   * @param {String} bkt_id Bucket id
   * @return {Promise} Array of Devices with ID and Name
   */
  getDevicesAssociated(bkt_id) {
    if (!bkt_id || bkt_id == '') {
      return Promise.reject('Bucket ID parameter is obrigatory.');
    }
    let url = `${config.api_url}/bucket/${bkt_id}/device`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, { url, method });
    return request(options);
  }

  /** Get Amount of data on the Bucket
    * @param  {String} Bucket id
    * @return {Promise} With number of amount
    */
  amount(bkt_id) {
    if (!bkt_id || bkt_id == '') {
      return Promise.reject('Bucket ID parameter is obrigatory.');
    }
    let url = `${config.api_url}/bucket/${bkt_id}/data_amount`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, { url, method });
    return request(options);
  }

  /** Get Info of the Bucket
    * @param  {String} bucket id
    * @return {Promise}
    */
  info(bkt_id) {
    if (!bkt_id || bkt_id == '') {
      //If ID is send with null, it will get List instead info.
      return new Promise((resolve,reject) => reject('Bucket ID parameter is obrigatory.'));
    }
    let url    = `${config.api_url}/bucket/${bkt_id}`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** Get Info of the Backup
    * @param  {String} backup id
    * @return {Promise}
     */
  backupInfo(backup_id) {
    if (!backup_id || backup_id == '') {
      return new Promise((resolve,reject) => reject('Backup ID parameter is obrigatory.'));
    }
    let url    = `${config.api_url}/backup/${backup_id}`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** List all backups of the account
    * @return {Promise}
     */
  backupList() {
    let url    = `${config.api_url}/backup`;
    let method = 'GET';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** Delete the Backup
    * @param  {String} backup_id id
    * @return {Promise}
     */
  backupDelete(backup_id) {
    if (!backup_id || backup_id == '') {
      return new Promise((resolve,reject) => reject('Backup ID parameter is obrigatory.'));
    }
    let url    = `${config.api_url}/backup/${backup_id}`;
    let method = 'DELETE';

    let options = Object.assign({}, this.default_options, {url, method});
    return request(options);
  }

  /** Recover the Backup
    * @param  {JSON} data object with parameters for recover
    * @param  {String} data.id backup id to be recovered
    * @param  {Array} data.ids multiple id's to be recovered
    * @return {Promise}
     */
  backupRecover(data) {
    data       = data || {};
    let url    = `${config.api_url}/backup/recover`;
    let method = 'POST';

    let options = Object.assign({}, this.default_options, {url, method, data});
    return request(options);
  }

  /** Get share list of the dashboard
    * @param  {String} dashboard id
    * @return {Promise}
     */
  shareList(bucket_id) {
    if (!bucket_id || bucket_id == '') {
      //If ID is send with null, it will get List instead info.
      return new Promise((resolve,reject) => reject('Bucket ID parameter is obrigatory.'));
    }
    return share.list('bucket', bucket_id, this.default_options);
  }

  /** Share the bucket with another person
    * @param  {String} bucket id
    * @param  {JSON} data -
    * @param  {String} data.email - Email to receive invitation
    * @param  {String} data.message - Scope message for the email
    * @param  {String} data.permission - Permission to be applied
    * @param  {boolean} data.copy_me - true to send a copy to yourself
    * @return {Promise}
     */
  shareSendInvite(bucket_id, data) {
    data = data || {};
    if (!bucket_id || bucket_id == '') {
      return new Promise((resolve,reject) => reject('Bucket ID parameter is obrigatory.'));
    } else if (!data.email) {
      return new Promise((resolve,reject) => reject('data.email parameter is obrigatory.'));
    }
    return share.invite('bucket', bucket_id, data, this.default_options);
  }

  /** Change permissions of the bucket
    * @param  {String} share id
    * @param  {JSON} data -
    * @param  {String} data.email - Email to change permissions
    * @param  {String} data.permission - New Permission to be applied
    * @param  {String} data.everyone
    * @return {Promise}
     */
  shareEdit(share_id, data) {
    data = data || {};
    if (!share_id || share_id == '') {
      return new Promise((resolve,reject) => reject('Share ID parameter is obrigatory.'));
    } else if (!data.email) {
      return new Promise((resolve,reject) => reject('data.email parameter is obrigatory.'));
    }
    return share.edit('bucket', share_id, data, this.default_options);
  }

  /** Remove share of the bucket
    * @param  {String} share id
    * @return {Promise}
     */
  shareDelete(share_id) {
    if (!share_id || share_id == '') {
      return new Promise((resolve,reject) => reject('Share ID parameter is obrigatory.'));
    }
    return share.remove('bucket', share_id, this.default_options);
  }

  /** Share the bucket with another person
    * @param  {String} output csv/json/xml
    * @param  {Object[]} buckets -
    * @param  {String} buckets[].id - bucket id to be filtred
    * @param  {String} buckets[].origin - variable origin to be filtred
    * @param  {Object[]} buckets[].variables - Array with variables name to be exported
    * @param  {Object} options -
    * @param  {String} options.start_date - start date to be filtred
    * @param  {String} options.end_date - end date to be filtred
    * @return {Promise}
     */
  exportData(output, buckets, options) {
    buckets = buckets || [];
    options = options || {};
    if (!output || output == '') {
      return new Promise((resolve,reject) => reject('Output parameter is obrigatory.'));
    } else if (!buckets || !buckets[0]) {
      return new Promise((resolve,reject) => reject('Buckets parameter is obrigatory.'));
    }

    const data = Object.assign({ buckets }, options);

    let url    = `${config.api_url}/data/export?output=${output}`;
    let method = 'POST';

    let request_options = Object.assign({}, this.default_options, {url, method, data});
    return request(request_options);
  }
}

module.exports = Buckets;
<|endoftext|>


<commit_before>import Object from '@ember/object';
import THREE from "three";

export default Object.extend({

  textLabels: null,

  systemTextCache: null,
  nodeTextCache: null,
  appTextCache: null,

  font: null,

  init() {
    this._super(...arguments);

    this.set('textLabels', {});
    this.set('systemTextCache', []);
    this.set('nodeTextCache', []);
    this.set('appTextCache', []);
  },

  saveTextForLabeling(textToShow, parent, color) {
    const emberModelName = parent.userData.model.constructor.modelName;
    const text = textToShow ? textToShow : parent.userData.model.get('name');

    let textCache = 'systemTextCache';

    if (emberModelName === "node") {
      textCache = 'nodeTextCache';
    }
    else if (emberModelName === "application") {
      textCache = 'appTextCache';
    }

    this.get(textCache).push({ text: text, parent: parent, color: color });
  },

  drawTextLabels(font, configuration) {
    this.set('font', font);
    this.set('configuration', configuration);

    this.drawSystemTextLabels();
    this.drawNodeTextLabels();
    this.drawAppTextLabels();

    // After drawing, reset all caches for next tick
    this.set('systemTextCache', []);
    this.set('nodeTextCache', []);
    this.set('appTextCache', []);

  },

  drawSystemTextLabels() {

    this.get('systemTextCache').forEach((textObj) => {
      const threejsModel = textObj.parent;
      const emberModel = threejsModel.userData.model;

      let labelMesh = this.isLabelAlreadyCreated(emberModel);

      if (labelMesh && labelMesh.mesh) {
        // Update meta-info for model
        labelMesh.mesh.userData['model'] = emberModel;
        threejsModel['label'] = labelMesh.mesh;
        threejsModel.add(labelMesh.mesh);
        labelMesh = labelMesh.mesh;
      }
      else {
        const labelGeo = new THREE.TextBufferGeometry(textObj.text, {
          font: this.get('font'),
          size: 0.4,
          height: 0
        });

        const material = new THREE.MeshBasicMaterial({
          color: textObj.color
        });

        labelMesh = new THREE.Mesh(labelGeo, material);
        labelMesh.userData['type'] = 'label';
        labelMesh.userData['model'] = emberModel;

        this.get('textLabels')[emberModel.get('id')] =
          { "mesh": labelMesh };

        threejsModel['label'] = labelMesh;
        threejsModel.add(labelMesh);
      }

      this.repositionSystemLabel(labelMesh);
    });
  },

  drawNodeTextLabels() {

    this.get('nodeTextCache').forEach((textObj) => {
      const threejsModel = textObj.parent;
      const emberModel = threejsModel.userData.model;
      const nodegroupstate = emberModel.get('parent.opened');

      let labelMesh = this.isLabelAlreadyCreated(emberModel);

      if (labelMesh && labelMesh.mesh &&
        labelMesh.nodegroupopenstate === nodegroupstate) {
        // update meta-info for model
        labelMesh.mesh.userData['model'] = emberModel;
        threejsModel['label'] = labelMesh.mesh;
        threejsModel.add(labelMesh.mesh);
        labelMesh = labelMesh.mesh;
      }
      else {
        const text = emberModel.getDisplayName();
        textObj.text = text;

        const labelGeo = new THREE.TextBufferGeometry(text, {
          font: this.get('font'),
          size: 0.22,
          height: 0
        });

        const material = new THREE.MeshBasicMaterial({
          color: textObj.color
        });

        labelMesh = new THREE.Mesh(labelGeo, material);

        labelMesh.userData['type'] = 'label';
        labelMesh.userData['model'] = emberModel;

        this.get('textLabels')[emberModel.get('id')] =
          { "mesh": labelMesh, "nodegroupopenstate": emberModel.get('parent.opened') };

        threejsModel['label'] = labelMesh;
        threejsModel.add(labelMesh);
      }

      this.repositionNodeLabel(labelMesh);
    });
  },

  drawAppTextLabels() {

    this.get('appTextCache').forEach((textObj) => {

      const threejsModel = textObj.parent;
      const emberModel = threejsModel.userData.model;

      let labelMesh = this.isLabelAlreadyCreated(emberModel);

      if (labelMesh && labelMesh.mesh) {
        // Update meta-info for model
        labelMesh.mesh.userData['model'] = emberModel;
        threejsModel['label'] = labelMesh.mesh;
        threejsModel.add(labelMesh.mesh);
        labelMesh = labelMesh.mesh;
      }
      else {
        const labelGeo = new THREE.TextBufferGeometry(textObj.text, {
          font: this.get('font'),
          size: 0.25,
          height: 0
        });

        const material = new THREE.MeshBasicMaterial({
          color: textObj.color
        });

        labelMesh = new THREE.Mesh(labelGeo, material);

        labelMesh.userData['type'] = 'label';
        labelMesh.userData['model'] = emberModel;

        this.get('textLabels')[emberModel.get('id')] =
          { "mesh": labelMesh };

        threejsModel['label'] = labelMesh;
        threejsModel.add(labelMesh);
      }

      this.repositionAppLabel(labelMesh);
    });
  },

  repositionSystemLabel(labelMesh) {
    const parent = labelMesh.parent;

    parent.geometry.computeBoundingBox();
    const bboxParent = parent.geometry.boundingBox;

    labelMesh.geometry.computeBoundingBox();
    const labelBoundingBox = labelMesh.geometry.boundingBox;

    const labelLength = Math.abs(labelBoundingBox.max.x) -
      Math.abs(labelBoundingBox.min.x);

    const yOffset = 0.6;

    labelMesh.position.x = - (labelLength / 2.0);
    labelMesh.position.y = bboxParent.max.y - yOffset;
    labelMesh.position.z = parent.position.z + 0.001;
  },

  repositionNodeLabel(labelMesh) {
    const parent = labelMesh.parent;

    parent.geometry.computeBoundingBox();
    const bboxParent = parent.geometry.boundingBox;

    labelMesh.geometry.computeBoundingBox();
    const labelBoundingBox = labelMesh.geometry.boundingBox;

    const labelLength = Math.abs(labelBoundingBox.max.x) -
      Math.abs(labelBoundingBox.min.x);

    const yOffset = 0.2;

    labelMesh.position.x = - (labelLength / 2.0);
    labelMesh.position.y = bboxParent.min.y + yOffset;
    labelMesh.position.z = parent.position.z + 0.001;

  },

  repositionAppLabel(labelMesh) {
    const parent = labelMesh.parent;

    parent.geometry.computeBoundingBox();
    const bboxParent = parent.geometry.boundingBox;

    labelMesh.geometry.computeBoundingBox();
    const labelBoundingBox = labelMesh.geometry.boundingBox;

    const labelHeight = Math.abs(labelBoundingBox.max.y) -
      Math.abs(labelBoundingBox.min.y);

    const xOffset = 0.1;

    labelMesh.position.x = bboxParent.min.x + xOffset;
    labelMesh.position.y = -(labelHeight / 2.0);
    labelMesh.position.z = parent.position.z + 0.001;
  },

  isLabelAlreadyCreated(emberModel) {
    // Label already created and color didn't change?
    if (this.get('textLabels')[emberModel.get('id')] &&
      !this.get('configuration.landscapeColors.textchanged')) {

      const oldTextLabelObj =
        this.get('textLabels')[emberModel.get('id')];

      return oldTextLabelObj;
    }
    return null;
  },

  findLongestTextLabel(labelStrings) {
    let longestString = "";

    labelStrings.map(function (obj) {

      if (obj.text.length >= longestString.length) {
        longestString = obj.text;
      }
    });

    return longestString;
  }

});
<commit_msg>Fix: Update labels if name of landscape entities changed<commit_after>import Object from '@ember/object';
import THREE from "three";

export default Object.extend({

  textLabels: null,

  systemTextCache: null,
  nodeTextCache: null,
  appTextCache: null,

  font: null,

  init() {
    this._super(...arguments);

    this.set('textLabels', {});
    this.set('systemTextCache', []);
    this.set('nodeTextCache', []);
    this.set('appTextCache', []);
  },

  saveTextForLabeling(textToShow, parent, color) {
    const emberModelName = parent.userData.model.constructor.modelName;
    const text = textToShow ? textToShow : parent.userData.model.get('name');

    let textCache = 'systemTextCache';

    if (emberModelName === "node") {
      textCache = 'nodeTextCache';
    }
    else if (emberModelName === "application") {
      textCache = 'appTextCache';
    }

    this.get(textCache).push({ text: text, parent: parent, color: color });
  },

  drawTextLabels(font, configuration) {
    this.set('font', font);
    this.set('configuration', configuration);

    this.drawSystemTextLabels();
    this.drawNodeTextLabels();
    this.drawAppTextLabels();

    // After drawing, reset all caches for next tick
    this.set('systemTextCache', []);
    this.set('nodeTextCache', []);
    this.set('appTextCache', []);

  },

  drawSystemTextLabels() {

    this.get('systemTextCache').forEach((textObj) => {
      const threejsModel = textObj.parent;
      const emberModel = threejsModel.userData.model;

      let labelMesh = this.isLabelAlreadyCreated(emberModel);

      if (labelMesh && labelMesh.mesh) {
        // Update meta-info for model
        labelMesh.mesh.userData['model'] = emberModel;
        threejsModel['label'] = labelMesh.mesh;
        threejsModel.add(labelMesh.mesh);
        labelMesh = labelMesh.mesh;
      }
      else {
        const labelGeo = new THREE.TextBufferGeometry(textObj.text, {
          font: this.get('font'),
          size: 0.4,
          height: 0
        });

        const material = new THREE.MeshBasicMaterial({
          color: textObj.color
        });

        labelMesh = new THREE.Mesh(labelGeo, material);

        labelMesh.name = emberModel.get('name');
        labelMesh.userData['type'] = 'label';
        labelMesh.userData['model'] = emberModel;

        this.get('textLabels')[emberModel.get('id')] =
          { "mesh": labelMesh };

        threejsModel['label'] = labelMesh;
        threejsModel.add(labelMesh);
      }

      this.repositionSystemLabel(labelMesh);
    });
  },

  drawNodeTextLabels() {

    this.get('nodeTextCache').forEach((textObj) => {
      const threejsModel = textObj.parent;
      const emberModel = threejsModel.userData.model;
      const nodegroupstate = emberModel.get('parent.opened');

      let labelMesh = this.isLabelAlreadyCreated(emberModel);

      if (labelMesh && labelMesh.mesh &&
        labelMesh.nodegroupopenstate === nodegroupstate) {
        // update meta-info for model
        labelMesh.mesh.userData['model'] = emberModel;
        threejsModel['label'] = labelMesh.mesh;
        threejsModel.add(labelMesh.mesh);
        labelMesh = labelMesh.mesh;
      }
      else {
        const text = emberModel.getDisplayName();
        textObj.text = text;

        const labelGeo = new THREE.TextBufferGeometry(text, {
          font: this.get('font'),
          size: 0.22,
          height: 0
        });

        const material = new THREE.MeshBasicMaterial({
          color: textObj.color
        });

        labelMesh = new THREE.Mesh(labelGeo, material);

        labelMesh.name = emberModel.get('name');
        labelMesh.userData['type'] = 'label';
        labelMesh.userData['model'] = emberModel;

        this.get('textLabels')[emberModel.get('id')] =
          { "mesh": labelMesh, "nodegroupopenstate": emberModel.get('parent.opened') };

        threejsModel['label'] = labelMesh;
        threejsModel.add(labelMesh);
      }

      this.repositionNodeLabel(labelMesh);
    });
  },

  drawAppTextLabels() {

    this.get('appTextCache').forEach((textObj) => {

      const threejsModel = textObj.parent;
      const emberModel = threejsModel.userData.model;

      let labelMesh = this.isLabelAlreadyCreated(emberModel);

      if (labelMesh && labelMesh.mesh) {
        // Update meta-info for model
        labelMesh.mesh.userData['model'] = emberModel;
        threejsModel['label'] = labelMesh.mesh;
        threejsModel.add(labelMesh.mesh);
        labelMesh = labelMesh.mesh;
      }
      else {
        const labelGeo = new THREE.TextBufferGeometry(textObj.text, {
          font: this.get('font'),
          size: 0.25,
          height: 0
        });

        const material = new THREE.MeshBasicMaterial({
          color: textObj.color
        });

        labelMesh = new THREE.Mesh(labelGeo, material);

        labelMesh.name = emberModel.get('name');
        labelMesh.userData['type'] = 'label';
        labelMesh.userData['model'] = emberModel;

        this.get('textLabels')[emberModel.get('id')] =
          { "mesh": labelMesh };

        threejsModel['label'] = labelMesh;
        threejsModel.add(labelMesh);
      }

      this.repositionAppLabel(labelMesh);
    });
  },

  repositionSystemLabel(labelMesh) {
    const parent = labelMesh.parent;

    parent.geometry.computeBoundingBox();
    const bboxParent = parent.geometry.boundingBox;

    labelMesh.geometry.computeBoundingBox();
    const labelBoundingBox = labelMesh.geometry.boundingBox;

    const labelLength = Math.abs(labelBoundingBox.max.x) -
      Math.abs(labelBoundingBox.min.x);

    const yOffset = 0.6;

    labelMesh.position.x = - (labelLength / 2.0);
    labelMesh.position.y = bboxParent.max.y - yOffset;
    labelMesh.position.z = parent.position.z + 0.001;
  },

  repositionNodeLabel(labelMesh) {
    const parent = labelMesh.parent;

    parent.geometry.computeBoundingBox();
    const bboxParent = parent.geometry.boundingBox;

    labelMesh.geometry.computeBoundingBox();
    const labelBoundingBox = labelMesh.geometry.boundingBox;

    const labelLength = Math.abs(labelBoundingBox.max.x) -
      Math.abs(labelBoundingBox.min.x);

    const yOffset = 0.2;

    labelMesh.position.x = - (labelLength / 2.0);
    labelMesh.position.y = bboxParent.min.y + yOffset;
    labelMesh.position.z = parent.position.z + 0.001;

  },

  repositionAppLabel(labelMesh) {
    const parent = labelMesh.parent;

    parent.geometry.computeBoundingBox();
    const bboxParent = parent.geometry.boundingBox;

    labelMesh.geometry.computeBoundingBox();
    const labelBoundingBox = labelMesh.geometry.boundingBox;

    const labelHeight = Math.abs(labelBoundingBox.max.y) -
      Math.abs(labelBoundingBox.min.y);

    const xOffset = 0.1;

    labelMesh.position.x = bboxParent.min.x + xOffset;
    labelMesh.position.y = -(labelHeight / 2.0);
    labelMesh.position.z = parent.position.z + 0.001;
  },

  isLabelAlreadyCreated(emberModel) {
    let potentialLabel = this.get('textLabels')[emberModel.get('id')];
    // Label exists and text + text color did not change?
    if (potentialLabel && potentialLabel.mesh.name === emberModel.get('name') &&
      !this.get('configuration.landscapeColors.textchanged')) {
      const oldTextLabelObj =
        this.get('textLabels')[emberModel.get('id')];

      return oldTextLabelObj;
    }
    return null;
  },

  findLongestTextLabel(labelStrings) {
    let longestString = "";

    labelStrings.map(function (obj) {

      if (obj.text.length >= longestString.length) {
        longestString = obj.text;
      }
    });

    return longestString;
  }

});
<|endoftext|>


<commit_before>// @flow
import createPoint from 'utils/recallPoint'

type album = {
  title: string,
  artist: string,
  cover: string,
  tracks: [
    {
      title: string,
      hash: string
    }
  ]
};

const getInitial = () => (
  {
    title: '',
    artist: '',
    cover: '',
    tracks: [
      {
        title: '',
        hash: ''
      }
    ]
  }: album
)

let state = getInitial()

const point = createPoint(
  (ACTION, ...params) => {
    if (ACTION === 'DROP') {
      state = getInitial()
    }
    if (ACTION === 'SET_VALUE') {
      const [name, value] = params
      state[name] = value
    }
    if (ACTION === 'ADD_TRACK') {
      state.tracks.push({
        title: '', hash: ''
      })
    }
    if (ACTION === 'EDIT_TRACK') {
      const [index, value] = params
      state.tracks[index] = value
    }
    return state
  }
)

export default point
<commit_msg>formAlbumState moved to recall-action<commit_after>// @flow
import createPoint from 'recall-action'

type album = {
  title: string,
  artist: string,
  cover: string,
  tracks: [
    {
      title: string,
      hash: string
    }
  ]
};

const getInitial = () => (
  {
    title: '',
    artist: '',
    cover: '',
    tracks: [
      {
        title: '',
        hash: ''
      }
    ]
  }: album
)

let state = getInitial()

const actions = {
  DROP () {
    state = getInitial()
  },
  SET_VALUE (...params) {
    const [name, value] = params
    state[name] = value
  },
  ADD_TRACK (...params) {
    state.tracks.push({
      title: '', hash: ''
    })
  },
  EDIT_TRACK (...params) {
    const [index, value] = params
    state.tracks[index] = value
  }
}

const point = createPoint(
  (ACTION, ...params) => {
    if (ACTION) {
      actions[ACTION](...params)
    }
    return state
  }
)

export default point
<|endoftext|>


<commit_before>import React from 'react';
import Field from '../Field';
import Checkbox from '../../components/Checkbox';
import { FormField } from 'elemental';

module.exports = Field.create({
	displayName: 'BooleanField',
	statics: {
		type: 'Boolean',
	},
	propTypes: {
		indent: React.PropTypes.bool,
		label: React.PropTypes.string,
		onChange: React.PropTypes.func.isRequired,
		path: React.PropTypes.string.isRequired,
		value: React.PropTypes.bool,
	},

	valueChanged (value) {
		this.props.onChange({
			path: this.props.path,
			value: value,
		});
	},
	renderFormInput () {
		if (!this.shouldRenderField()) return;

		return (
			<input
				name={this.getInputName(this.props.path)}
				type="hidden"
				value={!!this.props.value}
			/>
		);
	},
	renderUI () {
		const { indent, value, label, path } = this.props;

		return (

				<FormField offsetAbsentLabel={indent}>

						{this.renderFormInput()}
						<Checkbox
							checked={value}
							onChange={this.shouldRenderField() && this.valueChanged}
							readonly={!this.shouldRenderField()}
						/>

							{label}

					{this.renderNote()}
				</FormField>

		);
	},
});
<commit_msg>Fix BooleanField propType warning<commit_after>import React from 'react';
import Field from '../Field';
import Checkbox from '../../components/Checkbox';
import { FormField } from 'elemental';

const NOOP = () => {};

module.exports = Field.create({
	displayName: 'BooleanField',
	statics: {
		type: 'Boolean',
	},
	propTypes: {
		indent: React.PropTypes.bool,
		label: React.PropTypes.string,
		onChange: React.PropTypes.func.isRequired,
		path: React.PropTypes.string.isRequired,
		value: React.PropTypes.bool,
	},

	valueChanged (value) {
		this.props.onChange({
			path: this.props.path,
			value: value,
		});
	},
	renderFormInput () {
		if (!this.shouldRenderField()) return;

		return (
			<input
				name={this.getInputName(this.props.path)}
				type="hidden"
				value={!!this.props.value}
			/>
		);
	},
	renderUI () {
		const { indent, value, label, path } = this.props;

		return (

				<FormField offsetAbsentLabel={indent}>

						{this.renderFormInput()}
						<Checkbox
							checked={value}
							onChange={(this.shouldRenderField() && this.valueChanged) || NOOP}
							readonly={!this.shouldRenderField()}
						/>

							{label}

					{this.renderNote()}
				</FormField>

		);
	},
});
<|endoftext|>