<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(function(t) {
        return 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.activities` || $state.current.name === `main.${$scope.$parent.entityName}.byentity.details.activities`) {
            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.activities`) {
            $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') {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byparent.details`;
    } else {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byentity.details`;
    }

    var isScrolled = false;

    $scope.isCurrentState = function(id) {
        var isActive = ($state.current.name.indexOf(`main.${$scope.$parent.entityName}.byparent.details`) === 0 || $state.current.name.indexOf(`main.${$scope.$parent.entityName}.byentity.details`) === 0 || $state.current.name.indexOf(`main.${$scope.$parent.entityName}.all.details`) === 0) && $state.params.id === id;
        if (isActive && !isScrolled) {
            //$uiViewScroll($element.find('[data-id="' + $stateParams.id + '"]'));
            isScrolled = true;
        }
        return isActive;
    };

    // ============================================================= //
    // ========================== 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;
        }

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

    $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 ============================ //
    // ============================================================= //

    var creatingStatuses = {
        NotCreated: 0,
        Creating: 1,
        Created: 2
    }

    $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 + '.activities', {
            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)=>{
            //             if (localStorage.getItem('type') == 'new') {
            //                 $state.go($scope.detailsState + '.activities', {
            //                     id: result._id,
            //                     entity: context.entityName,
            //                     entityId: context.entityId,
            //                     nameFocused: false,
            //                     officeDocuments
            //                 });
            //             } else {
            $scope.refreshVisibleItems();
            $timeout(()=> {
              let els = $element.find('td.name');
              els.length && els[els.length - 1].focus();
            },100);
            $state.go($scope.detailsState + '.activities', {
                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', function(event, cornerState){
        multipleSelectSetAllSelected(cornerState === 'all');
    });

    function multipleSelectSetAllSelected(status){
        for(let i = 0; i < $scope.visibleItems.length; i++){
            $scope.visibleItems[i].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();
        let filteredSelected = filterResults(selected);
        let newSelectedList = MultipleSelectService.setSelectedList(filteredSelected);

        return newSelectedList;
    }

    function getRefreshedCornerState(){
        let filteredItems = filterResults($scope.visibleItems);
        let refreshedCornerState = MultipleSelectService.refreshCornerState(filteredItems.length);

        return refreshedCornerState;
    }

    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();

            if ($element.find('td.name')[index + 1] && $scope.items[index + 1]) {
                $state.go($scope.detailsState + '.activities', {
                    id: $scope.items[index + 1]._id,
                    entity: context.entityName,
                    entityId: context.entityId,
                    nameFocused: true
                });
                $element.find('td.name')[index + 1].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 = filterResults($scope.items);
    };

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

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

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

    $scope.$on('refreshList', function () {
        $scope.refreshVisibleItems();
    });

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

        return newArray;
    }

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

    NotifyingService.subscribe('filterMyTasks', function () {
      $scope.refreshVisibleItems();
    }, $scope);

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

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

    $scope.recycled = function(entity) {
        if (entity && entity.hasOwnProperty('recycled'))
            return true;
        return false;
    }

    $scope.havePermissions = function(entity, type) {
        return PermissionsService.havePermissions(entity, type);
    }

    $scope.haveEditiorsPermissions = function(entity) {
        return PermissionsService.haveEditorsPerms(entity);
    }

    $scope.permsToSee = function(entity) {
      return PermissionsService.haveAnyPerms(entity);
    }

}

angular.module('mean.icu.ui.entityList', ['dragularModule']).controller('EntityListController', EntityListController);
<commit_msg>fixed showing list in middle pane after clicking on subentity in projects https://github.com/linnovate/root/issues/1268<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(function(t) {
        return 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.activities` || $state.current.name === `main.${$scope.$parent.entityName}.byentity.details.activities`) {
            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.activities`) {
            $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') {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byparent.details`;
    } else {
        $scope.detailsState = `main.${$scope.$parent.entityName}.byentity.details`;
    }

    var isScrolled = false;

    $scope.isCurrentState = function(id) {
        var isActive = ($state.current.name.indexOf(`main.${$scope.$parent.entityName}.byparent.details`) === 0 || $state.current.name.indexOf(`main.${$scope.$parent.entityName}.byentity.details`) === 0 || $state.current.name.indexOf(`main.${$scope.$parent.entityName}.all.details`) === 0) && $state.params.id === id;
        if (isActive && !isScrolled) {
            //$uiViewScroll($element.find('[data-id="' + $stateParams.id + '"]'));
            isScrolled = true;
        }
        return isActive;
    };

    // ============================================================= //
    // ========================== 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;
        }

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

    $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 ============================ //
    // ============================================================= //

    var creatingStatuses = {
        NotCreated: 0,
        Creating: 1,
        Created: 2
    }

    $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 + '.activities', {
            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)=>{
            //             if (localStorage.getItem('type') == 'new') {
            //                 $state.go($scope.detailsState + '.activities', {
            //                     id: result._id,
            //                     entity: context.entityName,
            //                     entityId: context.entityId,
            //                     nameFocused: false,
            //                     officeDocuments
            //                 });
            //             } else {
            $scope.refreshVisibleItems();
            $timeout(()=> {
              let els = $element.find('td.name');
              els.length && els[els.length - 1].focus();
            },100);
            $state.go($scope.detailsState + '.activities', {
                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', function(event, cornerState){
        multipleSelectSetAllSelected(cornerState === 'all');
    });

    function multipleSelectSetAllSelected(status){
        for(let i = 0; i < $scope.visibleItems.length; i++){
            $scope.visibleItems[i].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();
        let filteredSelected = filterResults(selected);
        let newSelectedList = MultipleSelectService.setSelectedList(filteredSelected);

        return newSelectedList;
    }

    function getRefreshedCornerState(){
        let filteredItems = filterResults($scope.visibleItems);
        let refreshedCornerState = MultipleSelectService.refreshCornerState(filteredItems.length);

        return refreshedCornerState;
    }

    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();

            if ($element.find('td.name')[index + 1] && $scope.items[index + 1]) {
                $state.go($scope.detailsState + '.activities', {
                    id: $scope.items[index + 1]._id,
                    entity: context.entityName,
                    entityId: context.entityId,
                    nameFocused: true
                });
                $element.find('td.name')[index + 1].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 = filterResults($scope.items);
    };

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

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

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

    $scope.$on('refreshList', function () {
        $scope.refreshVisibleItems();
    });

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

        return newArray;
    }

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

    NotifyingService.subscribe('filterMyTasks', function () {
      $scope.refreshVisibleItems();
    }, $scope);

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

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

    $scope.recycled = function(entity) {
        if (entity && entity.hasOwnProperty('recycled'))
            return true;
        return false;
    }

    $scope.havePermissions = function(entity, type) {
        return PermissionsService.havePermissions(entity, type);
    }

    $scope.haveEditiorsPermissions = function(entity) {
        return PermissionsService.haveEditorsPerms(entity);
    }

    $scope.permsToSee = function(entity) {
      return PermissionsService.haveAnyPerms(entity);
    }

}

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


<commit_before>'use strict';

var _ = require('lodash');
var Reflux = require('reflux');
var moment = require('moment');

var CampaignStore = require('stores/CampaignStore');

var api = require('data/api');
var builtins = require('dashboard/builtin');

var NavigationStore = Reflux.createStore({
  init: function () {
    this.campaigns = [];
    this.dashboards = [];
    this.customDashboards = [];
    this.loaded = false;

    Promise.all([
      CampaignStore.getCampaignsPromise(),
      api.get_dashboard(),
      api.office().then(response => response.objects)
    ]).then(_.spread(this._loadDashboards));
  },

  getInitialState: function () {
    return {
      campaigns: this.campaigns,
      dashboards: this.dashboards,
      documents: this.documents,
      loaded: this.loaded
    };
  },

  // API
  getDashboard: function (slug) {
    var dashboard = _.find(this.dashboards, d => _.kebabCase(d.title) === slug) || {};

    if(!dashboard.id) {
      dashboard.charts = [];
      return Promise.reject('dashboard does not exist').then(function(reason) {
      }, function(reason) {
        console.log(reason);
      });
    }

    if (dashboard.id <= 0) {
      return new Promise(resolve => {
        resolve(dashboard)
      })
    } else {
      return api.get_chart({dashboard_id: dashboard.id}, null, {'cache-control': 'no-cache'}).then(res => {
        dashboard.charts = res.objects.map(chart => {
          var result = chart.chart_json;
          result.id = chart.id;
          return result;
        });
        return dashboard
      }, function (err) {
        console.log(err);
        dashboard.charts = [];
      });
    }
  },

  // Helpers
  _loadDashboards: function (campaigns, dashboards, offices) {
    var allDashboards = builtins.concat(dashboards.objects);

    campaigns = _(campaigns);

    // Take the first location alphabetically at the highest geographic level
    // available as the default location for this dashboard
    var office = _.min(offices, _.property('id'));

    this.dashboards = _(allDashboards)
      .map(function (d) {
        // Find the latest campaign for the chosen location
        var campaign = campaigns
          .filter(c => {
            return office.id === c.office_id;
          })
          .max(c => {
            return moment(c.start_date, 'YYYY-MM-DD').valueOf()
          });

        // Build the path for the dashboard
        var path = '';
        try {
          path = '/' + office.name + '/' + moment(campaign.start_date, 'YYYY-MM-DD').format('YYYY/MM');
        } catch (err) {
          path = '/'
        }
        // Patch the non-comformant API response
        d.charts = d.charts || d.dashboard_json;

        return _.assign({}, d, {
          href: '/datapoints/' + _.kebabCase(d.title) + path
        });
      })
      .reject(_.isNull)
      .value();

    var indexedOffices = _.indexBy(offices, 'id');
    this.campaigns = campaigns
      .map(c => {
        var m = moment(c.start_date, 'YYYY-MM-DD');
        var dt = m.format('YYYY/MM');
        var officeName = indexedOffices[c.office_id].name;
        var title = officeName + ': ' + m.format('MMMM YYYY');

        var links = _.map(allDashboards, function (d) {
          return _.defaults({
            path: _.kebabCase(d.title) + '/' + officeName + '/' + dt
          }, d);
        });

        return _.defaults({
          title: title,
          dashboards: links
        }, c);
      });

    this.loaded = true;

    this.trigger({
      dashboards: this.dashboards,
      campaigns: this.campaigns,
      loaded: this.loaded
    });
  }
});

module.exports = NavigationStore;
<commit_msg>remove unused code<commit_after>'use strict';

var _ = require('lodash');
var Reflux = require('reflux');
var moment = require('moment');

var CampaignStore = require('stores/CampaignStore');

var api = require('data/api');
var builtins = require('dashboard/builtin');

var NavigationStore = Reflux.createStore({
  init: function () {
    this.campaigns = [];
    this.dashboards = [];
    this.customDashboards = [];
    this.loaded = false;

    Promise.all([
      CampaignStore.getCampaignsPromise(),
      api.get_dashboard(),
      api.office().then(response => response.objects)
    ]).then(_.spread(this._loadDashboards));
  },

  getInitialState: function () {
    return {
      campaigns: this.campaigns,
      dashboards: this.dashboards,
      documents: this.documents,
      loaded: this.loaded
    };
  },

  // API
  getDashboard: function (slug) {
    var dashboard = _.find(this.dashboards, d => _.kebabCase(d.title) === slug) || {};

    if (dashboard.id <= 0) {
      return new Promise(resolve => {
        resolve(dashboard)
      })
    } else {
      return api.get_chart({dashboard_id: dashboard.id}, null, {'cache-control': 'no-cache'}).then(res => {
        dashboard.charts = res.objects.map(chart => {
          var result = chart.chart_json;
          result.id = chart.id;
          return result;
        });
        return dashboard
      }, function (err) {
        console.log(err);
        dashboard.charts = [];
      });
    }
  },

  // Helpers
  _loadDashboards: function (campaigns, dashboards, offices) {
    var allDashboards = builtins.concat(dashboards.objects);

    campaigns = _(campaigns);

    // Take the first location alphabetically at the highest geographic level
    // available as the default location for this dashboard
    var office = _.min(offices, _.property('id'));

    this.dashboards = _(allDashboards)
      .map(function (d) {
        // Find the latest campaign for the chosen location
        var campaign = campaigns
          .filter(c => {
            return office.id === c.office_id;
          })
          .max(c => {
            return moment(c.start_date, 'YYYY-MM-DD').valueOf()
          });

        // Build the path for the dashboard
        var path = '';
        try {
          path = '/' + office.name + '/' + moment(campaign.start_date, 'YYYY-MM-DD').format('YYYY/MM');
        } catch (err) {
          path = '/'
        }
        // Patch the non-comformant API response
        d.charts = d.charts || d.dashboard_json;

        return _.assign({}, d, {
          href: '/datapoints/' + _.kebabCase(d.title) + path
        });
      })
      .reject(_.isNull)
      .value();

    var indexedOffices = _.indexBy(offices, 'id');
    this.campaigns = campaigns
      .map(c => {
        var m = moment(c.start_date, 'YYYY-MM-DD');
        var dt = m.format('YYYY/MM');
        var officeName = indexedOffices[c.office_id].name;
        var title = officeName + ': ' + m.format('MMMM YYYY');

        var links = _.map(allDashboards, function (d) {
          return _.defaults({
            path: _.kebabCase(d.title) + '/' + officeName + '/' + dt
          }, d);
        });

        return _.defaults({
          title: title,
          dashboards: links
        }, c);
      });

    this.loaded = true;

    this.trigger({
      dashboards: this.dashboards,
      campaigns: this.campaigns,
      loaded: this.loaded
    });
  }
});

module.exports = NavigationStore;
<|endoftext|>


<commit_before>/*! Por recomendacion. Evita errores por el mal cierre de scripts */
/*!
 * función anónima que nos asegura que el símbolo $
 * sea del objeto jQuery, en caso que este sea usado como objeto por otras bibliotecas.
 * Uso como parámetro la variable windows para ahorrar tiempo de búsqueda de objetos globales.
 * Uso del parámetro undefined para asegurar que la variable es no definida.
 */
var numeroDeDiasFestivos=0;
var numeroDeDiasFestivosM=0;
var id_horario=0;
var id_horario_m=0;
var idnCExtra=0;
(function( $, window, undefined ) {
  var DIAS_MAXIMOS = 7,
      DIAS_MAXIMOS_CLASE = 7;
  $.fn.agregaDiaFestivo = function(contenedor) {
  var contenedorDiasFestivos = contenedor,
        contenedorDiasFestivos;

    // Uso de encadenamiento
    return this.each(function() {
      $boton = $(this);
      $boton.on('click', function () {
      $("#guardar").removeAttr("disabled");
      if ( $('.content').size() < DIAS_MAXIMOS ) {
        numeroDeDiasFestivos++;
        $( contenedorDiasFestivos ).append(
            '
'+
              '<input id="inicio_'+numeroDeDiasFestivos+
                  '" type="text" placeholder="aaaa-mm-dd" onblur="validaFecha(\'inicio_'
                  +numeroDeDiasFestivos+'\')"/>'+
              '<textarea id="descripcion_'+numeroDeDiasFestivos+
                  '" onblur="validaDescripcion(\'descripcion_'
                  +numeroDeDiasFestivos+'\')"></textarea>'+
              '<button class="quitarFestivo">-</button>'+
            '
');
          $('body').eliminarElemento();
          $('#inicio_'+numeroDeDiasFestivos).datePickerElem();
        };
      });
    });
  }
  $.fn.agregaDiaFestivom = function(contenedor) {
    return this.each(function () {
      $(this).on('click', function(){
        if($('.content').size() < DIAS_MAXIMOS) {
          numeroDeDiasFestivosM++;
          $( contenedor ).append(
            '
'+
              '<input id="inicio_m_' +numeroDeDiasFestivosM+
                  '" type="text" placeholder="aaaa-mm-dd" onblur="validaFecha(\'inicio_m_'
                  +numeroDeDiasFestivosM+'\')"/>'+
              '<textarea id="descripcion_m_'+numeroDeDiasFestivosM+
                  '" onblur="validaDescripcion(\'descripcion_m_'
                  +numeroDeDiasFestivosM+'\')"></textarea>'+
              '<button class="quitarFestivo">-</button>'+
            '
');
          $('body').eliminarElemento();
          $('#inicio_m_'+numeroDeDiasFestivosM).datePickerElem();
        }
      });
    });
  }
  $.fn.eliminarElemento = function () {
    return this.each( function () {
      $('body').on('click', '.quitarFestivo', function () {
        var elem = ($(this).parent().attr('id'));
        $('#'+elem).remove();
        enable_button('guardar');
      });
    });
  }
  $.fn.agregaDiaDeClase = function(contenedor) {
    var ndia=0, c, id_horario_f;
    return this.each(function() {
      $(this).on('click', function () {
        c = $(this).siblings( contenedor ).attr('id');
        if ( c.lastIndexOf('_m') == -1 ) { p = ''; } else { p = '_m' }
        $("#guardar").removeAttr("disabled");
        if ( $('.content').size() < DIAS_MAXIMOS_CLASE ) {
          if ( c == 'wrapper_m' ) {
            id_horario_f = id_horario_m;
            id_horario_m++;
          } else if (c == 'wrapper') {
            id_horario_f = id_horario;
            id_horario++;
          }
          $( '#' + c ).append(
            '
'+
              '<select id="SelectDia'+p+'_'+id_horario_f+'" name="dia'+p+'_'+id_horario_f+'"></select>
'+
              '<input id="Hora_inicio_clase'+p+'_'+id_horario_f+'" type="text" placeholder="Hora inicio clase" />'+
              '<input id="Hora_fin_clase'+p+'_'+id_horario_f+'" type="text" placeholder="Hora fin clase" />'+
            '
'+
              '<select id="SelectDia_'+p+'_'+id_horario+'" name="dia_'+id_horario+'"></select>
'+
              '<input id="Hora_inicio_clase'+p+'_'+id_horario+'" type="text" placeholder="Hora inicio clase" />'+
              '<input id="duracion_'+p+'_'+id_horario+'" type="text" placeholder="Duracion de la clase" />'+
              '<button class="quitarDia">-</button>'+
            '
');
          for (i=0; i<6; i++) {
            switch(i) {
              case 0: ndia='Lunes';break;
              case 1: ndia='Martes';break;
              case 2: ndia='Miercoles';break;
              case 3: ndia='Jueves';break;
              case 4: ndia='Viernes';break;
              case 5: ndia='Sabado';break;
            }
            $('#SelectDia'+p+'_'+id_horario_f).append('<option id="dia'+p+'_'+i+'">'+ndia+'</option>');
          }
        };
      });
      $('body').on('click', '.quitarDia', function () {
        $(this).parent().remove();
      });
    });
  }
  $.fn.agregaCampoE = function(contenedor) {
    return this.each(function(){
      $(this).on('click', function () {
        idnCExtra++;
        $(contenedor).append(
          '
'+
            '<input id="campoExtraTipo_'+idnCExtra+'" name="campoExtraTipo_'+idnCExtra+
                '" type="text" placeholder="tipo de cuenta" style="width:55%" onblur="validaCampoExtra(\'campoExtraTipo_'+idnCExtra+'\')" />'+
            '<button class="quitar">-</button>'+
            '<input id="campoExtra_'+idnCExtra+'" name="campoExtra_'+idnCExtra+
                '" type="text" placeholder="Nombre de cuenta" onblur="validaCampoExtra(\'campoExtra_'+idnCExtra+'\')"/>'+
            '<button class="quitar">-</button>'+
          '
');
      });
      $('body').on('click', '.quitar', function () {
        $(this).parent().remove();
      });
    });
  }
  $.fn.datePickerElem = function() {
    return this.each(function(){
      $(this).datepicker({
        clearText: 'Borrar',
        clearStatus: 'Borrar fecha actual',
        closeText: 'Cerrar',
        closeStatus: 'Cerrar sin guardar',
        dateFormat: 'yy-mm-dd',
        dayNames: ['Domingo','Lunes','Martes','Miercoles','Jueves','Viernes','Sabado'],
        dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi', 'Sa'],
        firstDay: 0,
        inline: true,
        monthNames: ['Enero','Febrero','Marzo','Abril',
                    'Mayo','Junio','Julio','Agosto',
                    'Septienbre','Octubre','Novienbre','Diciembre'],
        monthNameShort: ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'],
        prevStatus: 'Mostrar mes anterior',
        prevBigStatus: 'Mostrar año anterior',
        selectOtherMonths: true,
        showOtherMonths: true,
        showWeek: true
      });
    })
  }
  $.fn.mostrarDiasFestivos = function (contenedor, diaF, descripcionD) {
    return this.each( function () {
      numeroDeDiasFestivos++;
      numero = numeroDeDiasFestivos;
      $( contenedor ).append(
        '
'+
            '<input id="inicio_'+numero+
                '" type="text" placeholder="aaaa-mm-dd" onblur="validaFecha(\'inicio_'+
                numero+'\')" value="'+diaF+'" onchange="enable_button(\'guardar\')" />'+
            '<textarea id="descripcion_'+numero+
                '" onblur="validaDescripcion(\'descripcion_'+
                numero+'\')" onchange="enable_button(\'guardar\')">'+descripcionD+'</textarea>'+
            '<button class="quitarFestivo">-</button>'+
          '
');
          $('#inicio_'+numeroDeDiasFestivos).datePickerElem();
          $('body').eliminarElemento();
    });
  }
  $.fn.limpiarListaDeHijos = function (contenedor) {
    return this.each( function () {
      $( contenedor ).empty();
    });
  }
})( jQuery, window );
<commit_msg>ajuste funcion dias de clase jquery<commit_after>/*! Por recomendacion. Evita errores por el mal cierre de scripts */
/*!
 * función anónima que nos asegura que el símbolo $
 * sea del objeto jQuery, en caso que este sea usado como objeto por otras bibliotecas.
 * Uso como parámetro la variable windows para ahorrar tiempo de búsqueda de objetos globales.
 * Uso del parámetro undefined para asegurar que la variable es no definida.
 */
var numeroDeDiasFestivos=0;
var numeroDeDiasFestivosM=0;
var id_horario=0;
var id_horario_m=0;
var idnCExtra=0;
(function( $, window, undefined ) {
  var DIAS_MAXIMOS = 7,
      DIAS_MAXIMOS_CLASE = 7;
  $.fn.agregaDiaFestivo = function(contenedor) {
  var contenedorDiasFestivos = contenedor,
        contenedorDiasFestivos;

    // Uso de encadenamiento
    return this.each(function() {
      $boton = $(this);
      $boton.on('click', function () {
      $("#guardar").removeAttr("disabled");
      if ( $('.content').size() < DIAS_MAXIMOS ) {
        numeroDeDiasFestivos++;
        $( contenedorDiasFestivos ).append(
            '
'+
              '<input id="inicio_'+numeroDeDiasFestivos+
                  '" type="text" placeholder="aaaa-mm-dd" onblur="validaFecha(\'inicio_'
                  +numeroDeDiasFestivos+'\')"/>'+
              '<textarea id="descripcion_'+numeroDeDiasFestivos+
                  '" onblur="validaDescripcion(\'descripcion_'
                  +numeroDeDiasFestivos+'\')"></textarea>'+
              '<button class="quitarFestivo">-</button>'+
            '
');
          $('body').eliminarElemento();
          $('#inicio_'+numeroDeDiasFestivos).datePickerElem();
        };
      });
    });
  }
  $.fn.agregaDiaFestivom = function(contenedor) {
    return this.each(function () {
      $(this).on('click', function(){
        if($('.content').size() < DIAS_MAXIMOS) {
          numeroDeDiasFestivosM++;
          $( contenedor ).append(
            '
'+
              '<input id="inicio_m_' +numeroDeDiasFestivosM+
                  '" type="text" placeholder="aaaa-mm-dd" onblur="validaFecha(\'inicio_m_'
                  +numeroDeDiasFestivosM+'\')"/>'+
              '<textarea id="descripcion_m_'+numeroDeDiasFestivosM+
                  '" onblur="validaDescripcion(\'descripcion_m_'
                  +numeroDeDiasFestivosM+'\')"></textarea>'+
              '<button class="quitarFestivo">-</button>'+
            '
');
          $('body').eliminarElemento();
          $('#inicio_m_'+numeroDeDiasFestivosM).datePickerElem();
        }
      });
    });
  }
  $.fn.eliminarElemento = function () {
    return this.each( function () {
      $('body').on('click', '.quitarFestivo', function () {
        var elem = ($(this).parent().attr('id'));
        $('#'+elem).remove();
        enable_button('guardar');
      });
    });
  }
  $.fn.agregaDiaDeClase = function(contenedor) {
    var ndia=0, c, id_horario_f;
    return this.each(function() {
      $(this).on('click', function () {
        c = $(this).siblings( contenedor ).attr('id');
        if ( c.lastIndexOf('_m') == -1 ) { p = ''; } else { p = '_m' }
        $("#guardar").removeAttr("disabled");
        if ( $('.content').size() < DIAS_MAXIMOS_CLASE ) {
          if ( c == 'wrapper_m' ) {
            id_horario_f = id_horario_m;
            id_horario_m++;
          } else if (c == 'wrapper') {
            id_horario_f = id_horario;
            id_horario++;
          }
          $( '#' + c ).append(
            '
'+
              '<select id="SelectDia'+p+'_'+id_horario_f+'" name="dia'+p+'_'+id_horario_f+'"></select>
'+
              '<input id="Hora_inicio_clase'+p+'_'+id_horario_f+'" type="text" placeholder="Hora inicio clase" />'+
              '<input id="Hora_fin_clase'+p+'_'+id_horario_f+'" type="text" placeholder="Hora fin clase" />'+
              '<button class="quitarDia">-</button>'+
            '
');
          for (i=0; i<6; i++) {
            switch(i) {
              case 0: ndia='Lunes';break;
              case 1: ndia='Martes';break;
              case 2: ndia='Miercoles';break;
              case 3: ndia='Jueves';break;
              case 4: ndia='Viernes';break;
              case 5: ndia='Sabado';break;
            }
            $('#SelectDia'+p+'_'+id_horario_f).append('<option id="dia'+p+'_'+i+'">'+ndia+'</option>');
          }
        };
      });
      $('body').on('click', '.quitarDia', function () {
        $(this).parent().remove();
      });
    });
  }
  $.fn.agregaCampoE = function(contenedor) {
    return this.each(function(){
      $(this).on('click', function () {
        idnCExtra++;
        $(contenedor).append(
          '
'+
            '<input id="campoExtraTipo_'+idnCExtra+'" name="campoExtraTipo_'+idnCExtra+
                '" type="text" placeholder="tipo de cuenta" style="width:55%" onblur="validaCampoExtra(\'campoExtraTipo_'+idnCExtra+'\')" />'+
            '<button class="quitar">-</button>'+
            '<input id="campoExtra_'+idnCExtra+'" name="campoExtra_'+idnCExtra+
                '" type="text" placeholder="Nombre de cuenta" onblur="validaCampoExtra(\'campoExtra_'+idnCExtra+'\')"/>'+
            '<button class="quitar">-</button>'+
          '
');
      });
      $('body').on('click', '.quitar', function () {
        $(this).parent().remove();
      });
    });
  }
  $.fn.datePickerElem = function() {
    return this.each(function(){
      $(this).datepicker({
        clearText: 'Borrar',
        clearStatus: 'Borrar fecha actual',
        closeText: 'Cerrar',
        closeStatus: 'Cerrar sin guardar',
        dateFormat: 'yy-mm-dd',
        dayNames: ['Domingo','Lunes','Martes','Miercoles','Jueves','Viernes','Sabado'],
        dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi', 'Sa'],
        firstDay: 0,
        inline: true,
        monthNames: ['Enero','Febrero','Marzo','Abril',
                    'Mayo','Junio','Julio','Agosto',
                    'Septienbre','Octubre','Novienbre','Diciembre'],
        monthNameShort: ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'],
        prevStatus: 'Mostrar mes anterior',
        prevBigStatus: 'Mostrar año anterior',
        selectOtherMonths: true,
        showOtherMonths: true,
        showWeek: true
      });
    })
  }
  $.fn.mostrarDiasFestivos = function (contenedor, diaF, descripcionD) {
    return this.each( function () {
      numeroDeDiasFestivos++;
      numero = numeroDeDiasFestivos;
      $( contenedor ).append(
        '
'+
            '<input id="inicio_'+numero+
                '" type="text" placeholder="aaaa-mm-dd" onblur="validaFecha(\'inicio_'+
                numero+'\')" value="'+diaF+'" onchange="enable_button(\'guardar\')" />'+
            '<textarea id="descripcion_'+numero+
                '" onblur="validaDescripcion(\'descripcion_'+
                numero+'\')" onchange="enable_button(\'guardar\')">'+descripcionD+'</textarea>'+
            '<button class="quitarFestivo">-</button>'+
          '
');
          $('#inicio_'+numeroDeDiasFestivos).datePickerElem();
          $('body').eliminarElemento();
    });
  }
  $.fn.limpiarListaDeHijos = function (contenedor) {
    return this.each( function () {
      $( contenedor ).empty();
    });
  }
})( jQuery, window );
<|endoftext|>


<commit_before>'use strict';

angular.module('mean.icu.ui.searchlist')
.controller('SearchListController', function ($rootScope, $scope, $stateParams, $location, $timeout, results, term, SearchService, UsersService) {
	$scope.results = results;
    filterFinalRes();

	$scope.inObjArray = function(id,array){
		array.forEach(function(w){
			if(w._id && w._id === id){
				return true;
			}
		});
		return false;
	};

    $scope.$on('refreshList', function (ev) {
        SearchService.find(term).then(function(res){
            $scope.results = res;
            filterFinalRes();
        });
    });

    function filterFinalRes(){
        UsersService.getMe().then(function(me){
            let id = me._id;
            let finalResults = [];
            for(let i=0; i < $scope.results.length; i++){
                let task = $scope.results[i];
                if(
                    task.creator === id
                    || task.assign === id
                    || $.inArray(id, task.watchers) !== -1
                    || $scope.inObjArray(id,task.watchers)){
                    finalResults.push(task);
                }
            }
            $scope.term = term;
            $scope.results = finalResults;
            $scope.resultsLength = $scope.results.length;
        });
    }

    //**********Multiple Select*********//
    $scope.multipleSelectMode = false;

});

<commit_msg>Add piwik to searchpages<commit_after>'use strict';

angular.module('mean.icu.ui.searchlist')
.controller('SearchListController', function ($rootScope, $scope, $stateParams, $location, $timeout, results, term, SearchService, UsersService) {

	document.me = $scope.me.id;

	$scope.results = results;
    filterFinalRes();

	$scope.inObjArray = function(id,array){
		array.forEach(function(w){
			if(w._id && w._id === id){
				return true;
			}
		});
		return false;
	};

    $scope.$on('refreshList', function (ev) {
        SearchService.find(term).then(function(res){
            $scope.results = res;
            filterFinalRes();
        });
    });

    function filterFinalRes(){
        UsersService.getMe().then(function(me){
            let id = me._id;
            let finalResults = [];
            for(let i=0; i < $scope.results.length; i++){
                let task = $scope.results[i];
                if(
                    task.creator === id
                    || task.assign === id
                    || $.inArray(id, task.watchers) !== -1
                    || $scope.inObjArray(id,task.watchers)){
                    finalResults.push(task);
                }
            }
            $scope.term = term;
            $scope.results = finalResults;
            $scope.resultsLength = $scope.results.length;
        });
    }

    //**********Multiple Select*********//
    $scope.multipleSelectMode = false;

});

<|endoftext|>


<commit_before>'use strict';
module.exports = function hydrateOutputSchema(schema) {
    schema.properties = schema.properties || {};
    schema.required = schema.required || [];
    add_id(schema);
    addStatusInfo(schema);
    addOwnerInfo(schema);
};

function add_id(schema) {
    const defaultIdField = {
        type: 'string',
        format: 'mongoId',
        mongoId: true,
        minLength: 24,
        maxLength: 24
    };
    schema.properties._id = Object.assign({}, defaultIdField, schema.properties._id);
    schema.required.push('_id');
}

function addStatusInfo(schema) {
    if (!schema.statuses) {
        return;
    }
    if (!schema.updateStatusSchema) {
        throw new Error(
            'Cannot have statuses array specified on the schema but not provide an updateStatusSchema property'
        );
    }
    const statusNames = schema.statuses.map(status => status.name);
    schema.properties.status = {
        type: 'string',
        enum: statusNames
    };
    schema.properties.statusDate = {
        type: 'string',
        format: 'date-time',
        faker: 'date.past'
    };
    schema.properties.statusLog = {
        type: 'array',
        items: {
            type: 'object',
            properties: {
                status: schema.properties.status,
                statusDate: schema.properties.statusDate,
                data: schema.updateStatusSchema
            },
            required: ['status', 'statusDate', 'data'],
            additionalProperties: false
        },
        additionalItems: false
    };
    schema.required.push('status');
    schema.required.push('statusDate');
    schema.required.push('statusLog');
}

function addOwnerInfo(schema) {
    if (!schema.ownership) {
        return;
    }
    schema.properties.owner = {
        type: 'string',
        format: 'mongoId',
        mongoId: true,
        minLength: 24,
        maxLength: 24
    };
    schema.properties.ownerDate = {
        type: 'string',
        format: 'date-time',
        faker: 'date.past'
    };
    schema.properties.ownerLog = {
        type: 'array',
        items: {
            type: 'object',
            properties: {
                owner: schema.properties.owner,
                ownerDate: schema.properties.ownerDate,
                data: {
                    type: ['object', 'string'] //todo?
                }
            },
            required: ['owner', 'ownerDate', 'data'],
            additionalProperties: false
        },
        additionalItems: false
    };
    schema.required.push('owner');
    schema.required.push('ownerDate');
    schema.required.push('ownerLog');
}
<commit_msg>Updating todo's<commit_after>'use strict';
module.exports = function hydrateOutputSchema(schema) {
    schema.properties = schema.properties || {};
    schema.required = schema.required || [];
    add_id(schema);
    addStatusInfo(schema);
    addOwnerInfo(schema);
};

function add_id(schema) {
    const defaultIdField = {
        type: 'string',
        format: 'mongoId',
        mongoId: true,
        minLength: 24,
        maxLength: 24
    };
    schema.properties._id = Object.assign({}, defaultIdField, schema.properties._id);
    schema.required.push('_id');
}

function addStatusInfo(schema) {
    if (!schema.statuses) {
        return;
    }
    if (!schema.updateStatusSchema) {
        throw new Error(
            'Cannot have statuses array specified on the schema but not provide an updateStatusSchema property'
        );
    }
    const statusNames = schema.statuses.map(status => status.name);
    schema.properties.status = {
        type: 'string',
        enum: statusNames
    };
    schema.properties.statusDate = {
        type: 'string',
        format: 'date-time',
        faker: 'date.past'
    };
    schema.properties.statusLog = {
        type: 'array',
        items: {
            type: 'object',
            properties: {
                status: schema.properties.status,
                statusDate: schema.properties.statusDate,
                data: schema.updateStatusSchema //todo anyof?
            },
            required: ['status', 'statusDate', 'data'], //todo - data check schema anyof?
            additionalProperties: false
        },
        additionalItems: false
    };
    schema.required.push('status');
    schema.required.push('statusDate');
    schema.required.push('statusLog');
}

function addOwnerInfo(schema) {
    if (!schema.ownership) {
        return;
    }
    schema.properties.owner = {
        type: 'string',
        format: 'mongoId',
        mongoId: true,
        minLength: 24,
        maxLength: 24
    };
    schema.properties.ownerDate = {
        type: 'string',
        format: 'date-time',
        faker: 'date.past'
    };
    schema.properties.ownerLog = {
        type: 'array',
        items: {
            type: 'object',
            properties: {
                owner: schema.properties.owner,
                ownerDate: schema.properties.ownerDate,
                data: {
                    type: ['object', 'string'] //todo?
                }
            },
            required: ['owner', 'ownerDate', 'data'], //todo - data check schema anyof?
            additionalProperties: false
        },
        additionalItems: false
    };
    schema.required.push('owner');
    schema.required.push('ownerDate');
    schema.required.push('ownerLog');
}
<|endoftext|>


<commit_before>// {{{ Settings
Hints.style('font-size: 1rem; border: none; color:#efe1eb; background: initial; background-color: #552a48;')
Hints.style('font-size: 1rem; border: none; background: initial; background-color: #c0c0c0', 'text')
settings.nextLinkRegex = /((?!first)(next|older|more|>|»|forward|→|次(のページ|へ))+)/i
settings.prevLinkRegex = /((?!last)(prev(ious)?|newer|back|«|less|<|←|前(のページ|へ))+)/i
settings.hintAlign = 'left'
settings.focusAfterClosed = 'right'
// }}}

// {{{ MapKeys
map('<Ctrl-f>', 'd')
map('<Ctrl-b>', 'e')
map('<Ctrl-u>', 'e')
map('<Ctrl-d>', 'd')
map('<Ctrl-e>', 'j')
map('<Ctrl-y>', 'k')
map('<Ctrl-n>', 'R')
map('<Ctrl-p>', 'E')
map('H', 'S')
map('L', 'D')
map('d', 'x')
map('u', 'X')
map('F', 'gf')
map('P', 'sg')
map('<Ctrl-t><Ctrl-t>', '<Ctrl-6>')
map('<Ctrl-[>', '<Esc>')
map('gn', 't')
// }}}

// {{{ UnmapKeys
const unmapKeys = keys => keys.forEach(key => unmap(key))
unmapKeys(['go', 'ob', 'sb', 'ow', 'sw', '<Meta-b>'])
const iunmapKeys = keys => keys.forEach(key => iunmap(key))
iunmapKeys([':', '<Ctrl-f>', '<Ctrl-e>'])
const vunmapKeys = keys => keys.forEach(key => vunmap(key))
vunmapKeys(['q'])
// }}}

// {{{ SearchAlias & MapKeys
removeSearchAliasX('b')
removeSearchAliasX('w')

addSearchAliasX(
  'a',
  'Amazon',
  'https://www.amazon.co.jp/s?k=',
  's',
  'https://completion.amazon.co.jp/search/complete?method=completion&search-alias=aps&mkt=6&q=',
  response => JSON.parse(response.text)[1]
)
mapkey('oa', '#8Open Search with alias A', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'a' })
})

addSearchAliasX(
  'alc',
  'ALC',
  'https://eow.alc.co.jp/'
)
mapkey('alc', '#8Open Search with alias a', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'alc' })
})
mapkey(';a', '#14ALC', () => {
  const selection = window.getSelection().toString()
  if (selection !== '') {
    tabOpenLink(
      `https://eow.alc.co.jp/${encodeURI(selection)}`
    )
  }
})

addSearchAliasX(
  'r',
  'Yahoo! Real-time search',
  'http://realtime.search.yahoo.co.jp/search?ei=UTF-8&p='
)
mapkey('or', '#8Open Search with alias r', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'r' })
})

addSearchAliasX(
  't',
  'Google Translation',
  'https://translate.google.com/?sl=auto&tl=ja&text='
)
mapkey('ot', '#8Open Search with alias t', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 't' })
})
mapkey(';t', '#14Google Translate', () => {
  const selection = window.getSelection().toString()
  if (selection === '') {
    tabOpenLink(
      `http://translate.google.com/translate?u=${window.location.href}`
    )
  } else {
    tabOpenLink(
      `https://translate.google.com/?sl=auto&tl=ja&text=${encodeURI(selection)}`
    )
  }
})

addSearchAliasX(
  'tw',
  'Twitter',
  'https://twitter.com/search?q='
)
mapkey('oT', '#8Open Search with alias tw', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'tw' })
})

addSearchAliasX(
  'w',
  'Wikipedia',
  'https://ja.wikipedia.org/w/index.php?search='
)
mapkey('ow', '#8Open Search with alias w', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'w' })
})

mapkey(';b', '#14Hatena Bookmark', () => {
  const { location } = window
  switch (location.protocol) {
    case 'http:': {
      tabOpenLink(
        `https://b.hatena.ne.jp/entry/${location.href.replace('http://', '')}`
      )
      break
    }
    case 'https:': {
      tabOpenLink(
        `https://b.hatena.ne.jp/entry/s/${location.href.replace('https://', '')}`
      )
      break
    }
    default: {
      throw new Error('Error')
    }
  }
})
// }}}

// {{{ qmarks
const qmarksUrls = {
  b: 'https://b.hatena.ne.jp',
  c: 'https://calendar.google.com',
  m: 'https://mail.google.com'
}
const qmarksMapKey = (prefix, urls, newTab) => {
  const openLink = (link, newTab) => () => {
    RUNTIME('openLink', {
      tab: { tabbed: newTab },
      url: link,
    })
  }
  for (const key in urls) {
    mapkey(prefix + key, `qmark: ${urls[key]}`, openLink(urls[key], newTab))
  }
}
qmarksMapKey('go', qmarksUrls, true)
qmarksMapKey('gO', qmarksUrls, false)
// }}}

// {{{ Images
const ri = { repeatIgnore: true }
const Hint = (selector, action = Hints.dispatchMouseClick) => () =>
  Hints.create(selector, action)
mapkey('gI', '#4View image in new tab', Hint('img', i => tabOpenLink(i.src)), ri)
mapkey('yI', '#7Copy Image URL', Hint('img', i => Clipboard.write(i.src)), ri)
// }}}

// {{{ Copy
const copyTitleAndUrl = format => {
  const text = format
    .replace('%URL%', location.href)
    .replace('%TITLE%', document.title)
  Clipboard.write(text)
}
mapkey('cm', '#7Copy title and link to markdown', () => {
  copyTitleAndUrl('[%TITLE%](%URL%)')
})
mapkey('ct', '#7Copy title and link to textile', () => {
  copyTitleAndUrl('"%TITLE%":%URL%')
})
mapkey('cj', '#7Copy title and link to jira', () => {
  const title = document.title.replace(/[|[]]/g, ' ').replace(/^ +/, '')
  Clipboard.write(`[${title}|${location.href}]`)
})
mapkey('ch', '#7Copy title and link to human readable', () => {
  copyTitleAndUrl('%TITLE% - %URL%')
})
// }}}

// {{{ Settings for each service
const clickElm = selector => () => document.querySelector(selector).click()
const clickElmFr = selector => () =>
  document
    .querySelector('.speakerdeck-iframe')
    .contentWindow.document.querySelector(selector)
    .click()

if (/speakerdeck\.com/.test(window.location.hostname)) {
  mapkey(']', 'next page', clickElmFr('.sd-player-next'))
  mapkey('[', 'prev page', clickElmFr('.sd-player-previous'))
}

if (/www\.slideshare\.net/.test(window.location.hostname)) {
  mapkey(']', 'next page', clickElm('.j-next-btn'))
  mapkey('[', 'prev page', clickElm('.j-prev-btn'))
}

if (/youtube\.com/.test(window.location.hostname)) {
  mapkey(
    'T',
    'Toggle theater mode',
    clickElm('.ytp-size-button.ytp-button'))
  mapkey(
    'F',
    'Toggle fullscreen',
    clickElm('.ytp-fullscreen-button.ytp-button'))
  mapkey(']', 'Skip ad', clickElm('.ytp-ad-text.ytp-ad-skip-button-text'))
  mapkey('<Alt-x>', 'Skip ad', clickElm('.ytp-ad-overlay-close-button'))
}
// }}}

// {{{ Modify the page's URL
if (/www.amazon.co.jp/.test(window.location.hostname)) {
  mapkey('==', '#14Shorten the URL', () => {
    location.href = `https://www.amazon.co.jp/dp/${
      document.querySelectorAll("[name='ASIN'], [name='ASIN.0']")[0].value
    }`
  })
}

const shortenURL = (pattern) => location.href = location.href.replace(pattern, '')
mapkey('=?', '#14Delete query string', () => shortenURL(/\?.*/))
mapkey('=q', '#14Delete query string', () => shortenURL(/\?.*/))
mapkey('=#', '#14Delete hash', () => shortenURL(/#.*/))
mapkey('=h', '#14Delete hash', () => shortenURL(/#.*/))
// }}}

// {{{ unmapAllExcept
const commonUnmapKeys = [
  '<Ctrl-f>', '<Ctrl-b>',
  '<Ctrl-d>', '<Ctrl-u>',
  '<Ctrl-y>', '<Ctrl-e>',
  '<Ctrl-n>', '<Ctrl-p>',
  '<Ctrl-t><Ctrl-t>',
  't', 'gn',
  'oT', 'oa', 'od', 'og',
  'oh', 'oi', 'om', 'on',
  'or', 'ot', 'ox', 'oy',
  'H', 'L',
  'f', 'F',
  'x', 'X', 'd',
  '>>', '<<',
  '<Alt-p>'
].concat(
  Object.keys(qmarksUrls).map(key => `gO${key}`)
)

unmapAllExcept(
  commonUnmapKeys,
  /mail\.google\.com/
)

unmapAllExcept(
  commonUnmapKeys.concat(['u', 'G', 'gg']).concat(
    Object.keys(qmarksUrls).map(key => `go${key}`)
  ),
  /outlook\.office\.com|b\.hatena\.ne\.jp|twitter\.com/
)
// }}}
<commit_msg>[Surfingkeys] Tweaks<commit_after>// {{{ Settings
Hints.style('font-size: 1rem; border: none; color:#efe1eb; background: initial; background-color: #552a48;')
Hints.style('font-size: 1rem; border: none; background: initial; background-color: #c0c0c0', 'text')
settings.nextLinkRegex = /((?!first)(next|older|more|>|»|forward|→|次(のページ|へ))+)/i
settings.prevLinkRegex = /((?!last)(prev(ious)?|newer|back|«|less|<|←|前(のページ|へ))+)/i
settings.hintAlign = 'left'
settings.focusAfterClosed = 'right'
// }}}

// {{{ MapKeys
map('<Ctrl-f>', 'd')
map('<Ctrl-b>', 'e')
map('<Ctrl-u>', 'e')
map('<Ctrl-d>', 'd')
map('<Ctrl-e>', 'j')
map('<Ctrl-y>', 'k')
map('<Ctrl-n>', 'R')
map('<Ctrl-p>', 'E')
map('H', 'S')
map('L', 'D')
map('d', 'x')
map('u', 'X')
map('F', 'gf')
map('P', 'sg')
map('<Ctrl-s><Ctrl-s>', '<Ctrl-6>')
map('<Ctrl-[>', '<Esc>')
map('gn', 't')
// }}}

// {{{ UnmapKeys
const unmapKeys = keys => keys.forEach(key => unmap(key))
unmapKeys(['go', 'ob', 'sb', 'ow', 'sw', '<Meta-b>'])
const iunmapKeys = keys => keys.forEach(key => iunmap(key))
iunmapKeys([':', '<Ctrl-f>', '<Ctrl-e>'])
const vunmapKeys = keys => keys.forEach(key => vunmap(key))
vunmapKeys(['q'])
// }}}

// {{{ SearchAlias & MapKeys
removeSearchAliasX('b')
removeSearchAliasX('w')

addSearchAliasX(
  'a',
  'Amazon',
  'https://www.amazon.co.jp/s?k=',
  's',
  'https://completion.amazon.co.jp/search/complete?method=completion&search-alias=aps&mkt=6&q=',
  response => JSON.parse(response.text)[1]
)
mapkey('oa', '#8Open Search with alias A', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'a' })
})

addSearchAliasX(
  'alc',
  'ALC',
  'https://eow.alc.co.jp/'
)
mapkey('alc', '#8Open Search with alias a', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'alc' })
})
mapkey(';a', '#14ALC', () => {
  const selection = window.getSelection().toString()
  if (selection !== '') {
    tabOpenLink(
      `https://eow.alc.co.jp/${encodeURI(selection)}`
    )
  }
})

addSearchAliasX(
  'r',
  'Yahoo! Real-time search',
  'http://realtime.search.yahoo.co.jp/search?ei=UTF-8&p='
)
mapkey('or', '#8Open Search with alias r', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'r' })
})

addSearchAliasX(
  't',
  'Google Translation',
  'https://translate.google.com/?sl=auto&tl=ja&text='
)
mapkey('ot', '#8Open Search with alias t', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 't' })
})
mapkey(';t', '#14Google Translate', () => {
  const selection = window.getSelection().toString()
  if (selection === '') {
    tabOpenLink(
      `http://translate.google.com/translate?u=${window.location.href}`
    )
  } else {
    tabOpenLink(
      `https://translate.google.com/?sl=auto&tl=ja&text=${encodeURI(selection)}`
    )
  }
})

addSearchAliasX(
  'tw',
  'Twitter',
  'https://twitter.com/search?q='
)
mapkey('oT', '#8Open Search with alias tw', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'tw' })
})

addSearchAliasX(
  'w',
  'Wikipedia',
  'https://ja.wikipedia.org/w/index.php?search='
)
mapkey('ow', '#8Open Search with alias w', function() {
  Front.openOmnibar({ type: 'SearchEngine', extra: 'w' })
})

mapkey(';b', '#14Hatena Bookmark', () => {
  const { location } = window
  switch (location.protocol) {
    case 'http:': {
      tabOpenLink(
        `https://b.hatena.ne.jp/entry/${location.href.replace('http://', '')}`
      )
      break
    }
    case 'https:': {
      tabOpenLink(
        `https://b.hatena.ne.jp/entry/s/${location.href.replace('https://', '')}`
      )
      break
    }
    default: {
      throw new Error('Error')
    }
  }
})
// }}}

// {{{ qmarks
const qmarksUrls = {
  b: 'https://b.hatena.ne.jp',
  c: 'https://calendar.google.com',
  m: 'https://mail.google.com'
}
const qmarksMapKey = (prefix, urls, newTab) => {
  const openLink = (link, newTab) => () => {
    RUNTIME('openLink', {
      tab: { tabbed: newTab },
      url: link,
    })
  }
  for (const key in urls) {
    mapkey(prefix + key, `qmark: ${urls[key]}`, openLink(urls[key], newTab))
  }
}
qmarksMapKey('go', qmarksUrls, true)
qmarksMapKey('gO', qmarksUrls, false)
// }}}

// {{{ Images
const ri = { repeatIgnore: true }
const Hint = (selector, action = Hints.dispatchMouseClick) => () =>
  Hints.create(selector, action)
mapkey('gI', '#4View image in new tab', Hint('img', i => tabOpenLink(i.src)), ri)
mapkey('yI', '#7Copy Image URL', Hint('img', i => Clipboard.write(i.src)), ri)
// }}}

// {{{ Copy
const copyTitleAndUrl = format => {
  const text = format
    .replace('%URL%', location.href)
    .replace('%TITLE%', document.title)
  Clipboard.write(text)
}
mapkey('cm', '#7Copy title and link to markdown', () => {
  copyTitleAndUrl('[%TITLE%](%URL%)')
})
mapkey('ct', '#7Copy title and link to textile', () => {
  copyTitleAndUrl('"%TITLE%":%URL%')
})
mapkey('cj', '#7Copy title and link to jira', () => {
  const title = document.title.replace(/[|[]]/g, ' ').replace(/^ +/, '')
  Clipboard.write(`[${title}|${location.href}]`)
})
mapkey('ch', '#7Copy title and link to human readable', () => {
  copyTitleAndUrl('%TITLE% - %URL%')
})
// }}}

// {{{ Settings for each service
const clickElm = selector => () => document.querySelector(selector).click()
const clickElmFr = selector => () =>
  document
    .querySelector('.speakerdeck-iframe')
    .contentWindow.document.querySelector(selector)
    .click()

if (/speakerdeck\.com/.test(window.location.hostname)) {
  mapkey(']', 'next page', clickElmFr('.sd-player-next'))
  mapkey('[', 'prev page', clickElmFr('.sd-player-previous'))
}

if (/www\.slideshare\.net/.test(window.location.hostname)) {
  mapkey(']', 'next page', clickElm('.j-next-btn'))
  mapkey('[', 'prev page', clickElm('.j-prev-btn'))
}

if (/youtube\.com/.test(window.location.hostname)) {
  mapkey(
    'T',
    'Toggle theater mode',
    clickElm('.ytp-size-button.ytp-button'))
  mapkey(
    'F',
    'Toggle fullscreen',
    clickElm('.ytp-fullscreen-button.ytp-button'))
  mapkey(']', 'Skip ad', clickElm('.ytp-ad-text.ytp-ad-skip-button-text'))
  mapkey('<Alt-x>', 'Skip ad', clickElm('.ytp-ad-overlay-close-button'))
}
// }}}

// {{{ Modify the page's URL
if (/www.amazon.co.jp/.test(window.location.hostname)) {
  mapkey('==', '#14Shorten the URL', () => {
    location.href = `https://www.amazon.co.jp/dp/${
      document.querySelectorAll("[name='ASIN'], [name='ASIN.0']")[0].value
    }`
  })
}

const shortenURL = (pattern) => location.href = location.href.replace(pattern, '')
mapkey('=?', '#14Delete query string', () => shortenURL(/\?.*/))
mapkey('=q', '#14Delete query string', () => shortenURL(/\?.*/))
mapkey('=#', '#14Delete hash', () => shortenURL(/#.*/))
mapkey('=h', '#14Delete hash', () => shortenURL(/#.*/))
// }}}

// {{{ unmapAllExcept
const commonUnmapKeys = [
  '<Ctrl-f>', '<Ctrl-b>',
  '<Ctrl-d>', '<Ctrl-u>',
  '<Ctrl-y>', '<Ctrl-e>',
  '<Ctrl-n>', '<Ctrl-p>',
  '<Ctrl-t><Ctrl-t>',
  't', 'gn',
  'oT', 'oa', 'od', 'og',
  'oh', 'oi', 'om', 'on',
  'or', 'ot', 'ox', 'oy',
  'H', 'L',
  'f', 'F',
  'x', 'X', 'd',
  '>>', '<<',
  '<Alt-p>'
].concat(
  Object.keys(qmarksUrls).map(key => `gO${key}`)
)

unmapAllExcept(
  commonUnmapKeys,
  /mail\.google\.com/
)

unmapAllExcept(
  commonUnmapKeys.concat(['u', 'G', 'gg']).concat(
    Object.keys(qmarksUrls).map(key => `go${key}`)
  ),
  /outlook\.office\.com|b\.hatena\.ne\.jp|twitter\.com/
)
// }}}
<|endoftext|>


<commit_before>import { pick, assign } from 'lodash';

// will eventually hook into data loading/saving using the
// derived model's identifiedBy strings
export class BaseModel {

  constructor(attrs) {
    if (attrs) { this.update(attrs); }
  }

}

// export decorators so they can be easily imported into model classes
export {
  identifiedBy, identifier, hasMany, belongsTo, field, session,
} from 'mobx-decorated-models';

export {
  computed,
  observable,
} from 'mobx'
<commit_msg>missing ;<commit_after>import { pick, assign } from 'lodash';

// will eventually hook into data loading/saving using the
// derived model's identifiedBy strings
export class BaseModel {

  constructor(attrs) {
    if (attrs) { this.update(attrs); }
  }

}

// export decorators so they can be easily imported into model classes
export {
  identifiedBy, identifier, hasMany, belongsTo, field, session,
} from 'mobx-decorated-models';

export {
  computed,
  observable,
} from 'mobx';
<|endoftext|>