<commit_before>'use strict';

/**
 * @desc order directive that is specific to the order module at a company named Acme
 * @example

 */

function EntityListController($scope, $window, $state, context, $filter, $stateParams, EntityService, dragularService, $element, $interval, $uiViewScroll, $timeout, LayoutService, UsersService, TasksService, PermissionsService, MultipleSelectService, NotifyingService) {

    // ============================================================= //
    // ========================= navigate ========================== //
    // ============================================================= //
    $scope.unifiedRowTpl = '/icu/components/entity-list/regions/row.html';

    $scope.isCurrentEntityState = function(id) {
        return $state.current.name.indexOf(`main.${$scope.$parent.entityName}.byentity`) === 0 && $state.current.name.indexOf('details') === -1;
    }

    let possibleNavigate = $scope.$parent.items.filter( t => t.recycled == null );

    if (possibleNavigate.length) {
        function navigateToDetails(item) {
            if (!item)
                return;

            $scope.detailsState = context.entityName === 'all' ? `main.${$scope.$parent.entityName}.all.details` : `main.${$scope.$parent.entityName}.byentity.details`;

            $state.go($scope.detailsState, {
                id: item._id,
                entity: context.entityName,
                entityId: context.entityId,
            });
        }
        if ($state.current.name === `main.${$scope.$parent.entityName}.all` || $state.current.name === `main.${$scope.$parent.entityName}.byentity` || $state.current.name === `main.${$scope.$parent.entityName}.all.details.${window.config.defaultTab}` || $state.current.name === `main.${$scope.$parent.entityName}.byentity.details.${window.config.defaultTab}`) {
            var date = new Date();
            var lastIndex = possibleNavigate.length - 1;
            var diff = date.getTime() - new Date(possibleNavigate[lastIndex].created).getTime();
            if (possibleNavigate[lastIndex].title == "" && diff <= 2500) {
                navigateToDetails(possibleNavigate[lastIndex]);
            } else {
                navigateToDetails(possibleNavigate[0]);
            }
        }
    } else {
        if ($state.current.name == `main.${$scope.$parent.entityName}.all.details.${window.config.defaultTab}`) {
            $state.go(`main.${$scope.$parent.entityName}.all`);
        }
    }

   if (context.entityName === 'all') {
        $scope.detailsState = `main.${$scope.$parent.entityName}.all.details`;
    } else if (context.entityName === 'my') {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byassign.details`;
    } else if (
      (context.entityName === 'task' || context.entityName === 'project')
     && $state.current.name.indexOf('byparent') !== -1) {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byparent.details`;
    } else {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byentity.details`;
    }

    var isScrolled = false;

    $scope.seenSelectedItem = false;
    $scope.isCurrentState = isCurrentState();
    $scope.isCurrentEntity = function(id){
        let currentSelected = $state.params.id === id;

        if(currentSelected)
            $scope.seenSelectedItem = true;
        return currentSelected
    };

    function isCurrentState() {
        let currentState = postfix => $state.current.name.indexOf(`main.${$scope.$parent.entityName}${postfix}`) === 0;
        let isActive = (
          currentState('.byparent.details') || currentState('.byentity.details') ||
          currentState('.all.details')
        );
        if (isActive && !isScrolled) {
            isScrolled = true;
        }
        return isActive;
    }

    $scope.$watch('seenSelectedItem', newValue => {
      if(newValue)$timeout(() => scrollToElement(), 0);
    });

    function scrollToElement(){
        let list = document.getElementsByClassName('list-table scroll')[0],
            elem = document.querySelector('tr.active');
        if(!list && !elem)return;

        let listBottom = list.scrollTop + list.offsetHeight,
            elementBottom = elem.offsetTop + elem.offsetHeight;
        // if(elementBottom > listBottom)list.scrollTop = elem.offsetTop;
        if(elementBottom > listBottom)
            elem.scrollIntoView({ behavior: 'smooth' });

    }

    // ============================================================= //
    // ========================== filters ========================== //
    // ============================================================= //

    $scope.print = function() {
        $window.print()
    };

    $scope.starred = $stateParams.starred;

    $scope.activeToggleList = EntityService.activeToggleList;
    $scope.activeToggle = {
        field: !EntityService.isActiveStatusAvailable() ? 'all' : $stateParams.activeToggle || 'active',
        disabled: !EntityService.isActiveStatusAvailable()
    };

    $scope.changeOrder = function() {
        if ($scope.sorting.field != "custom") {
            $scope.sorting.isReverse = !$scope.sorting.isReverse;
        }

        $scope.refreshVisibleItems();

        /*Made By OHAD - Needed for reversing sort*/
        $state.go($state.current.name, {
            sort: $scope.sorting.field
        });

        $scope.refreshVisibleItems();
    };

    $scope.sorting = {
        field: $stateParams.sort || 'created',
        isReverse: false
    };

    $scope.sortingList = [{
        title: 'title',
        value: 'title'
    }, {
        title: 'status',
        value: 'status'
    }, {
        title: 'created',
        value: 'created'
    }, {
      title: 'bolded',
      value: 'bolded.bolded'
    }];

    if (context.entityName != "all") {
        $scope.sortingList.push({
            title: 'custom',
            value: 'custom'
        });
    }

    $scope.toggleStarred = function() {
        $state.go($state.current.name, {
            starred: !$stateParams.starred
        });
    };

    $scope.filterActive = function() {
        EntityService.activeStatusFilterValue = $scope.activeToggle.field;
        $state.go($state.current.name, {
            activeToggle: $scope.activeToggle.field
        });
    };

    // ============================================================= //
    // =========================== list ============================ //
    // ============================================================= //

    $scope.context = context;
    $scope.isLoading = true;

    let inCurrentEntity = (entity)=> $state.current.name.indexOf(entity) !== -1;

    $scope.showTaskExcel = inCurrentEntity('tasks')
    $scope.showOfficeDocumentsExcel = inCurrentEntity('offices');

    let tasksExcelHandler = TasksService.excel;
    $scope.taskExcel = tasksExcelHandler;
    $scope.excel = {
        selected:{title:""},
        officeList:_.filter($scope.offices,(office)=>office.title&&office.title!=="")
    };

    $scope.onClickRow = function($event, item) {
        if ($scope.displayOnly) {
            return;
        }

        var nameFocused = angular.element($event.target).hasClass('name');

        $state.go($scope.detailsState + '.' + window.config.defaultTab, {
            id: item._id,
            entity: context.entityName,
            entityId: context.entityId,
            nameFocused: nameFocused
        });

        LayoutService.clicked();
    };

    $scope.onCreate = function() {
        if ($state.current.name.indexOf("byentity") !== -1 || $state.current.name.indexOf("byparent") !== -1) {
            var parent = {};
            parent.type = $state.current.params.entity || 'parent';
            parent.id = $state.current.params.entityId;
        }
        $scope.$parent.create(parent).then((result)=>{
            $scope.refreshVisibleItems();
            $timeout(()=> {
              let lastElementIndex = $element.find('td.name').length - 1;
              let currentElement = $element.find('td.name').get(lastElementIndex - 1);
              let nextElement = $element.find('td.name').get(lastElementIndex);

              let focusedElement = currentElement && nextElement;
              focusedElement.focus();
            },100);
            $state.go($scope.detailsState + '.' + window.config.defaultTab, {
                id: result._id,
                entity: context.entityName,
                entityId: context.entityId,
                nameFocused: true
            });
            //             }

        }
        );
    };

    // ============================================================= //
    // =================== multiple operations ===================== //
    // ============================================================= //

    $scope.mouseOnMultiple = false;
    $scope.multipleSelectMode = false;
    $scope.selectedItems = MultipleSelectService.refreshSelectedList();
    $scope.cornerState = MultipleSelectService.getCornerState();
    NotifyingService.notify('multipleDisableDetailsPaneCheck');

    $scope.multipleSelectRefreshSelected = function (entity) {
        MultipleSelectService.refreshSelectedList(entity);
        multipleSelectRefreshState();
    };

    $scope.$on('changeCornerState', (event, cornerState) => multipleSelectSetAllSelected(cornerState === 'all'));

    function multipleSelectSetAllSelected(status){
        for(let i = 0; i < $scope.visibleItems.length; i++){
            let row = $scope.visibleItems[i];

            if(!row.selected)MultipleSelectService.refreshSelectedList(row);
            row.selected = status;
        }
        if(status){
            MultipleSelectService.setSelectedList($scope.visibleItems);
        } else {
            MultipleSelectService.refreshSelectedList();
        }
        multipleSelectRefreshState();
    }

    NotifyingService.subscribe('refreshAfterOperation', () => {
        multipleSelectRefreshState();
        $scope.refreshVisibleItems();
    }, $scope);

    $scope.cursorEnterMultiple = function(mouseOn){ $scope.mouseOnMultiple = !!mouseOn };
    $scope.showTick = function(item){ item.visible = true };
    $scope.hideTick = function(item){ item.visible = false };

    $scope.checkForHideMultiple = function(){
        if(MultipleSelectService.getCornerState() === 'none'){
            changeMultipleMode(false);
        }
    };

    function multipleSelectRefreshState(){
        $scope.selectedItems = getFilteredSelectedList();
        refreshActiveItemsInList();
        $scope.cornerState = getRefreshedCornerState();

        if ($scope.selectedItems.length) {
            changeMultipleMode(true);
        } else {
            MultipleSelectService.refreshSelectedList();
        }

        multipleDisablingCheck();
        $scope.$broadcast('refreshBulkButtonsAccess');
        NotifyingService.notify('multipleDisableDetailsPaneCheck');
    }

    function multipleDisablingCheck(){
        if(!$scope.selectedItems.length && !$scope.mouseOnMultiple){
            changeMultipleMode(false);
        }
    }

    function changeMultipleMode(value){
        $scope.multipleSelectMode = value;
    }

    function getFilteredSelectedList(){
        let selected = MultipleSelectService.getSelected(),
            filteredSelected = filterResults(selected),
            newSelectedList = MultipleSelectService.setSelectedList(filteredSelected);

        return newSelectedList;
    }

    function getRefreshedCornerState(){
        return MultipleSelectService.refreshCornerState(filterResults($scope.visibleItems).length);
    }

    function refreshActiveItemsInList(){
        for(let item of $scope.visibleItems){
            let entity = $scope.selectedItems.find( selectedItems => selectedItems._id === item._id );
            item.selected = !!entity;
        }
    }

    // ============================================================= //
    // ======================= item function ======================= //
    // ============================================================= //

    $scope.onKeydown = function($event, index) {
        angular.element($event.target).css('box-shadow', 'none');

        if ($event.keyCode === 13) {
            $event.preventDefault();
            let nextElementCreated = $scope.items[index + 1];
            let nextElementInDOM = $element.find('td.name').get(index + 1);

            if (nextElementCreated && nextElementInDOM) {
                $state.go($scope.detailsState + '.' + window.config.defaultTab, {
                    id: $scope.items[index + 1]._id,
                    entity: context.entityName,
                    entityId: context.entityId,
                    nameFocused: true
                });
                nextElementInDOM.focus();
            } else {
                $scope.onCreate();
            }
            //             var sr = $scope.searchResults[$scope.selectedSuggestion];
            //              $scope.select(sr);
        }
    }
    $scope.focusing = function(entity){
        entity.focus = true;
    };
    $scope.bluring = function(entity, $event){
        entity.focus = false;

        var scrollLeft = function(element){
            element.scrollLeft = 0;
        };
        var scrollRight = function(element){
            element.scrollLeft += $event.target.scrollWidth - $event.target.scrollLeft;
        };

        let usingFunction = config.direction === 'rtl' ? scrollRight : scrollLeft;
        usingFunction($event.target);
    };

    //     $scope.onBlur = function(item) {
    //         item.__autocomplete = false;
    //         $scope.searchResults.length = 0;
    //         $scope.selectedSuggestion = 0;
    //     }

    // infinite scroll
    //     $timeout(function() {
    $scope.displayLimit = Math.ceil($element.height() / 50);
    $scope.isLoading = false;
    //     }, 0);

    $scope.loadMore = function() {
        var LIMIT = 25;
        let loadedVisibleCount = 0;
        let listEnd = false;

        loadWithVisibleCheck(listEnd, loadedVisibleCount);

        function loadWithVisibleCheck(listEnd, loadedVisibleCount) {
            if (!$scope.isLoading) {
                if (loadedVisibleCount < 25 && !listEnd) {
                    var start = $scope.items.length;
                    var sort = 'created';
                    //$scope.order.field;
                    $scope.$parent.loadMore(start, LIMIT, sort).then(result => {
                        if (result.length === 0) listEnd = true;
                        loadedVisibleCount += filterResults(result).length;
                        $scope.refreshVisibleItems();
                        loadWithVisibleCheck(listEnd, loadedVisibleCount);
                    })
                }
            }
        }
    };

    $scope.refreshVisibleItems = function() {
        $scope.visibleItems = removeDuplicates(filterResults($scope.items))
    };

    $scope.checkForInactiveEntity = () => {
        if($scope.visibleItems.length){
            let entityIndex = $scope.visibleItems.findIndex( item => item._id === $stateParams.id );
            entityIndex = entityIndex === -1 ? 0 : entityIndex;

            $state.go($scope.detailsState || $state.current.name,
                {
                    id: $scope.visibleItems[entityIndex]._id,
                    entity: context.entityName,
                    entityId: context.entityId,
                    nameFocused: true
                })
        }
    };

    function setStatusFilterValue(value){
      let newActiveToggleField;
      if(!value)value = 'all';
      if(['new', 'assigned', 'in-progress', 'review'].includes(value))newActiveToggleField = 'active';
      if(['rejected', 'done', 'archived', 'canceled', 'done'].includes(value))newActiveToggleField = 'nonactive';

      if(newActiveToggleField)$scope.activeToggle.field = newActiveToggleField;
    }

    setStatusFilterValue($stateParams.status);
    $scope.refreshVisibleItems();
    $scope.checkForInactiveEntity();

    function filterResults(itemsArray){
        let newArray = $filter('filterRecycled')(itemsArray);
        newArray = $filter('filterByOptions')(newArray);
        newArray = $filter('filterByActiveStatus')(newArray, $scope.activeToggle.field);
        if($stateParams.filterStatus)newArray = filterByDefiniteStatus(newArray, $stateParams.filterStatus);
        // if($stateParams.entity)newArray = filterByParent(newArray, $stateParams.entityId);
        newArray = $filter('orderBy')(newArray, $scope.sorting.field, $scope.sorting.isReverse);

        return newArray;
    }

    function removeDuplicates(array) {
      return _.uniq(array, _.property('_id'));
    }

    function filterByDefiniteStatus(array, value){
      return array.filter( entity => entity.status === value);
    }

    function filterByParent(array, value) {
      return array.filter(entity => {
        let parent = entity[$stateParams.entity];
        return parent && (value === parent || value === parent._id);
      });
    }

    NotifyingService.subscribe('filterMyTasks', () => $scope.refreshVisibleItems(), $scope);
    $scope.$on('refreshList', () => $scope.refreshVisibleItems());

    // ============================================================= //
    // ======================== Permissions ======================== //
    // ============================================================= //

    $scope.me = {};
    UsersService.getMe().then(function(me) {
        $scope.me = me;
    });

    $scope.recycled = entity => entity && entity.hasOwnProperty('recycled');
    $scope.havePermissions = (entity, type) => PermissionsService.havePermissions(entity, type);
    $scope.haveEditiorsPermissions = entity => PermissionsService.haveEditorsPerms(entity);
    $scope.permsToSee = entity => PermissionsService.haveAnyPerms(entity)
}

angular.module('mean.icu.ui.entityList', ['dragularModule']).controller('EntityListController', EntityListController);
<commit_msg>Fix - Main menu ICU button bug<commit_after>'use strict';

/**
 * @desc order directive that is specific to the order module at a company named Acme
 * @example

 */

function EntityListController($scope, $window, $state, context, $filter, $stateParams, EntityService, dragularService, $element, $interval, $uiViewScroll, $timeout, LayoutService, UsersService, TasksService, PermissionsService, MultipleSelectService, NotifyingService) {

    // ============================================================= //
    // ========================= navigate ========================== //
    // ============================================================= //
    $scope.unifiedRowTpl = '/icu/components/entity-list/regions/row.html';

    $scope.isCurrentEntityState = function(id) {
        return $state.current.name.indexOf(`main.${$scope.$parent.entityName}.byentity`) === 0 && $state.current.name.indexOf('details') === -1;
    }

    let possibleNavigate = $scope.$parent.items.filter( t => t.recycled == null );

    if (possibleNavigate.length) {
        function navigateToDetails(item) {
            if (!item)
                return;

            $scope.detailsState = context.entityName === 'all' ? `main.${$scope.$parent.entityName}.all.details` : `main.${$scope.$parent.entityName}.byentity.details`;

            $state.go($scope.detailsState, {
                id: item._id,
                entity: context.entityName,
                entityId: context.entityId,
            });
        }
        if ($state.current.name === `main.${$scope.$parent.entityName}.all` || $state.current.name === `main.${$scope.$parent.entityName}.byentity` || $state.current.name === `main.${$scope.$parent.entityName}.all.details.${window.config.defaultTab}` || $state.current.name === `main.${$scope.$parent.entityName}.byentity.details.${window.config.defaultTab}`) {
            var date = new Date();
            var lastIndex = possibleNavigate.length - 1;
            var diff = date.getTime() - new Date(possibleNavigate[lastIndex].created).getTime();
            if (possibleNavigate[lastIndex].title == "" && diff <= 2500) {
                navigateToDetails(possibleNavigate[lastIndex]);
            } else {
                navigateToDetails(possibleNavigate[0]);
            }
        }
    } else {
        if ($state.current.name == `main.${$scope.$parent.entityName}.all.details.${window.config.defaultTab}`) {
            $state.go(`main.${$scope.$parent.entityName}.all`);
        }
    }

   if (context.entityName === 'all') {
        $scope.detailsState = `main.${$scope.$parent.entityName}.all.details`;
    } else if (context.entityName === 'my') {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byassign.details`;
    } else if (
      (context.entityName === 'task' || context.entityName === 'project')
     && $state.current.name.indexOf('byparent') !== -1) {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byparent.details`;
    } else {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byentity.details`;
    }

    var isScrolled = false;

    $scope.seenSelectedItem = false;
    $scope.isCurrentState = isCurrentState();
    $scope.isCurrentEntity = function(id){
        let currentSelected = $state.params.id === id;

        if(currentSelected)
            $scope.seenSelectedItem = true;
        return currentSelected
    };

    function isCurrentState() {
        let currentState = postfix => $state.current.name.indexOf(`main.${$scope.$parent.entityName}${postfix}`) === 0;
        let isActive = (
          currentState('.byparent.details') || currentState('.byentity.details') ||
          currentState('.all.details')
        );
        if (isActive && !isScrolled) {
            isScrolled = true;
        }
        return isActive;
    }

    $scope.$watch('seenSelectedItem', newValue => {
      if(newValue)$timeout(() => scrollToElement(), 0);
    });

    function scrollToElement(){
        let list = document.getElementsByClassName('list-table scroll')[0],
            elem = document.querySelector('tr.active');
        if(!list && !elem)return;

        let listBottom = list.scrollTop + list.offsetHeight,
            elementBottom = elem.offsetTop + elem.offsetHeight;
        // if(elementBottom > listBottom)list.scrollTop = elem.offsetTop;
        if(elementBottom > listBottom)
            elem.scrollIntoView({ behavior: 'smooth' });

    }

    // ============================================================= //
    // ========================== filters ========================== //
    // ============================================================= //

    $scope.print = function() {
        $window.print()
    };

    $scope.starred = $stateParams.starred;

    $scope.activeToggleList = EntityService.activeToggleList;
    $scope.activeToggle = {
        field: !EntityService.isActiveStatusAvailable() ? 'all' : $stateParams.activeToggle || 'active',
        disabled: !EntityService.isActiveStatusAvailable()
    };

    $scope.changeOrder = function() {
        if ($scope.sorting.field != "custom") {
            $scope.sorting.isReverse = !$scope.sorting.isReverse;
        }

        $scope.refreshVisibleItems();

        /*Made By OHAD - Needed for reversing sort*/
        $state.go($state.current.name, {
            sort: $scope.sorting.field
        });

        $scope.refreshVisibleItems();
    };

    $scope.sorting = {
        field: $stateParams.sort || 'created',
        isReverse: false
    };

    $scope.sortingList = [{
        title: 'title',
        value: 'title'
    }, {
        title: 'status',
        value: 'status'
    }, {
        title: 'created',
        value: 'created'
    }, {
      title: 'bolded',
      value: 'bolded.bolded'
    }];

    if (context.entityName != "all") {
        $scope.sortingList.push({
            title: 'custom',
            value: 'custom'
        });
    }

    $scope.toggleStarred = function() {
        $state.go($state.current.name, {
            starred: !$stateParams.starred
        });
    };

    $scope.filterActive = function() {
        EntityService.activeStatusFilterValue = $scope.activeToggle.field;
        $state.go($state.current.name, {
            activeToggle: $scope.activeToggle.field
        });
    };

    // ============================================================= //
    // =========================== list ============================ //
    // ============================================================= //

    $scope.context = context;
    $scope.isLoading = true;

    let inCurrentEntity = (entity)=> $state.current.name.indexOf(entity) !== -1;

    $scope.showTaskExcel = inCurrentEntity('tasks')
    $scope.showOfficeDocumentsExcel = inCurrentEntity('offices');

    let tasksExcelHandler = TasksService.excel;
    $scope.taskExcel = tasksExcelHandler;
    $scope.excel = {
        selected:{title:""},
        officeList:_.filter($scope.offices,(office)=>office.title&&office.title!=="")
    };

    $scope.onClickRow = function($event, item) {
        if ($scope.displayOnly) {
            return;
        }

        var nameFocused = angular.element($event.target).hasClass('name');

        $state.go($scope.detailsState + '.' + window.config.defaultTab, {
            id: item._id,
            entity: context.entityName,
            entityId: context.entityId,
            nameFocused: nameFocused
        });

        LayoutService.clicked();
    };

    $scope.onCreate = function() {
        if ($state.current.name.indexOf("byentity") !== -1 || $state.current.name.indexOf("byparent") !== -1) {
            var parent = {};
            parent.type = $state.current.params.entity || 'parent';
            parent.id = $state.current.params.entityId;
        }
        $scope.$parent.create(parent).then((result)=>{
            $scope.refreshVisibleItems();
            $timeout(()=> {
              let lastElementIndex = $element.find('td.name').length - 1;
              let currentElement = $element.find('td.name').get(lastElementIndex - 1);
              let nextElement = $element.find('td.name').get(lastElementIndex);

              let focusedElement = currentElement && nextElement;
              focusedElement.focus();
            },100);
            $state.go($scope.detailsState + '.' + window.config.defaultTab, {
                id: result._id,
                entity: context.entityName,
                entityId: context.entityId,
                nameFocused: true
            });
            //             }

        }
        );
    };

    // ============================================================= //
    // =================== multiple operations ===================== //
    // ============================================================= //

    $scope.mouseOnMultiple = false;
    $scope.multipleSelectMode = false;
    $scope.selectedItems = MultipleSelectService.refreshSelectedList();
    $scope.cornerState = MultipleSelectService.getCornerState();
    NotifyingService.notify('multipleDisableDetailsPaneCheck');

    $scope.multipleSelectRefreshSelected = function (entity) {
        MultipleSelectService.refreshSelectedList(entity);
        multipleSelectRefreshState();
    };

    $scope.$on('changeCornerState', (event, cornerState) => multipleSelectSetAllSelected(cornerState === 'all'));

    function multipleSelectSetAllSelected(status){
        for(let i = 0; i < $scope.visibleItems.length; i++){
            let row = $scope.visibleItems[i];

            if(!row.selected)MultipleSelectService.refreshSelectedList(row);
            row.selected = status;
        }
        if(status){
            MultipleSelectService.setSelectedList($scope.visibleItems);
        } else {
            MultipleSelectService.refreshSelectedList();
        }
        multipleSelectRefreshState();
    }

    NotifyingService.subscribe('refreshAfterOperation', () => {
        multipleSelectRefreshState();
        $scope.refreshVisibleItems();
    }, $scope);

    $scope.cursorEnterMultiple = function(mouseOn){ $scope.mouseOnMultiple = !!mouseOn };
    $scope.showTick = function(item){ item.visible = true };
    $scope.hideTick = function(item){ item.visible = false };

    $scope.checkForHideMultiple = function(){
        if(MultipleSelectService.getCornerState() === 'none'){
            changeMultipleMode(false);
        }
    };

    function multipleSelectRefreshState(){
        $scope.selectedItems = getFilteredSelectedList();
        refreshActiveItemsInList();
        $scope.cornerState = getRefreshedCornerState();

        if ($scope.selectedItems.length) {
            changeMultipleMode(true);
        } else {
            MultipleSelectService.refreshSelectedList();
        }

        multipleDisablingCheck();
        $scope.$broadcast('refreshBulkButtonsAccess');
        NotifyingService.notify('multipleDisableDetailsPaneCheck');
    }

    function multipleDisablingCheck(){
        if(!$scope.selectedItems.length && !$scope.mouseOnMultiple){
            changeMultipleMode(false);
        }
    }

    function changeMultipleMode(value){
        $scope.multipleSelectMode = value;
    }

    function getFilteredSelectedList(){
        let selected = MultipleSelectService.getSelected(),
            filteredSelected = filterResults(selected),
            newSelectedList = MultipleSelectService.setSelectedList(filteredSelected);

        return newSelectedList;
    }

    function getRefreshedCornerState(){
        return MultipleSelectService.refreshCornerState(filterResults($scope.visibleItems).length);
    }

    function refreshActiveItemsInList(){
        for(let item of $scope.visibleItems){
            let entity = $scope.selectedItems.find( selectedItems => selectedItems._id === item._id );
            item.selected = !!entity;
        }
    }

    // ============================================================= //
    // ======================= item function ======================= //
    // ============================================================= //

    $scope.onKeydown = function($event, index) {
        angular.element($event.target).css('box-shadow', 'none');

        if ($event.keyCode === 13) {
            $event.preventDefault();
            let nextElementCreated = $scope.items[index + 1];
            let nextElementInDOM = $element.find('td.name').get(index + 1);

            if (nextElementCreated && nextElementInDOM) {
                $state.go($scope.detailsState + '.' + window.config.defaultTab, {
                    id: $scope.items[index + 1]._id,
                    entity: context.entityName,
                    entityId: context.entityId,
                    nameFocused: true
                });
                nextElementInDOM.focus();
            } else {
                $scope.onCreate();
            }
            //             var sr = $scope.searchResults[$scope.selectedSuggestion];
            //              $scope.select(sr);
        }
    }
    $scope.focusing = function(entity){
        entity.focus = true;
    };
    $scope.bluring = function(entity, $event){
        entity.focus = false;

        var scrollLeft = function(element){
            element.scrollLeft = 0;
        };
        var scrollRight = function(element){
            element.scrollLeft += $event.target.scrollWidth - $event.target.scrollLeft;
        };

        let usingFunction = config.direction === 'rtl' ? scrollRight : scrollLeft;
        usingFunction($event.target);
    };

    //     $scope.onBlur = function(item) {
    //         item.__autocomplete = false;
    //         $scope.searchResults.length = 0;
    //         $scope.selectedSuggestion = 0;
    //     }

    // infinite scroll
    //     $timeout(function() {
    $scope.displayLimit = Math.ceil($element.height() / 50);
    $scope.isLoading = false;
    //     }, 0);

    $scope.loadMore = function() {
        var LIMIT = 25;
        let loadedVisibleCount = 0;
        let listEnd = false;

        loadWithVisibleCheck(listEnd, loadedVisibleCount);

        function loadWithVisibleCheck(listEnd, loadedVisibleCount) {
            if (!$scope.isLoading) {
                if (loadedVisibleCount < 25 && !listEnd) {
                    var start = $scope.items.length;
                    var sort = 'created';
                    //$scope.order.field;
                    $scope.$parent.loadMore(start, LIMIT, sort).then(result => {
                        if (result.length === 0) listEnd = true;
                        loadedVisibleCount += filterResults(result).length;
                        $scope.refreshVisibleItems();
                        loadWithVisibleCheck(listEnd, loadedVisibleCount);
                    })
                }
            }
        }
    };

    $scope.refreshVisibleItems = function() {
        $scope.visibleItems = removeDuplicates(filterResults($scope.items))
    };

    $scope.checkForInactiveEntity = () => {
        if($scope.visibleItems.length && $stateParams.id) {
            let entityIndex = $scope.visibleItems.findIndex( item => item._id === $stateParams.id );
            entityIndex = entityIndex === -1 ? 0 : entityIndex;

            $state.go($scope.detailsState || $state.current.name,
                {
                    id: $scope.visibleItems[entityIndex]._id,
                    entity: context.entityName,
                    entityId: context.entityId,
                    nameFocused: true
                })
        }
    };

    function setStatusFilterValue(value){
      let newActiveToggleField;
      if(!value)value = 'all';
      if(['new', 'assigned', 'in-progress', 'review'].includes(value))newActiveToggleField = 'active';
      if(['rejected', 'done', 'archived', 'canceled', 'done'].includes(value))newActiveToggleField = 'nonactive';

      if(newActiveToggleField)$scope.activeToggle.field = newActiveToggleField;
    }

    setStatusFilterValue($stateParams.status);
    $scope.refreshVisibleItems();
    $scope.checkForInactiveEntity();

    function filterResults(itemsArray){
        let newArray = $filter('filterRecycled')(itemsArray);
        newArray = $filter('filterByOptions')(newArray);
        newArray = $filter('filterByActiveStatus')(newArray, $scope.activeToggle.field);
        if($stateParams.filterStatus)newArray = filterByDefiniteStatus(newArray, $stateParams.filterStatus);
        // if($stateParams.entity)newArray = filterByParent(newArray, $stateParams.entityId);
        newArray = $filter('orderBy')(newArray, $scope.sorting.field, $scope.sorting.isReverse);

        return newArray;
    }

    function removeDuplicates(array) {
      return _.uniq(array, _.property('_id'));
    }

    function filterByDefiniteStatus(array, value){
      return array.filter( entity => entity.status === value);
    }

    function filterByParent(array, value) {
      return array.filter(entity => {
        let parent = entity[$stateParams.entity];
        return parent && (value === parent || value === parent._id);
      });
    }

    NotifyingService.subscribe('filterMyTasks', () => $scope.refreshVisibleItems(), $scope);
    $scope.$on('refreshList', () => $scope.refreshVisibleItems());

    // ============================================================= //
    // ======================== Permissions ======================== //
    // ============================================================= //

    $scope.me = {};
    UsersService.getMe().then(function(me) {
        $scope.me = me;
    });

    $scope.recycled = entity => entity && entity.hasOwnProperty('recycled');
    $scope.havePermissions = (entity, type) => PermissionsService.havePermissions(entity, type);
    $scope.haveEditiorsPermissions = entity => PermissionsService.haveEditorsPerms(entity);
    $scope.permsToSee = entity => PermissionsService.haveAnyPerms(entity)
}

angular.module('mean.icu.ui.entityList', ['dragularModule']).controller('EntityListController', EntityListController);
<|endoftext|>


<commit_before>var count1 = 0;
var count2 = 0;

window.onload = function() {
	var tabs = $$(".tab");
	for (var i = 0;i < tabs.length;i++) {
		tabs[i].onclick = switchTab;
	}
	if (BrowserDetect.OS == "Win") {
		$("win").src = "{{ MEDIA URL }}bigwin.jpg";
	} else if (BrowserDetect.OS == "Mac") {
		$("osx").src = "{{ MEDIA URL }}bigosx.jpg";
	} else if (BrowserDetect.OS == "Linux") {
		$("linux").src = "{{ MEDIA URL }}biglinux.jpg";
	} else {
	}
	$("checkAll").onclick = checkAll;
	var count = tally();
	$("maximizer1").textContent = "+" + "   " + count1 + " Machines";
	$("maximizer2").textContent = "+" + "   " + count2 + " Machines";
	try { if(!maximizer1.innerText) maximizer1.innerText = maximizer1.textContent; } catch(e) {}
	try { if(!maximizer2.innerText) maximizer2.innerText = maximizer2.textContent; } catch(e) {}
	$("maximizer1").onclick = table1unhide;
	$("maximizer2").onclick = table2unhide;
};

function table1unhide() {
	$("table1").display = "block";
	$("maximizer1").textContent = "-" + "   " + count1 + " Machines";
	try { if(!maximizer1.innerText) maximizer1.innerText = maximizer1.textContent; } catch(e) {}
	$("maximizer1").onclick = function() {
		$("maximizer1").display = "none";
		$("maximizer1").textContent = "+" + "   " + count1 + " Machines";
		try { if(!maximizer1.innerText) maximizer1.innerText = maximizer1.textContent; } catch(e) {}
		$("maximizer1").onclick = table1unhide();
	}
}

function table2unhide() {
	$("sharedResources").display = "block";
	$("maximizer2").textContent = "-" + "   " + count2 + " Machines";
	try { if(!maximizer2.innerText) maximizer2.innerText = maximizer2.textContent; } catch(e) {}
	$("maximizer2").onclick = function() {
		$("sharedResources").display = "none";
		$("maximizer2").textContent = "+" + "   " + count2 + " Machines";
		try { if(!maximizer2.innerText) maximizer2.innerText = maximizer2.textContent; } catch(e) {}
		$("maximizer2").onclick = table1unhide();
	}
}

function tally() {
	var list1 = $$(".table1row");
	var list2 = $$(".table2row");
	for (var i = 0;i < list1.length;i++) {
		count1++;
	}
	for (var j = 0;j < list2.length;j++) {
		count2++;
	}
}

function switchTab() {
	var index = (Number)(this.id[3]);
	var windows = $$(".window");
	var tabs = $$(".tab");
	for (var i = 0;i < windows.length;i++) {
		windows[i].style.display = "none";
		tabs[i].removeClassName("highlighted");
	}
	$("window" + index).style.display = "block";
	this.addClassName("highlighted");

}

function checkAll() {
	var checkboxes = $$("check");
	for (var i = 0;i < checkboxes.length;i++) {
		checkboxes[i].checked = "true";
	}
}

/*Free online downloaded script that can return OS, Browser Name, and Browser Version, used for browser compatibility purposes*/
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();<commit_msg>MORE BUG FIXES!<commit_after>var count1 = 0;
var count2 = 0;

window.onload = function() {
	var tabs = $$(".tab");
	for (var i = 0;i < tabs.length;i++) {
		tabs[i].onclick = switchTab;
	}
	if (BrowserDetect.OS == "Win") {
		$("win").src = "{{ MEDIA URL }}bigwin.jpg";
	} else if (BrowserDetect.OS == "Mac") {
		$("osx").src = "{{ MEDIA URL }}bigosx.jpg";
	} else if (BrowserDetect.OS == "Linux") {
		$("linux").src = "{{ MEDIA URL }}biglinux.jpg";
	} else {
	}
	$("checkAll").onclick = checkAll;
	var count = tally();
	$("maximizer1").textContent = "+" + "   " + count1 + " Machines";
	$("maximizer2").textContent = "+" + "   " + count2 + " Machines";
	try { if(!maximizer1.innerText) maximizer1.innerText = maximizer1.textContent; } catch(e) {}
	try { if(!maximizer2.innerText) maximizer2.innerText = maximizer2.textContent; } catch(e) {}
	$("maximizer1").onclick = table1unhide;
	$("maximizer2").onclick = table2unhide;
};

function table1unhide() {
	$("table1").style.display = "block";
	$("maximizer1").textContent = "-" + "   " + count1 + " Machines";
	try { if(!maximizer1.innerText) maximizer1.innerText = maximizer1.textContent; } catch(e) {}
	$("maximizer1").onclick = function() {
		$("maximizer1").style.display = "none";
		$("maximizer1").textContent = "+" + "   " + count1 + " Machines";
		try { if(!maximizer1.innerText) maximizer1.innerText = maximizer1.textContent; } catch(e) {}
		$("maximizer1").onclick = table1unhide();
	}
}

function table2unhide() {
	$("sharedResources").style.display = "block";
	$("maximizer2").textContent = "-" + "   " + count2 + " Machines";
	try { if(!maximizer2.innerText) maximizer2.innerText = maximizer2.textContent; } catch(e) {}
	$("maximizer2").onclick = function() {
		$("sharedResources").style.display = "none";
		$("maximizer2").textContent = "+" + "   " + count2 + " Machines";
		try { if(!maximizer2.innerText) maximizer2.innerText = maximizer2.textContent; } catch(e) {}
		$("maximizer2").onclick = table1unhide();
	}
}

function tally() {
	var list1 = $$(".table1row");
	var list2 = $$(".table2row");
	for (var i = 0;i < list1.length;i++) {
		count1++;
	}
	for (var j = 0;j < list2.length;j++) {
		count2++;
	}
}

function switchTab() {
	var index = (Number)(this.id[3]);
	var windows = $$(".window");
	var tabs = $$(".tab");
	for (var i = 0;i < windows.length;i++) {
		windows[i].style.display = "none";
		tabs[i].removeClassName("highlighted");
	}
	$("window" + index).style.display = "block";
	this.addClassName("highlighted");

}

function checkAll() {
	var checkboxes = $$("check");
	for (var i = 0;i < checkboxes.length;i++) {
		checkboxes[i].checked = "true";
	}
}

/*Free online downloaded script that can return OS, Browser Name, and Browser Version, used for browser compatibility purposes*/
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();<|endoftext|>


<commit_before>const nexe = require('nexe');
const fs = require('fs');
const path = require('path');
const os = require('os');
const zlib = require('zlib');
const embed = require('./embed');

const nodeVersion = '8.5.0';

function getDirContents(dir, accumPath = dir) {
  let filenames = fs.readdirSync(dir);

  return filenames.reduce((ret, filename) => {
    const fname = path.resolve(accumPath, filename);
    const fStat = fs.statSync(fname);

    if (fStat.isDirectory()) {
      const newAccum = path.join(accumPath, filename);
      return ret.concat(getDirContents(newAccum, newAccum));
    }

    ret.push(path.join(accumPath, filename));
    return ret;
  }, []);
}

function deflate(fname) {
  return new Promise((resolve, reject) => {
    fs.readFile(fname, (err, input) => {
      fs.writeFileSync(fname, zlib.deflateSync(input));
      resolve();
    });
  });
}

const outputPath = `build/${/^Windows/.test(os.type()) ? 'lumo.exe' : 'lumo'}`;
const resources = getDirContents('target').filter(
  fname =>
    fname.endsWith('.aot.js.map') ||
    (!fname.endsWith('main.js') &&
      !fname.endsWith('bundle.js') &&
      !fname.endsWith('bundle.min.js') &&
      !fname.endsWith('google-closure-compiler-js.js') &&
      !fname.endsWith('aot.edn') &&
      !/target[\\\/]cljs[\\/]core.js/.test(fname) &&
      !fname.endsWith('.map')),
);

function moveLibs(compiler, options, callback) {
  fs.writeFileSync(
    `${compiler.dir}/google-closure-compiler-js.js`,
    fs.readFileSync(`target/google-closure-compiler-js.js`),
  );

  callback();
}

Promise.all(resources.map(deflate)).then(() => {
  embed(resources, 'target');

  nexe.compile(
    {
      input: 'target/bundle.min.js',
      output: outputPath,
      nodeTempDir: 'tmp',
      patchFns: moveLibs,
      nodeConfigureArgs: [
        '--without-dtrace',
        '--without-npm',
        '--without-inspector',
        '--without-etw',
        '--without-perfctr',
        '--with-snapshot',
        '--link-module',
        'google-closure-compiler-js.js',
      ],
      nodeMakeArgs: ['-j', '8'],
      nodeVCBuildArgs: ['nosign', 'x64', 'noetw', 'noperfctr'],
      flags: true,
      startupSnapshot: 'target/main.js',
      noBundle: true,
      framework: 'node',
      nodeVersion,
    },
    err => {
      if (err) {
        throw err;
      }
      console.log(
        `Finished bundling. Nexe binary can be found in ${outputPath}`,
      );
    },
  );
});
<commit_msg>more serious attempt to have Closure in Windows builds<commit_after>const nexe = require('nexe');
const monkeyPatch = require('nexe/lib/monkeypatch');
const fs = require('fs');
const path = require('path');
const os = require('os');
const zlib = require('zlib');
const embed = require('./embed');

const nodeVersion = '8.5.0';

function getDirContents(dir, accumPath = dir) {
  let filenames = fs.readdirSync(dir);

  return filenames.reduce((ret, filename) => {
    const fname = path.resolve(accumPath, filename);
    const fStat = fs.statSync(fname);

    if (fStat.isDirectory()) {
      const newAccum = path.join(accumPath, filename);
      return ret.concat(getDirContents(newAccum, newAccum));
    }

    ret.push(path.join(accumPath, filename));
    return ret;
  }, []);
}

function deflate(fname) {
  return new Promise((resolve, reject) => {
    fs.readFile(fname, (err, input) => {
      fs.writeFileSync(fname, zlib.deflateSync(input));
      resolve();
    });
  });
}

const outputPath = `build/${/^Windows/.test(os.type()) ? 'lumo.exe' : 'lumo'}`;
const resources = getDirContents('target').filter(
  fname =>
    fname.endsWith('.aot.js.map') ||
    (!fname.endsWith('main.js') &&
      !fname.endsWith('bundle.js') &&
      !fname.endsWith('bundle.min.js') &&
      !fname.endsWith('google-closure-compiler-js.js') &&
      !fname.endsWith('aot.edn') &&
      !/target[\\\/]cljs[\\/]core.js/.test(fname) &&
      !fname.endsWith('.map')),
);

function moveLibs(compiler, options, callback) {
  fs.writeFileSync(
    `${compiler.dir}/google-closure-compiler-js.js`,
    fs.readFileSync(`target/google-closure-compiler-js.js`),
  );

  callback(null, compiler, options);
}

function patchNodeGyp(compiler, options, callback) {
  const gypPath = path.join(compiler.dir, 'node.gyp');

  monkeyPatch(
    gypPath,
    function(content) {
      return ~content.indexOf('google-closure-compiler-js.js');
    },
    function(content, next) {
      const newContent = content.replace(
        "'deps/node-inspect/lib/internal/inspect_repl.js',",
        `'deps/node-inspect/lib/internal/inspect_repl.js',
      'google-closure-compiler-js.js',`,
      );
      next(null, newContent);
    },
    callback,
  );
}

Promise.all(resources.map(deflate)).then(() => {
  embed(resources, 'target');

  nexe.compile(
    {
      input: 'target/bundle.min.js',
      output: outputPath,
      nodeTempDir: 'tmp',
      patchFns: [moveLibs, patchNodeGyp],
      nodeConfigureArgs: [
        '--without-dtrace',
        '--without-npm',
        '--without-inspector',
        '--without-etw',
        '--without-perfctr',
        '--with-snapshot',
      ],
      nodeMakeArgs: ['-j', '8'],
      nodeVCBuildArgs: ['nosign', 'x64', 'noetw', 'noperfctr'],
      flags: true,
      startupSnapshot: 'target/main.js',
      noBundle: true,
      framework: 'node',
      nodeVersion,
    },
    err => {
      if (err) {
        throw err;
      }
      console.log(
        `Finished bundling. Nexe binary can be found in ${outputPath}`,
      );
    },
  );
});
<|endoftext|>


<commit_before>/*
 *  The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 The Regents of the University of California
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
 * following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

/**
 * Created by dat on 3/21/17.
 */
var hic = (function (hic) {

    var labels =
    {
        NONE: 'None',
        VC: 'Coverage',
        VC_SQRT: 'Coverage - Sqrt',
        KR: 'Balanced',
        INTER_VC: 'Interchromosomal Coverage',
        INTER_VC_SQRT: 'Interchromosomal Coverage - Sqrt',
        INTER_KR: 'Interchromosomal Balanced',
        GW_VC: 'Genome-wide Coverage',
        GW_VC_SQRT: 'Genome-wide Coverage - Sqrt',
        GW_KR: 'Genome-wide Balanced'
    };

    hic.NormalizationWidget = function (browser, $parent) {
        var self = this,
            $label;

        this.browser = browser;

        // container
        this.$container = $('
');
        $parent.append(this.$container);

        // label
        $label = $('
');
        $label.text( (true === browser.config.miniMode) ? 'Normalization' : 'Norm.');
        this.$container.append($label);

        // select
        this.$normalization_selector = $('<select name="select">');
        this.$normalization_selector.attr('name', 'normalization_selector');
        this.$normalization_selector.on('change', function (e) {
            self.browser.setNormalization($(this).val());
        });
        this.$container.append(this.$normalization_selector);

        // spinner
        this.$spinner = $('
');
        this.$spinner.text('Loading ...');
        this.$container.append(this.$spinner);
        this.$spinner.hide();

        this.browser.eventBus.subscribe("MapLoad", this);
        this.browser.eventBus.subscribe("NormVectorIndexLoad", this);
        this.browser.eventBus.subscribe("NormalizationFileLoad", this);

    };

    hic.NormalizationWidget.prototype.startNotReady = function () {
        this.$normalization_selector.hide();
        this.$spinner.show();
    };

    hic.NormalizationWidget.prototype.stopNotReady = function () {
        this.$spinner.hide();
        this.$normalization_selector.show();
    };

    hic.NormalizationWidget.prototype.receiveEvent = function (event) {

        function updateOptions() {
            var dataset = event.data,
                normalizationTypes,
                elements,
                norm = this.browser.state.normalization;

            normalizationTypes = dataset.normalizationTypes;
            elements = _.map(normalizationTypes, function (normalization) {
                var label,
                    labelPresentation,
                    isSelected,
                    titleString,
                    valueString;

                label = labels[normalization] || normalization;
                isSelected = (norm === normalization);
                titleString = (label === undefined ? '' : ' title = "' + label + '" ');
                valueString = ' value=' + normalization + (isSelected ? ' selected' : '');

                labelPresentation = '&nbsp &nbsp' + label + '&nbsp &nbsp';
                return '<option' + titleString + valueString + '>' + labelPresentation + '</option>';
            });

            this.$normalization_selector.empty();
            this.$normalization_selector.append(elements.join(''));
        }

        if ("MapLoad" === event.type) {
            // TODO -- start norm widget "not ready" state
            this.startNotReady();

            updateOptions.call(this);

        } else if ("NormVectorIndexLoad" === event.type) {

            updateOptions.call(this);

            // TODO -- end norm widget "not ready" state
            this.stopNotReady();

        } else if ("NormalizationFileLoad" === event.type) {
            if(event.data === "start") {
                this.startNotReady();
            } else {
                this.stopNotReady();
            }
        }
    };

    return hic;

})
(hic || {});
<commit_msg>label tweak<commit_after>/*
 *  The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 The Regents of the University of California
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
 * following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

/**
 * Created by dat on 3/21/17.
 */
var hic = (function (hic) {

    var labels =
    {
        NONE: 'None',
        VC: 'Coverage',
        VC_SQRT: 'Coverage - Sqrt',
        KR: 'Balanced',
        INTER_VC: 'Interchromosomal Coverage',
        INTER_VC_SQRT: 'Interchromosomal Coverage - Sqrt',
        INTER_KR: 'Interchromosomal Balanced',
        GW_VC: 'Genome-wide Coverage',
        GW_VC_SQRT: 'Genome-wide Coverage - Sqrt',
        GW_KR: 'Genome-wide Balanced'
    };

    hic.NormalizationWidget = function (browser, $parent) {
        var self = this,
            $label;

        this.browser = browser;

        // container
        this.$container = $('
');
        $parent.append(this.$container);

        // label
        $label = $('
');
        $label.text( (true === browser.config.miniMode) ? 'Normalization' : 'Norm');
        this.$container.append($label);

        // select
        this.$normalization_selector = $('<select name="select">');
        this.$normalization_selector.attr('name', 'normalization_selector');
        this.$normalization_selector.on('change', function (e) {
            self.browser.setNormalization($(this).val());
        });
        this.$container.append(this.$normalization_selector);

        // spinner
        this.$spinner = $('
');
        this.$spinner.text('Loading ...');
        this.$container.append(this.$spinner);
        this.$spinner.hide();

        this.browser.eventBus.subscribe("MapLoad", this);
        this.browser.eventBus.subscribe("NormVectorIndexLoad", this);
        this.browser.eventBus.subscribe("NormalizationFileLoad", this);

    };

    hic.NormalizationWidget.prototype.startNotReady = function () {
        this.$normalization_selector.hide();
        this.$spinner.show();
    };

    hic.NormalizationWidget.prototype.stopNotReady = function () {
        this.$spinner.hide();
        this.$normalization_selector.show();
    };

    hic.NormalizationWidget.prototype.receiveEvent = function (event) {

        function updateOptions() {
            var dataset = event.data,
                normalizationTypes,
                elements,
                norm = this.browser.state.normalization;

            normalizationTypes = dataset.normalizationTypes;
            elements = _.map(normalizationTypes, function (normalization) {
                var label,
                    labelPresentation,
                    isSelected,
                    titleString,
                    valueString;

                label = labels[normalization] || normalization;
                isSelected = (norm === normalization);
                titleString = (label === undefined ? '' : ' title = "' + label + '" ');
                valueString = ' value=' + normalization + (isSelected ? ' selected' : '');

                labelPresentation = '&nbsp &nbsp' + label + '&nbsp &nbsp';
                return '<option' + titleString + valueString + '>' + labelPresentation + '</option>';
            });

            this.$normalization_selector.empty();
            this.$normalization_selector.append(elements.join(''));
        }

        if ("MapLoad" === event.type) {
            // TODO -- start norm widget "not ready" state
            this.startNotReady();

            updateOptions.call(this);

        } else if ("NormVectorIndexLoad" === event.type) {

            updateOptions.call(this);

            // TODO -- end norm widget "not ready" state
            this.stopNotReady();

        } else if ("NormalizationFileLoad" === event.type) {
            if(event.data === "start") {
                this.startNotReady();
            } else {
                this.stopNotReady();
            }
        }
    };

    return hic;

})
(hic || {});
<|endoftext|>


<commit_before>var editor = CodeMirror(document.body, {
							lineNumbers: true,
							//styleActiveLine: true,
							matchBrackets: true,
							autofocus: true,
							gutters: ["CodeMirror-linenumbers", "breakpoints"],
							autoCloseBrackets: true,
							styleSelectedText: true
						});
var ternServer;

editor.setOption("theme", "solarized dark");
editor.setOption("indentUnit", 4);
editor.setOption("indentWithTabs", true);
editor.setOption("fullScreen", true);

editor.changeRegistered = false;
editor.breakpointsChangeRegistered = false;

editor.on("change", function(eMirror, object) {
	editor.changeRegistered = true;
});

var mac = /Mac/.test(navigator.platform);
if (mac === true) {
	editor.setOption("extraKeys", {
						 "Cmd-V": function(cm) {
							 cm.replaceSelection(clipboard);
						 },
						 "Cmd-X": function(cm) {
							 window.document.execCommand("cut");
						 },
						 "Cmd-C": function(cm) {
							 window.document.execCommand("copy");
						 }});
}

makeMarker = function() {
	var marker = document.createElement("div");
	marker.style.color = "#822";
	marker.innerHTML = "●";
	return marker;
};

toggleBreakpointLine = function(n) {
	var info = editor.lineInfo(n);
	editor.setGutterMarker(n, "breakpoints", info.gutterMarkers ? null : makeMarker());
	editor.breakpointsChangeRegistered = true;
}

editor.on("gutterClick", function(cm, n) {
	toggleBreakpointLine(n);
});

toggleBreakpoint = function() {
	var line = editor.getCursor().line;
	toggleBreakpointLine(line);
}

getTextChanged = function() {
	return editor.changeRegistered;
};

getText = function() {
	editor.changeRegistered = false;
	return editor.getValue();
};

getBreakpointsChanged = function() {
	return editor.changeRegistered || editor.breakpointsChangeRegistered;   //TODO: track new lines
};

getBreakpoints = function() {
	var locations = [];
	editor.breakpointsChangeRegistered = false;
	var doc = editor.doc;
	doc.iter(function(line) {
		if (line.gutterMarkers && line.gutterMarkers["breakpoints"]) {
			var l = doc.getLineNumber(line);
			locations.push({
							   start: editor.indexFromPos({ line: l, ch: 0}),
							   end: editor.indexFromPos({ line: l + 1, ch: 0})
						   });;
		}
	});
	return locations;
};

setTextBase64 = function(text) {
	editor.setValue(window.atob(text));
	editor.getDoc().clearHistory();
	editor.focus();
};

setText = function(text) {
	editor.setValue(text);
};

setMode = function(mode) {
	this.editor.setOption("mode", mode);

	if (mode === "javascript")
	{
		ternServer = new CodeMirror.TernServer({defs: [ ecma5Spec() ]});
		editor.setOption("extraKeys", {
							 "Ctrl-Space": function(cm) { ternServer.complete(cm); },
							 "Ctrl-I": function(cm) { ternServer.showType(cm); },
							 "Ctrl-O": function(cm) { ternServer.showDocs(cm); },
							 "Alt-.": function(cm) { ternServer.jumpToDef(cm); },
							 "Alt-,": function(cm) { ternServer.jumpBack(cm); },
							 "Ctrl-Q": function(cm) { ternServer.rename(cm); },
							 "Ctrl-.": function(cm) { ternServer.selectName(cm); },
							 "'.'": function(cm) { setTimeout(function() { ternServer.complete(cm); }, 100); throw CodeMirror.Pass; }
						 })
		editor.on("cursorActivity", function(cm) { ternServer.updateArgHints(cm); });
	}
	else if (mode === "solidity")
	{
		CodeMirror.commands.autocomplete = function(cm) {
			CodeMirror.showHint(cm, CodeMirror.hint.anyword);
		}
		editor.setOption("extraKeys", {
							 "Ctrl-Space": "autocomplete"
						 })
	}
};

setClipboardBase64 = function(text) {
	clipboard = window.atob(text);
};

var executionMark;
highlightExecution = function(start, end) {
	if (executionMark)
		executionMark.clear();
	if (start === 0 && end + 1 === editor.getValue().length)
		return; // Do not hightlight the whole document.
	if (debugWarning)
		debugWarning.clear();
	executionMark = editor.markText(editor.posFromIndex(start), editor.posFromIndex(end), { className: "CodeMirror-exechighlight" });
}

var changeId;
changeGeneration = function()
{
	changeId = editor.changeGeneration(true);
}

isClean = function()
{
	return editor.isClean(changeId);
}

var debugWarning = null;
showWarning = function(content)
{
	if (executionMark)
		executionMark.clear();
	if (debugWarning)
		debugWarning.clear();
	var node = document.createElement("div");
	node.id = "annotation"
	node.innerHTML = content;
	node.className = "CodeMirror-errorannotation-context";
	debugWarning = editor.addLineWidget(0, node, { coverGutter: false, above: true });
}

var annotation = null;
var compilationCompleteBool = true;
compilationError = function(line, column, content)
{
	compilationCompleteBool = false;
	window.setTimeout(function(){
		if (compilationCompleteBool)
			return;
		line = parseInt(line);
		column = parseInt(column);
		if (line > 0)
			line = line - 1;
		if (column > 0)
			column = column - 1;

		if (annotation == null)
			annotation = new ErrorAnnotation(editor, line, column, content);
		else if (annotation.line !== line || annotation.column !== column || annotation.content !== content)
		{
			annotation.destroy();
			annotation = new ErrorAnnotation(editor, line, column, content);
		}
	}, 500)
}

compilationComplete = function()
{
	if (annotation !== null)
	{
		annotation.destroy();
		annotation = null;
	}
	compilationCompleteBool = true;
}
<commit_msg>Mix: fixed editor clipboard for os x<commit_after>var editor = CodeMirror(document.body, {
							lineNumbers: true,
							//styleActiveLine: true,
							matchBrackets: true,
							autofocus: true,
							gutters: ["CodeMirror-linenumbers", "breakpoints"],
							autoCloseBrackets: true,
							styleSelectedText: true
						});
var ternServer;

editor.setOption("theme", "solarized dark");
editor.setOption("indentUnit", 4);
editor.setOption("indentWithTabs", true);
editor.setOption("fullScreen", true);

editor.changeRegistered = false;
editor.breakpointsChangeRegistered = false;

editor.on("change", function(eMirror, object) {
	editor.changeRegistered = true;
});

var mac = /Mac/.test(navigator.platform);
var extraKeys = {};
if (mac === true) {
	extraKeys["Cmd-V"] = function(cm) { cm.replaceSelection(clipboard); };
	extraKeys["Cmd-X"] = function(cm) { window.document.execCommand("cut"); };
	extraKeys["Cmd-C"] = function(cm) { window.document.execCommand("copy"); };
}

makeMarker = function() {
	var marker = document.createElement("div");
	marker.style.color = "#822";
	marker.innerHTML = "●";
	return marker;
};

toggleBreakpointLine = function(n) {
	var info = editor.lineInfo(n);
	editor.setGutterMarker(n, "breakpoints", info.gutterMarkers ? null : makeMarker());
	editor.breakpointsChangeRegistered = true;
}

editor.on("gutterClick", function(cm, n) {
	toggleBreakpointLine(n);
});

toggleBreakpoint = function() {
	var line = editor.getCursor().line;
	toggleBreakpointLine(line);
}

getTextChanged = function() {
	return editor.changeRegistered;
};

getText = function() {
	editor.changeRegistered = false;
	return editor.getValue();
};

getBreakpointsChanged = function() {
	return editor.changeRegistered || editor.breakpointsChangeRegistered;   //TODO: track new lines
};

getBreakpoints = function() {
	var locations = [];
	editor.breakpointsChangeRegistered = false;
	var doc = editor.doc;
	doc.iter(function(line) {
		if (line.gutterMarkers && line.gutterMarkers["breakpoints"]) {
			var l = doc.getLineNumber(line);
			locations.push({
							   start: editor.indexFromPos({ line: l, ch: 0}),
							   end: editor.indexFromPos({ line: l + 1, ch: 0})
						   });;
		}
	});
	return locations;
};

setTextBase64 = function(text) {
	editor.setValue(window.atob(text));
	editor.getDoc().clearHistory();
	editor.focus();
};

setText = function(text) {
	editor.setValue(text);
};

setMode = function(mode) {
	this.editor.setOption("mode", mode);

	if (mode === "javascript")
	{
		ternServer = new CodeMirror.TernServer({defs: [ ecma5Spec() ]});
		extraKeys["Ctrl-Space"] = function(cm) { ternServer.complete(cm); };
		extraKeys["Ctrl-I"] = function(cm) { ternServer.showType(cm); };
		extraKeys["Ctrl-O"] = function(cm) { ternServer.showDocs(cm); };
		extraKeys["Alt-."] = function(cm) { ternServer.jumpToDef(cm); };
		extraKeys["Alt-,"] = function(cm) { ternServer.jumpBack(cm); };
		extraKeys["Ctrl-Q"] = function(cm) { ternServer.rename(cm); };
		extraKeys["Ctrl-."] = function(cm) { ternServer.selectName(cm); };
		extraKeys["'.'"] = function(cm) { setTimeout(function() { ternServer.complete(cm); }, 100); throw CodeMirror.Pass; };
		editor.on("cursorActivity", function(cm) { ternServer.updateArgHints(cm); });
	}
	else if (mode === "solidity")
	{
		CodeMirror.commands.autocomplete = function(cm) {
			CodeMirror.showHint(cm, CodeMirror.hint.anyword);
		}
		extraKeys["Ctrl-Space"] = "autocomplete";
	}
};

setClipboardBase64 = function(text) {
	clipboard = window.atob(text);
};

var executionMark;
highlightExecution = function(start, end) {
	if (executionMark)
		executionMark.clear();
	if (start === 0 && end + 1 === editor.getValue().length)
		return; // Do not hightlight the whole document.
	if (debugWarning)
		debugWarning.clear();
	executionMark = editor.markText(editor.posFromIndex(start), editor.posFromIndex(end), { className: "CodeMirror-exechighlight" });
}

var changeId;
changeGeneration = function()
{
	changeId = editor.changeGeneration(true);
}

isClean = function()
{
	return editor.isClean(changeId);
}

var debugWarning = null;
showWarning = function(content)
{
	if (executionMark)
		executionMark.clear();
	if (debugWarning)
		debugWarning.clear();
	var node = document.createElement("div");
	node.id = "annotation"
	node.innerHTML = content;
	node.className = "CodeMirror-errorannotation-context";
	debugWarning = editor.addLineWidget(0, node, { coverGutter: false, above: true });
}

var annotation = null;
var compilationCompleteBool = true;
compilationError = function(line, column, content)
{
	compilationCompleteBool = false;
	window.setTimeout(function(){
		if (compilationCompleteBool)
			return;
		line = parseInt(line);
		column = parseInt(column);
		if (line > 0)
			line = line - 1;
		if (column > 0)
			column = column - 1;

		if (annotation == null)
			annotation = new ErrorAnnotation(editor, line, column, content);
		else if (annotation.line !== line || annotation.column !== column || annotation.content !== content)
		{
			annotation.destroy();
			annotation = new ErrorAnnotation(editor, line, column, content);
		}
	}, 500)
}

compilationComplete = function()
{
	if (annotation !== null)
	{
		annotation.destroy();
		annotation = null;
	}
	compilationCompleteBool = true;
}

editor.setOption("extraKeys", extraKeys);
<|endoftext|>