<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 ({
 	/**
 	 *  Test cancel button closes UISorterList.
 	 */
    testCancelButton : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");
        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        }, function(cmp) {
        //	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
 	 *  Test Apply button.
 	 */
    testApplyButton : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");
        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//click on Apply button
        	this.pressApply(listSorter);
        	defaultSortOrder = this.defaultSortOrder(listSorter);
        	sortApplied = this.getSortOrderApplied(cmp,"defaultListSorter");
        	$A.test.assertEquals(defaultSortOrder, sortApplied, "Sort not applied correctly after apply button was pressed.");
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Test title of Sort modal
     */
    testTitleOfSortPanel: {
        attributes : {title: 'Sort Panel'},
        test: function(cmp){
        	listSorter = cmp.find("defaultListSorter");
            $A.test.assertEquals("Sort Panel", $A.test.getText(listSorter.find("title").getElement()));
        }
    },

    /**
 	 *  Test sortOrderPicker and output(selectedItemOutput,selectedSortOrderOutput) of listSort dialog
 	 */
    testSortOrderPickerAndSelectedSortOutput : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");
        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	this.pressSortOrderButtonAndAssert(listSorter,"asc");
        }, function(cmp) {
        	this.pressSortOrderButtonAndAssert(listSorter,"dec");
        }, function(cmp) {
        	this.pressSortOrderButtonAndAssert(listSorter,"asc");
        }, function(cmp) {
        	this.selectSortByColumnAndAssert(listSorter, 1);
        }, function(cmp) {
        	this.selectSortByColumnAndAssert(listSorter, 2);
        }, function(cmp) {
        	this.selectSortByColumnAndAssert(listSorter, 4);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Test to verify all sortable columns present in the Sort dialog
     * and none of the hidden column visible
     */
    testAllSortableColumnsPresent : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");
        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//verify all sortable fields present on the dialog
        	this.verifyAllColumnsPresent(listSorter);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Test to check after pressing cancel and reopening list sorter resets
     * sorter state to default behavior.
     *
     */
    testPressCancelResetsSorterToDefaultState : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");

        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//Select column 4
        	this.selectSortByColumnAndAssert(listSorter, 4);
        }, function(cmp) {
        	//Sort by order A-Z
        	this.pressSortOrderButtonAndAssert(listSorter,"asc");
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//make sure the selected Column and order reset's to default selected column from model
        	this.verifyDefaultBehviour(listSorter);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Verify default Sort order and default Column is selected when
     * List Sorter is opened
     * Also make sure column selected is the active element on the page
     */
    testDefaultSortOrderSelection : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");

        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	this.verifyDefaultBehviour(listSorter);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Verify default Sort order and default Column is selected when
     * List Sorter is opened
     * Also make sure column selected is the active element on the page
     */
    verifyDefaultBehviour: function(listSorter){
    	var sortOrderButton = listSorter.find("decBtn").getElement();
    	//Verify Z-A buton selected
    	$A.test.assertTrue($A.util.hasClass(sortOrderButton,"selected"), "By Defauly Z-A Button should be selected");
    	//verify Sort Order label is correct
    	var sortOrderLabelValue = this.getSortOrderLabel(listSorter);
    	var defaultCoumn = "Column 2";
    	var defaultOrder = "Z-A"
    	var defaultSortOrder = defaultCoumn + ":" + defaultOrder;
    	$A.test.assertEquals(defaultSortOrder, sortOrderLabelValue, "Default Sort order Label displayed is not correct");
    	//column2 to should be selected by default
    	var menuItems =  this.getDisplayedColumns(listSorter);
    	var selectedColumn = this.getSelectedColumns(menuItems);
    	$A.test.assertEquals(defaultCoumn, selectedColumn, "Default Selected column is not correct");
    	//active element should be column 2
    	$A.test.assertEquals(defaultCoumn, $A.test.getActiveElementText(), "Default column 2 should be active element");
    },

    /**
     * select sortBy column and make sure its checked on the sort menu
     */
    selectSortByColumnAndAssert: function(listSorter, columnNumber){
    	var menuItem = this.getMenuItemByColumnNumber(listSorter,columnNumber);
    	menuItem.get('e.click').fire();
    	var expectedColumn = "Column " + columnNumber;
    	$A.test.addWaitForWithFailureMessage(expectedColumn, function(){
			var actualSelectedItemOutput = $A.test.getText(listSorter.find("selectedItemOutput").getElement());
    		return actualSelectedItemOutput;
			}, "Wrong Selected field displayed on Dialog");
    	//TODO: Uncomment below line after W-1985179 is fix
    	//$A.test.assertEquals(expectedColumn, $A.test.getActiveElementText(), expectedColumn + " should be focused");
    },

    /**
     * Click on pressSortOrderButton, pass in sortOrder ="asc" for A-Z and "dec" for Z-A
     */
    pressSortOrderButtonAndAssert : function(listSorter, sortOrder) {
    	var sortOrderButton = listSorter.find(sortOrder + "Btn").getElement();
		$A.test.clickOrTouch(sortOrderButton);
    	this.assertSortOrderOutput(listSorter, sortOrder);
    	$A.test.assertTrue($A.util.hasClass(sortOrderButton,"selected"), sortOrder + "Button should be selected");
    },

	/**
	 * Assert correct order is displayed on the page
	 */
	assertSortOrderOutput: function(listSorter, sortOrder){
		var expectedSortOrderOutput = "Z-A";
		if(sortOrder == "asc"){
			expectedSortOrderOutput = "A-Z";
		}
		$A.test.addWaitForWithFailureMessage(expectedSortOrderOutput, function(){
			var actualSortOuput = $A.test.getText(listSorter.find("selectedSortOrderOutput").getElement());
    		return actualSortOuput;
			}, "Wrong Sort Order displayed on Dialog");
	},

    /**
     * Return the field name and order which got applied after apply button was pressed
     */
    getSortOrderApplied: function(cmp, resultCmpId){
    	var output = cmp.find(resultCmpId+"Result");
    	return output.get("v.value");
    },

    /**
     * Click on trigger so that sorter is visible
     */
    openListSorter : function(trigger, listSorter) {
    	trigger.get("e.click").fire();
    	this.assertUISorterPresent(listSorter, true);
    },

    /**
     * Click on Apply
     */
    pressApply : function(listSorter) {
    	var applyButton = listSorter.find("set").getElement();
		$A.test.clickOrTouch(applyButton);
    	this.assertUISorterPresent(listSorter, false);
	},

    /**
     * Close the sorter by clicking on cancel
     */
    closeSorter : function(listSorter) {
    	var cancelButton = listSorter.find("cancel").getElement();
    	//cancelButton.click();
		$A.test.clickOrTouch(cancelButton);
    	this.assertUISorterPresent(listSorter, false);
    },

    /**
     * Verify cancel event did get fired
     */
    assertCancelEventFired : function(cmp)	{
    	$A.test.assertTrue(cmp.get('v.cancelEventFired'),"Cancel event did not get fired");
    },

    /**
     * check if sorter is visible on the page
     */
    assertUISorterPresent : function(listSorter, isPresent)	{
    	if(isPresent){
    		$A.test.addWaitForWithFailureMessage(isPresent, function(){return $A.util.hasClass(listSorter.find("sorterContainer").getElement(),"open");}, "List Sorter should be visible");
        }
    	else{
    		$A.test.addWaitForWithFailureMessage(isPresent, function(){return $A.util.hasClass(listSorter.find("sorterContainer").getElement(),"open");}, "List Sorter should not be visible");
        }
    },

    /**
     * Return the sortOrderLabel which is SelectedItem:SortOrder
     */
    getSortOrderLabel: function(listSorter){
    	var selectedField = $A.test.getText(listSorter.find("selectedItemOutput").getElement());
    	var selectedSortOrderOutput = $A.test.getText(listSorter.find("selectedSortOrderOutput").getElement());
    	var sortOrderLabel = selectedField + ":" + selectedSortOrderOutput;
    	return sortOrderLabel;
    },

    /**
     * Get all display columns including hidden one from the model
     */
    getColumnsFromModel: function(listSorter){
    	return listSorter.getValue("v.dataProvider").get(0).get("m.columns");
    },

    getDefaultOrderByListFromModel: function(listSorter){
    	return listSorter.getValue("v.dataProvider").get(0).get("m.defaultOrderByList");
    },

    defaultSortOrder: function(listSorter){
    	var defaultOrderObj = this.getDefaultOrderByListFromModel(listSorter)
    	var defaultOrder = [];
        for (var i = 0; i < defaultOrderObj.length; i++) {
        	var defaultField = defaultOrderObj[i];
        	var fieldName = defaultField.fieldName;
        	var sortOrder = defaultField.ascending ? "A-Z" : "Z-A";
        	defaultOrder.push(defaultField.fieldName + " : " +sortOrder);
        }
        return defaultOrder.join(",");
    },

    getDisplayedColumns: function(listSorter){
    	var menuCmp = listSorter.find("sorterMenuList");
        var menuItems = menuCmp.getValue("v.childMenuItems");
        return menuItems;
    },

    getSelectedColumns: function(menuItems){
    	var values = [];
        for (var i = 0; i < menuItems.getLength(); i++) {
            var c = menuItems.getValue(i);
            if (c.get("v.selected") === true) {
                values.push(c.get("v.label"));
            }
        }
        return values.join(",");
    },

    getAllColumnsLabel: function(menuItems){
    	var values = [];
        for (var i = 0; i < menuItems.getLength(); i++) {
            var c = menuItems.getValue(i);
            values.push(c.get("v.label"));
        }
        return values;
    },

    /**
     * Get menuItem component given columnNumber
     * First column = 1, 2nd Column = 2..
     */
    getMenuItemByColumnNumber: function(listSorter, columnNumber){
    	var menuItems = this.getDisplayedColumns(listSorter);
    	if (!$A.util.isUndefinedOrNull(menuItems.getValue(columnNumber - 1))) {
                return menuItems.getValue(columnNumber - 1);
    	}
    	$A.test.fail("Test fail! Column not present in the Sort Menu");
    },

    getOnlySortableColumnsFromModel: function(listSorter){
    	var columns = this.getColumnsFromModel(listSorter);
    	var sortableColumns = [];
        for (var i = 0; i < columns.length; i++) {
        	var column = columns[i];
            var isSortable = column.isSortable;
            if(isSortable === true){
                sortableColumns.push(column.label);
            }
        }
        return sortableColumns;
    },

    verifyAllColumnsPresent: function(listSorter){
    	var sortableColumnsFromModel = this.getOnlySortableColumnsFromModel(listSorter);
    	var menuItems = this.getDisplayedColumns(listSorter);
    	var columnsFromUI = this.getAllColumnsLabel(menuItems);
    	var hiddenColumnLabel = "Hidden Column";
    	$A.test.assertEquals(sortableColumnsFromModel.join(","), columnsFromUI.join(","), "Some columns are missing in UI Sorter which are sortable")
    	$A.test.assertFalse(hiddenColumnLabel.indexOf(columnsFromUI.join(",")) != -1, "Hidden Column should not be displayed on the page, list of columns diplayed:" + columnsFromUI.join(","))
//    	this.getMenuItemByColumnNumber(listSorter,1);
//    	this.getDefaultOrderByListFromModel(listSorter);
//    	menuItems=  this.getDisplayedColumns(listSorter);
//    	selectedColumn = this.getSelectedColumns(menuItems);
    }
})<commit_msg>Title: Fire cancel event test @bug W-1627220@<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 ({
 	/**
 	 *  Test cancel button closes UISorterList.
 	 */
    testCancelButton : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");
        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        }, function(cmp) {
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
 	 *  Test Apply button.
 	 */
    testApplyButton : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");
        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//click on Apply button
        	this.pressApply(listSorter);
        	defaultSortOrder = this.defaultSortOrder(listSorter);
        	sortApplied = this.getSortOrderApplied(cmp,"defaultListSorter");
        	$A.test.assertEquals(defaultSortOrder, sortApplied, "Sort not applied correctly after apply button was pressed.");
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Test title of Sort modal
     */
    testTitleOfSortPanel: {
        attributes : {title: 'Sort Panel'},
        test: function(cmp){
        	listSorter = cmp.find("defaultListSorter");
            $A.test.assertEquals("Sort Panel", $A.test.getText(listSorter.find("title").getElement()));
        }
    },

    /**
 	 *  Test sortOrderPicker and output(selectedItemOutput,selectedSortOrderOutput) of listSort dialog
 	 */
    testSortOrderPickerAndSelectedSortOutput : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");
        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	this.pressSortOrderButtonAndAssert(listSorter,"asc");
        }, function(cmp) {
        	this.pressSortOrderButtonAndAssert(listSorter,"dec");
        }, function(cmp) {
        	this.pressSortOrderButtonAndAssert(listSorter,"asc");
        }, function(cmp) {
        	this.selectSortByColumnAndAssert(listSorter, 1);
        }, function(cmp) {
        	this.selectSortByColumnAndAssert(listSorter, 2);
        }, function(cmp) {
        	this.selectSortByColumnAndAssert(listSorter, 4);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Test to verify all sortable columns present in the Sort dialog
     * and none of the hidden column visible
     */
    testAllSortableColumnsPresent : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");
        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//verify all sortable fields present on the dialog
        	this.verifyAllColumnsPresent(listSorter);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Test to check after pressing cancel and reopening list sorter resets
     * sorter state to default behavior.
     *
     */
    testPressCancelResetsSorterToDefaultState : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");

        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//Select column 4
        	this.selectSortByColumnAndAssert(listSorter, 4);
        }, function(cmp) {
        	//Sort by order A-Z
        	this.pressSortOrderButtonAndAssert(listSorter,"asc");
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	//make sure the selected Column and order reset's to default selected column from model
        	this.verifyDefaultBehviour(listSorter);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Verify default Sort order and default Column is selected when
     * List Sorter is opened
     * Also make sure column selected is the active element on the page
     */
    testDefaultSortOrderSelection : {
    	test: [function(cmp) {
    		listSorter = cmp.find("defaultListSorter");
        	trigger = cmp.find("defaultListSorterTrigger");

        	//check sorter not visible
        	this.assertUISorterPresent(listSorter, false);
        }, function(cmp) {
        	//open List Sorter
        	this.openListSorter(trigger,listSorter);
        }, function(cmp) {
        	this.verifyDefaultBehviour(listSorter);
        }, function(cmp) {
        	//Use cancel button to close the sorter
        	this.closeSorter(listSorter);
        	this.assertCancelEventFired(cmp);
    	}]
    },

    /**
     * Verify default Sort order and default Column is selected when
     * List Sorter is opened
     * Also make sure column selected is the active element on the page
     */
    verifyDefaultBehviour: function(listSorter){
    	var sortOrderButton = listSorter.find("decBtn").getElement();
    	//Verify Z-A buton selected
    	$A.test.assertTrue($A.util.hasClass(sortOrderButton,"selected"), "By Defauly Z-A Button should be selected");
    	//verify Sort Order label is correct
    	var sortOrderLabelValue = this.getSortOrderLabel(listSorter);
    	var defaultCoumn = "Column 2";
    	var defaultOrder = "Z-A"
    	var defaultSortOrder = defaultCoumn + ":" + defaultOrder;
    	$A.test.assertEquals(defaultSortOrder, sortOrderLabelValue, "Default Sort order Label displayed is not correct");
    	//column2 to should be selected by default
    	var menuItems =  this.getDisplayedColumns(listSorter);
    	var selectedColumn = this.getSelectedColumns(menuItems);
    	$A.test.assertEquals(defaultCoumn, selectedColumn, "Default Selected column is not correct");
    	//active element should be column 2
    	$A.test.assertEquals(defaultCoumn, $A.test.getActiveElementText(), "Default column 2 should be active element");
    },

    /**
     * select sortBy column and make sure its checked on the sort menu
     */
    selectSortByColumnAndAssert: function(listSorter, columnNumber){
    	var menuItem = this.getMenuItemByColumnNumber(listSorter,columnNumber);
    	menuItem.get('e.click').fire();
    	var expectedColumn = "Column " + columnNumber;
    	$A.test.addWaitForWithFailureMessage(expectedColumn, function(){
			var actualSelectedItemOutput = $A.test.getText(listSorter.find("selectedItemOutput").getElement());
    		return actualSelectedItemOutput;
			}, "Wrong Selected field displayed on Dialog");
    	//TODO: Uncomment below line after W-1985179 is fix
    	//$A.test.assertEquals(expectedColumn, $A.test.getActiveElementText(), expectedColumn + " should be focused");
    },

    /**
     * Click on pressSortOrderButton, pass in sortOrder ="asc" for A-Z and "dec" for Z-A
     */
    pressSortOrderButtonAndAssert : function(listSorter, sortOrder) {
    	var sortOrderButton = listSorter.find(sortOrder + "Btn").getElement();
		$A.test.clickOrTouch(sortOrderButton);
    	this.assertSortOrderOutput(listSorter, sortOrder);
    	$A.test.assertTrue($A.util.hasClass(sortOrderButton,"selected"), sortOrder + "Button should be selected");
    },

	/**
	 * Assert correct order is displayed on the page
	 */
	assertSortOrderOutput: function(listSorter, sortOrder){
		var expectedSortOrderOutput = "Z-A";
		if(sortOrder == "asc"){
			expectedSortOrderOutput = "A-Z";
		}
		$A.test.addWaitForWithFailureMessage(expectedSortOrderOutput, function(){
			var actualSortOuput = $A.test.getText(listSorter.find("selectedSortOrderOutput").getElement());
    		return actualSortOuput;
			}, "Wrong Sort Order displayed on Dialog");
	},

    /**
     * Return the field name and order which got applied after apply button was pressed
     */
    getSortOrderApplied: function(cmp, resultCmpId){
    	var output = cmp.find(resultCmpId+"Result");
    	return output.get("v.value");
    },

    /**
     * Click on trigger so that sorter is visible
     */
    openListSorter : function(trigger, listSorter) {
    	trigger.get("e.click").fire();
    	this.assertUISorterPresent(listSorter, true);
    },

    /**
     * Click on Apply
     */
    pressApply : function(listSorter) {
    	var applyButton = listSorter.find("set").getElement();
		$A.test.clickOrTouch(applyButton);
    	this.assertUISorterPresent(listSorter, false);
	},

    /**
     * Close the sorter by clicking on cancel
     */
    closeSorter : function(listSorter) {
    	var cancelButton = listSorter.find("cancel").getElement();
    	//cancelButton.click();
		$A.test.clickOrTouch(cancelButton);
    	this.assertUISorterPresent(listSorter, false);
    },

    /**
     * Verify cancel event did get fired
     */
    assertCancelEventFired : function(cmp)	{
    	$A.test.assertTrue(cmp.get('v.cancelEventFired'),"Cancel event did not get fired");
    },

    /**
     * check if sorter is visible on the page
     */
    assertUISorterPresent : function(listSorter, isPresent)	{
    	if(isPresent){
    		$A.test.addWaitForWithFailureMessage(isPresent, function(){return $A.util.hasClass(listSorter.find("sorterContainer").getElement(),"open");}, "List Sorter should be visible");
        }
    	else{
    		$A.test.addWaitForWithFailureMessage(isPresent, function(){return $A.util.hasClass(listSorter.find("sorterContainer").getElement(),"open");}, "List Sorter should not be visible");
        }
    },

    /**
     * Return the sortOrderLabel which is SelectedItem:SortOrder
     */
    getSortOrderLabel: function(listSorter){
    	var selectedField = $A.test.getText(listSorter.find("selectedItemOutput").getElement());
    	var selectedSortOrderOutput = $A.test.getText(listSorter.find("selectedSortOrderOutput").getElement());
    	var sortOrderLabel = selectedField + ":" + selectedSortOrderOutput;
    	return sortOrderLabel;
    },

    /**
     * Get all display columns including hidden one from the model
     */
    getColumnsFromModel: function(listSorter){
    	return listSorter.getValue("v.dataProvider").get(0).get("m.columns");
    },

    getDefaultOrderByListFromModel: function(listSorter){
    	return listSorter.getValue("v.dataProvider").get(0).get("m.defaultOrderByList");
    },

    defaultSortOrder: function(listSorter){
    	var defaultOrderObj = this.getDefaultOrderByListFromModel(listSorter)
    	var defaultOrder = [];
        for (var i = 0; i < defaultOrderObj.length; i++) {
        	var defaultField = defaultOrderObj[i];
        	var fieldName = defaultField.fieldName;
        	var sortOrder = defaultField.ascending ? "A-Z" : "Z-A";
        	defaultOrder.push(defaultField.fieldName + " : " +sortOrder);
        }
        return defaultOrder.join(",");
    },

    getDisplayedColumns: function(listSorter){
    	var menuCmp = listSorter.find("sorterMenuList");
        var menuItems = menuCmp.getValue("v.childMenuItems");
        return menuItems;
    },

    getSelectedColumns: function(menuItems){
    	var values = [];
        for (var i = 0; i < menuItems.getLength(); i++) {
            var c = menuItems.getValue(i);
            if (c.get("v.selected") === true) {
                values.push(c.get("v.label"));
            }
        }
        return values.join(",");
    },

    getAllColumnsLabel: function(menuItems){
    	var values = [];
        for (var i = 0; i < menuItems.getLength(); i++) {
            var c = menuItems.getValue(i);
            values.push(c.get("v.label"));
        }
        return values;
    },

    /**
     * Get menuItem component given columnNumber
     * First column = 1, 2nd Column = 2..
     */
    getMenuItemByColumnNumber: function(listSorter, columnNumber){
    	var menuItems = this.getDisplayedColumns(listSorter);
    	if (!$A.util.isUndefinedOrNull(menuItems.getValue(columnNumber - 1))) {
                return menuItems.getValue(columnNumber - 1);
    	}
    	$A.test.fail("Test fail! Column not present in the Sort Menu");
    },

    getOnlySortableColumnsFromModel: function(listSorter){
    	var columns = this.getColumnsFromModel(listSorter);
    	var sortableColumns = [];
        for (var i = 0; i < columns.length; i++) {
        	var column = columns[i];
            var isSortable = column.isSortable;
            if(isSortable === true){
                sortableColumns.push(column.label);
            }
        }
        return sortableColumns;
    },

    verifyAllColumnsPresent: function(listSorter){
    	var sortableColumnsFromModel = this.getOnlySortableColumnsFromModel(listSorter);
    	var menuItems = this.getDisplayedColumns(listSorter);
    	var columnsFromUI = this.getAllColumnsLabel(menuItems);
    	var hiddenColumnLabel = "Hidden Column";
    	$A.test.assertEquals(sortableColumnsFromModel.join(","), columnsFromUI.join(","), "Some columns are missing in UI Sorter which are sortable")
    	$A.test.assertFalse(hiddenColumnLabel.indexOf(columnsFromUI.join(",")) != -1, "Hidden Column should not be displayed on the page, list of columns diplayed:" + columnsFromUI.join(","))
//    	this.getMenuItemByColumnNumber(listSorter,1);
//    	this.getDefaultOrderByListFromModel(listSorter);
//    	menuItems=  this.getDisplayedColumns(listSorter);
//    	selectedColumn = this.getSelectedColumns(menuItems);
    }
})<|endoftext|>


<commit_before>/*
 * Copyright 2016 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

define([
    'find/app/page/search/abstract-query-left-side-view',
    'backbone',
    'i18n!find/nls/bundle'
], function(AbstractQueryLeftSideView, Backbone, i18n) {

    var MATCH_NOTHING = 'y54u65u4w5uy654u5eureuy654yht754wy54euy45';

    describe("Abstract Query Left Side View", function() {

        beforeEach(function() {
            this.view = new (AbstractQueryLeftSideView.extend({
                IndexesView: Backbone.View.extend({
                    initialize: function(options) {
                        this.visibleIndexesCallback = options.visibleIndexesCallback;
                    }
                })
            }))({
                queryState: {}
            });
        });

        describe('dates filter', function() {
            it('should not display when the filter does not match the bundle string for dates', function() {
                this.view.filterModel.set('text', MATCH_NOTHING);

                expect(this.view.dateViewWrapper.$el).toHaveClass('hide');

            });

            it('should display when the filter is the empty string', function() {
                this.view.filterModel.set('text', '');

                expect(this.view.dateViewWrapper.$el).not.toHaveClass('hide');
                expect(this.view.$emptyMessage).toHaveClass('hide');
            });

            it('should display when the filter incompletely matches the bundle string for dates', function() {
                this.view.filterModel.set('text', i18n['search.dates'].substring(0,3));

                expect(this.view.dateViewWrapper.$el).not.toHaveClass('hide');
                expect(this.view.$emptyMessage).toHaveClass('hide');
            });
        });

        describe('indexes filter', function() {
            it('should display when the visibleIndexesCallback is called with a non-empty array', function() {
                this.view.indexesViewWrapper.view.visibleIndexesCallback(['index1', 'index2', 'index3']);

                expect(this.view.indexesViewWrapper.view.$el).not.toHaveClass('hide');
                expect(this.view.$emptyMessage).toHaveClass('hide');

            });

            it('should not display when the visibleIndexesCallback is called with the empty array', function() {
                this.view.indexesViewWrapper.view.visibleIndexesCallback([]);

                expect(this.view.indexesViewWrapper.$el).toHaveClass('hide');
            });
        });

        describe('parametric values filter', function() {
            beforeEach(function() {
                this.view.parametricDisplayCollection.reset();
            });

            describe('with parametric values and the filter set to the empty string', function() {
                beforeEach(function() {
                    this.view.filterModel.set('');
                });

                it('should display when the displayCollection is not empty', function() {
                    this.view.parametricDisplayCollection.add({fakeAttribute: true});

                    expect(this.view.parametricView.$el).not.toHaveClass('hide');
                    expect(this.view.$emptyMessage).toHaveClass('hide');
                });

                it('should not be displayed when there are no parametric values matching the filter', function() {
                    this.view.filterModel.set('text', MATCH_NOTHING);

                    expect(this.view.parametricView.$el).toHaveClass('hide');
                })
            });

            describe('with no parametric values', function() {
                it('should display when the filter is empty', function() {
                    this.view.filterModel.set('text', '');

                    expect(this.view.parametricView.$el).not.toHaveClass('hide');
                    expect(this.view.$emptyMessage).toHaveClass('hide');
                });

                it('should not display when the filter is non-empty', function() {
                    this.view.filterModel.set('text', MATCH_NOTHING);

                    expect(this.view.parametricView.$el).toHaveClass('hide');
                });
            })
        });

        it('should display the no filters matched message and hide everything when no filters are matched', function() {
            this.view.indexesViewWrapper.view.visibleIndexesCallback([]);
            this.view.filterModel.set('text', MATCH_NOTHING);

            expect(this.view.dateViewWrapper.$el).toHaveClass('hide');
            expect(this.view.indexesViewWrapper.$el).toHaveClass('hide');
            expect(this.view.parametricView.$el).toHaveClass('hide');
            expect(this.view.$emptyMessage).not.toHaveClass('hide');
        });
    });

});
<commit_msg>FIND-12 Numeric field search widget :: fix and write some tests<commit_after>/*
 * Copyright 2016 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

define([
    'find/app/page/search/abstract-query-left-side-view',
    'backbone',
    'i18n!find/nls/bundle',
    'js-testing/backbone-mock-factory'
], function(AbstractQueryLeftSideView, Backbone, i18n, backboneMockFactory) {

    var MATCH_NOTHING = 'y54u65u4w5uy654u5eureuy654yht754wy54euy45';

    describe("Abstract Query Left Side View", function() {

        beforeEach(function() {
            this.view = new (AbstractQueryLeftSideView.extend({
                IndexesView: Backbone.View.extend({
                    initialize: function(options) {
                        this.visibleIndexesCallback = options.visibleIndexesCallback;
                    }
                })
            }))({
                queryState: {},
                numericParametricCollection: new (backboneMockFactory.getCollection())()
            });
        });

        describe('dates filter', function() {
            it('should not display when the filter does not match the bundle string for dates', function() {
                this.view.filterModel.set('text', MATCH_NOTHING);

                expect(this.view.dateViewWrapper.$el).toHaveClass('hide');

            });

            it('should display when the filter is the empty string', function() {
                this.view.filterModel.set('text', '');

                expect(this.view.dateViewWrapper.$el).not.toHaveClass('hide');
                expect(this.view.$emptyMessage).toHaveClass('hide');
            });

            it('should display when the filter incompletely matches the bundle string for dates', function() {
                this.view.filterModel.set('text', i18n['search.dates'].substring(0,3));

                expect(this.view.dateViewWrapper.$el).not.toHaveClass('hide');
                expect(this.view.$emptyMessage).toHaveClass('hide');
            });
        });

        describe('indexes filter', function() {
            it('should display when the visibleIndexesCallback is called with a non-empty array', function() {
                this.view.indexesViewWrapper.view.visibleIndexesCallback(['index1', 'index2', 'index3']);

                expect(this.view.indexesViewWrapper.view.$el).not.toHaveClass('hide');
                expect(this.view.$emptyMessage).toHaveClass('hide');

            });

            it('should not display when the visibleIndexesCallback is called with the empty array', function() {
                this.view.indexesViewWrapper.view.visibleIndexesCallback([]);

                expect(this.view.indexesViewWrapper.$el).toHaveClass('hide');
            });
        });

        describe('numeric parametric values filter', function() {
            beforeEach(function() {
                this.view.numericParametricCollection.reset();
            });

            describe('with numeric parametric values and the filter set to the empty string', function() {
                beforeEach(function() {
                    this.view.filterModel.set('');
                });

                it('should display when the displayCollection is not empty', function() {
                    this.view.numericParametricCollection.add({fakeAttribute: true});

                    expect(this.view.numericParametricView.$el).not.toHaveClass('hide');
                    expect(this.view.$emptyMessage).toHaveClass('hide');
                });

                it('should not be displayed when there are no numeric parametric values matching the filter', function() {
                    this.view.filterModel.set('text', MATCH_NOTHING);

                    expect(this.view.numericParametricView.$el).toHaveClass('hide');
                })
            });

            describe('with no numeric parametric values', function() {
                it('should display when the filter is empty', function() {
                    this.view.filterModel.set('text', '');

                    expect(this.view.numericParametricView.$el).not.toHaveClass('hide');
                    expect(this.view.$emptyMessage).toHaveClass('hide');
                });

                it('should not display when the filter is non-empty', function() {
                    this.view.filterModel.set('text', MATCH_NOTHING);

                    expect(this.view.numericParametricView.$el).toHaveClass('hide');
                });
            })
        });

        describe('parametric values filter', function() {
            beforeEach(function() {
                this.view.parametricDisplayCollection.reset();
            });

            describe('with parametric values and the filter set to the empty string', function() {
                beforeEach(function() {
                    this.view.filterModel.set('');
                });

                it('should display when the displayCollection is not empty', function() {
                    this.view.parametricDisplayCollection.add({fakeAttribute: true});

                    expect(this.view.parametricView.$el).not.toHaveClass('hide');
                    expect(this.view.$emptyMessage).toHaveClass('hide');
                });

                it('should not be displayed when there are no parametric values matching the filter', function() {
                    this.view.filterModel.set('text', MATCH_NOTHING);

                    expect(this.view.parametricView.$el).toHaveClass('hide');
                })
            });

            describe('with no parametric values', function() {
                it('should display when the filter is empty', function() {
                    this.view.filterModel.set('text', '');

                    expect(this.view.parametricView.$el).not.toHaveClass('hide');
                    expect(this.view.$emptyMessage).toHaveClass('hide');
                });

                it('should not display when the filter is non-empty', function() {
                    this.view.filterModel.set('text', MATCH_NOTHING);

                    expect(this.view.parametricView.$el).toHaveClass('hide');
                });
            })
        });

        it('should display the no filters matched message and hide everything when no filters are matched', function() {
            this.view.indexesViewWrapper.view.visibleIndexesCallback([]);
            this.view.filterModel.set('text', MATCH_NOTHING);

            expect(this.view.dateViewWrapper.$el).toHaveClass('hide');
            expect(this.view.indexesViewWrapper.$el).toHaveClass('hide');
            expect(this.view.parametricView.$el).toHaveClass('hide');
            expect(this.view.$emptyMessage).not.toHaveClass('hide');
        });
    });

});
<|endoftext|>


<commit_before>import type { Dispatch, Store } from "redux";

declare module "react-redux" {
  import type { ComponentType, ElementConfig } from 'react';

  declare export class Provider<S, A> extends React$Component<{
    store: Store<S, A>,
    children?: any
  }> {}

  declare export function createProvider(
    storeKey?: string,
    subKey?: string
  ): Provider<*, *>;

  /*

  S = State
  A = Action
  OP = OwnProps
  SP = StateProps
  DP = DispatchProps
  MP = Merge props
  MDP = Map dispatch to props object
  RSP = Returned state props
  RDP = Returned dispatch props
  RMP = Returned merge props
  CP = Props for returned component
  Com = React Component
  ST = Static properties of Com
  */

  declare type MapStateToProps<S: Object, SP: Object, RSP: Object> = (state: S, props: SP) => RSP;

  declare type MapDispatchToProps<A, OP: Object, RDP: Object> = (dispatch: Dispatch<A>, ownProps: OP) => RDP;

  declare type MergeProps<SP: Object, DP: Object, MP: Object, RMP: Object> = (
    stateProps: SP,
    dispatchProps: DP,
    ownProps: MP
  ) => RMP;

  declare type ConnectOptions<S: Object, OP: Object, RSP: Object, RMP: Object> = {|
    pure?: boolean,
    withRef?: boolean,
    areStatesEqual?: (next: S, prev: S) => boolean,
    areOwnPropsEqual?: (next: OP, prev: OP) => boolean,
    areStatePropsEqual?: (next: RSP, prev: RSP) => boolean,
    areMergedPropsEqual?: (next: RMP, prev: RMP) => boolean,
    storeKey?: string
  |};

  declare type OmitDispatch<Component> = $Diff<Component, {dispatch: Dispatch<*>}>;

  declare export function connect<
    Com: ComponentType<*>,
    S: Object,
    SP: Object,
    RSP: Object,
    CP: $Diff<OmitDispatch<ElementConfig<Com>>, RSP>,
    ST: {[_: $Keys<Com>]: any}
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps?: null
  ): (component: Com) => ComponentType<CP & SP> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    ST: {[_: $Keys<Com>]: any}
    >(
    mapStateToProps?: null,
    mapDispatchToProps?: null
  ): (component: Com) => ComponentType<OmitDispatch<ElementConfig<Com>>> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    CP: $Diff<$Diff<ElementConfig<Com>, RSP>, RDP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: MapDispatchToProps<A, DP, RDP>
  ): (component: Com) => ComponentType<CP & SP & DP> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    A,
    OP: Object,
    DP: Object,
    PR: Object,
    CP: $Diff<ElementConfig<Com>, DP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps?: null,
    mapDispatchToProps: MapDispatchToProps<A, OP, DP>
  ): (Com) => ComponentType<CP & OP>;

  declare export function connect<
    Com: ComponentType<*>,
    MDP: Object,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps?: null,
    mapDispatchToProps: MDP
  ): (component: Com) => ComponentType<$Diff<ElementConfig<Com>, MDP>> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    S: Object,
    SP: Object,
    RSP: Object,
    MDP: Object,
    CP: $Diff<ElementConfig<Com>, RSP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: MDP
  ): (component: Com) => ComponentType<$Diff<CP, MDP> & SP> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    MP: Object,
    RMP: Object,
    CP: $Diff<ElementConfig<Com>, RMP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: ?MapDispatchToProps<A, DP, RDP>,
    mergeProps: MergeProps<RSP, RDP, MP, RMP>
  ): (component: Com) => ComponentType<CP & SP & DP & MP> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    MDP: Object,
    MP: Object,
    RMP: Object,
    CP: $Diff<ElementConfig<Com>, RMP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: MDP,
    mergeProps: MergeProps<RSP, RDP, MP, RMP>
  ): (component: Com) => ComponentType<CP & SP & DP & MP> & $Shape<ST>;

  declare export function connect<Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    MP: Object,
    RMP: Object,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: ?MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: ?MapDispatchToProps<A, DP, RDP>,
    mergeProps: ?MergeProps<RSP, RDP, MP, RMP>,
    options: ConnectOptions<S, SP & DP & MP, RSP, RMP>
  ): (component: Com) => ComponentType<$Diff<ElementConfig<Com>, RMP> & SP & DP & MP> & $Shape<ST>;

  declare export function connect<Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    MDP: Object,
    MP: Object,
    RMP: Object,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: ?MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: ?MapDispatchToProps<A, DP, RDP>,
    mergeProps: MDP,
    options: ConnectOptions<S, SP & DP & MP, RSP, RMP>
  ): (component: Com) => ComponentType<$Diff<ElementConfig<Com>, RMP> & SP & DP & MP> & $Shape<ST>;

  declare export default {
    Provider: typeof Provider,
    createProvider: typeof createProvider,
    connect: typeof connect,
  };
}
<commit_msg>fix type coverage on react-redux's connect (#2530)<commit_after>declare module "react-redux" {
  import type { ComponentType, ElementConfig } from 'react';

  // These types are copied directly from the redux libdef. Importing them in
  // this libdef causes a loss in type coverage.
  declare type DispatchAPI<A> = (action: A) => A;
  declare type Dispatch<A: { type: $Subtype<string> }> = DispatchAPI<A>;
  declare type Reducer<S, A> = (state: S | void, action: A) => S;
  declare type Store<S, A, D = Dispatch<A>> = {
    dispatch: D;
    getState(): S;
    subscribe(listener: () => void): () => void;
    replaceReducer(nextReducer: Reducer<S, A>): void
  };

  declare export class Provider<S, A> extends React$Component<{
    store: Store<S, A>,
    children?: any
  }> {}

  declare export function createProvider(
    storeKey?: string,
    subKey?: string
  ): Provider<*, *>;

  /*

  S = State
  A = Action
  OP = OwnProps
  SP = StateProps
  DP = DispatchProps
  MP = Merge props
  MDP = Map dispatch to props object
  RSP = Returned state props
  RDP = Returned dispatch props
  RMP = Returned merge props
  CP = Props for returned component
  Com = React Component
  ST = Static properties of Com
  */

  declare type MapStateToProps<S: Object, SP: Object, RSP: Object> = (state: S, props: SP) => RSP;

  declare type MapDispatchToProps<A, OP: Object, RDP: Object> = (dispatch: Dispatch<A>, ownProps: OP) => RDP;

  declare type MergeProps<SP: Object, DP: Object, MP: Object, RMP: Object> = (
    stateProps: SP,
    dispatchProps: DP,
    ownProps: MP
  ) => RMP;

  declare type ConnectOptions<S: Object, OP: Object, RSP: Object, RMP: Object> = {|
    pure?: boolean,
    withRef?: boolean,
    areStatesEqual?: (next: S, prev: S) => boolean,
    areOwnPropsEqual?: (next: OP, prev: OP) => boolean,
    areStatePropsEqual?: (next: RSP, prev: RSP) => boolean,
    areMergedPropsEqual?: (next: RMP, prev: RMP) => boolean,
    storeKey?: string
  |};

  declare type OmitDispatch<Component> = $Diff<Component, {dispatch?: Dispatch<*>}>;

  declare export function connect<
    Com: ComponentType<*>,
    S: Object,
    SP: Object,
    RSP: Object,
    CP: $Diff<OmitDispatch<ElementConfig<Com>>, RSP>,
    ST: {[_: $Keys<Com>]: any}
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps?: null
  ): (component: Com) => ComponentType<CP & SP> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    ST: {[_: $Keys<Com>]: any}
    >(
    mapStateToProps?: null,
    mapDispatchToProps?: null
  ): (component: Com) => ComponentType<OmitDispatch<ElementConfig<Com>>> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    CP: $Diff<$Diff<ElementConfig<Com>, RSP>, RDP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: MapDispatchToProps<A, DP, RDP>
  ): (component: Com) => ComponentType<CP & SP & DP> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    A,
    OP: Object,
    DP: Object,
    PR: Object,
    CP: $Diff<ElementConfig<Com>, DP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps?: null,
    mapDispatchToProps: MapDispatchToProps<A, OP, DP>
  ): (Com) => ComponentType<CP & OP>;

  declare export function connect<
    Com: ComponentType<*>,
    MDP: Object,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps?: null,
    mapDispatchToProps: MDP
  ): (component: Com) => ComponentType<$Diff<ElementConfig<Com>, MDP>> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    S: Object,
    SP: Object,
    RSP: Object,
    MDP: Object,
    CP: $Diff<ElementConfig<Com>, RSP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: MDP
  ): (component: Com) => ComponentType<$Diff<CP, MDP> & SP> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    MP: Object,
    RMP: Object,
    CP: $Diff<ElementConfig<Com>, RMP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: ?MapDispatchToProps<A, DP, RDP>,
    mergeProps: MergeProps<RSP, RDP, MP, RMP>
  ): (component: Com) => ComponentType<CP & SP & DP & MP> & $Shape<ST>;

  declare export function connect<
    Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    MDP: Object,
    MP: Object,
    RMP: Object,
    CP: $Diff<ElementConfig<Com>, RMP>,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: MDP,
    mergeProps: MergeProps<RSP, RDP, MP, RMP>
  ): (component: Com) => ComponentType<CP & SP & DP & MP> & $Shape<ST>;

  declare export function connect<Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    MP: Object,
    RMP: Object,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: ?MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: ?MapDispatchToProps<A, DP, RDP>,
    mergeProps: ?MergeProps<RSP, RDP, MP, RMP>,
    options: ConnectOptions<S, SP & DP & MP, RSP, RMP>
  ): (component: Com) => ComponentType<$Diff<ElementConfig<Com>, RMP> & SP & DP & MP> & $Shape<ST>;

  declare export function connect<Com: ComponentType<*>,
    A,
    S: Object,
    DP: Object,
    SP: Object,
    RSP: Object,
    RDP: Object,
    MDP: Object,
    MP: Object,
    RMP: Object,
    ST: $Subtype<{[_: $Keys<Com>]: any}>
    >(
    mapStateToProps: ?MapStateToProps<S, SP, RSP>,
    mapDispatchToProps: ?MapDispatchToProps<A, DP, RDP>,
    mergeProps: MDP,
    options: ConnectOptions<S, SP & DP & MP, RSP, RMP>
  ): (component: Com) => ComponentType<$Diff<ElementConfig<Com>, RMP> & SP & DP & MP> & $Shape<ST>;

  declare export default {
    Provider: typeof Provider,
    createProvider: typeof createProvider,
    connect: typeof connect,
  };
}
<|endoftext|>


<commit_before>
import { navUserAcctDropdownBtnSelector } from './../support/variables';

/**
* Test you can visit the Biosample create page.
*/
describe('Biosample create page', function () {

    context('Cypress test user profile create biosample page', function () {

        var testItemsToDelete = [];
        it('Main page visit', function () {
            cy.visit('/');
        });

        it('Ensure logged in, visit biosample create page ', function () {

            //Login CypressTest user
            cy.login4DN({ 'email': 'u4dntestcypress@gmail.com' }).end()
                .get(navUserAcctDropdownBtnSelector).then((accountListItem) => {
                    expect(accountListItem.text()).to.contain('Cypress');
                }).end();
            cy.visit('/search/?type=Biosample').get(".above-results-table-row .btn").should('contain', 'Create New')
                .get("a.btn.btn-primary.btn").should('contain', 'Create New').click().end().wait(10000);

            //Submit create biosample data name
            const identifier = ("bs-test-" + new Date().getTime());
            cy.get('.modal-dialog input#aliasInput.form-control').focus().type(identifier).wait(100).end()
                .get("button.btn-primary.btn").should('contain', 'Submit').click().end().wait(10000);
            cy.get('.field-row [data-field-name=biosource] .linked-object-buttons-container .select-create-linked-item-button').first().should('contain', 'Select existing').click().end();

            //Add biosources data file
            cy.get('.array-field-container  .field-row .field-column .linked-object-text-input-container  .form-control').focus().type('111116bc-8535-4448-903e-854af460b254').wait(100).end();

            //Biosource data file check succes
            cy.get('.remove-button-container .btn-success').click().end().wait(10000)
                //Click Validate button
                .get(".action-buttons-container .btn").within(function () {
                    return cy.contains('Validate').click().end();
                }).end()
                //Click Submit button
                .get(".action-buttons-container .btn").within(function () {
                    return cy.contains('Submit').click().end().wait(500);
                }).end()
                //Navigate new biosample data page
                .get(".action-buttons-container .btn").within(function () {
                    return cy.contains('Skip').click().end().wait(1000);
                }).end();

            afterEach(function () {
                cy.get('script[data-prop-name=context]').then(($context) => {
                    const context = $context.text();
                    const contextData = JSON.parse(context);
                    const atId = contextData['@id'];
                    testItemsToDelete.push(atId);//Test biosample data @id
                });

            });

        });
        it('Biosample delete data', function () {

            // Log in _as admin_.
            cy.visit('/').login4DN({ 'email': '4dndcic@gmail.com', 'useEnvToken': true }).wait(500);

            // Delete item biosample data.
            cy.wrap(testItemsToDelete).each(function (testItem) { // Synchronously process async stuff.
                cy.window().then(function (w) {
                    const token = w.fourfront.JWT.get();
                    cy.request({
                        method: "DELETE",
                        url: testItem,
                        headers: {
                            'Authorization': 'Bearer ' + token,
                            "Content-Type": "application/json",
                            "Accept": "application/json"
                        }
                    }).end().request({
                        method: "PATCH",
                        url: testItem,
                        headers: {
                            'Authorization': 'Bearer ' + token,
                            "Content-Type": "application/json",
                            "Accept": "application/json"
                        },
                        body: JSON.stringify({ "tags": ["deleted_by_cypress_test"] })
                    });
                });
            });

            // Empty the array now that we're done.
            testItemsToDelete = [];
        });
    });
});

<commit_msg>cypress test 9a biosource update<commit_after>
import { navUserAcctDropdownBtnSelector } from './../support/variables';

/**
* Test you can visit the Biosample create page.
*/
describe('Biosample create page', function () {

    context('Cypress test user profile create biosample page', function () {

        var testItemsToDelete = [];
        it('Main page visit', function () {
            cy.visit('/');
        });

        it('Ensure logged in, visit biosample create page ', function () {

            //Login CypressTest user
            cy.login4DN({ 'email': 'u4dntestcypress@gmail.com' }).end()
                .get(navUserAcctDropdownBtnSelector).then((accountListItem) => {
                    expect(accountListItem.text()).to.contain('Cypress');
                }).end();
            cy.visit('/search/?type=Biosample').get(".above-results-table-row .btn").should('contain', 'Create New')
                .get("a.btn.btn-primary.btn").should('contain', 'Create New').click().end().wait(10000);

            //Submit create biosample data name
            const identifier = ("bs-test-" + new Date().getTime());
            cy.get('.modal-dialog input#aliasInput.form-control').focus().type(identifier).wait(100).end()
                .get("button.btn-primary.btn").should('contain', 'Submit').click().end().wait(10000);
            cy.get('.field-row [data-field-name=biosource] .linked-object-buttons-container .select-create-linked-item-button').first().should('contain', 'Select existing').click().end();

            //Add biosources data file
            cy.get('.array-field-container  .field-row .field-column .linked-object-text-input-container  .form-control').focus().type('0f011b1e-b772-4f2a-8c24-cc55de28a994').wait(100).end();

            //Biosource data file check succes
            cy.get('.remove-button-container .btn-success').click().end().wait(10000)
                //Click Validate button
                .get(".action-buttons-container .btn").within(function () {
                    return cy.contains('Validate').click().end();
                }).end()
                //Click Submit button
                .get(".action-buttons-container .btn").within(function () {
                    return cy.contains('Submit').click().end().wait(500);
                }).end()
                //Navigate new biosample data page
                .get(".action-buttons-container .btn").within(function () {
                    return cy.contains('Skip').click().end().wait(1000);
                }).end();

            afterEach(function () {
                cy.get('script[data-prop-name=context]').then(($context) => {
                    const context = $context.text();
                    const contextData = JSON.parse(context);
                    const atId = contextData['@id'];
                    testItemsToDelete.push(atId);//Test biosample data @id
                });

            });

        });
        it('Biosample delete data', function () {

            // Log in _as admin_.
            cy.visit('/').login4DN({ 'email': '4dndcic@gmail.com', 'useEnvToken': true }).wait(500);

            // Delete item biosample data.
            cy.wrap(testItemsToDelete).each(function (testItem) { // Synchronously process async stuff.
                cy.window().then(function (w) {
                    const token = w.fourfront.JWT.get();
                    cy.request({
                        method: "DELETE",
                        url: testItem,
                        headers: {
                            'Authorization': 'Bearer ' + token,
                            "Content-Type": "application/json",
                            "Accept": "application/json"
                        }
                    }).end().request({
                        method: "PATCH",
                        url: testItem,
                        headers: {
                            'Authorization': 'Bearer ' + token,
                            "Content-Type": "application/json",
                            "Accept": "application/json"
                        },
                        body: JSON.stringify({ "tags": ["deleted_by_cypress_test"] })
                    });
                });
            });

            // Empty the array now that we're done.
            testItemsToDelete = [];
        });
    });
});

<|endoftext|>


<commit_before>const TEST_ENV = 'TEST';
const PROD_ENV = 'PROD';

class GoogleCalendarMoveToDate {
    // Maximum number of events to keep in a cell.
    #DEFAULT_MAX_EVENTS_PER_CELL = 14;

    // Oldest available cell date that has been found and should be used.
    topCellDate;

    constructor(options) {
        this.options = options;
        this.options.maxEventsPerCell = this.options.maxEventsPerCell || this.#DEFAULT_MAX_EVENTS_PER_CELL;
        this.env = options.env;
        this.debug = options.debug ? true : false;
    }

    findCellsInRow(row) {
        this.debug && console.info('findCellsInRow');
        this.debug && console.log('row:', row);
        var rowCells;
        if (this.env === PROD_ENV) {
            rowCells = row.querySelectorAll('[role="gridcell"]');
        } else if (this.env === TEST_ENV) {
            rowCells = row;
        }
        this.debug && console.log('rowCells:', rowCells);
        return rowCells;
    }

    clearTopCellDate() {
        this.debug && console.info('clearTopCellDate');
        this.topCellDate = undefined;
    }

    countEventsInCell(cell) {
        this.debug && console.info('countEventsInCell');
        this.debug && console.log('cell:', cell);
        var cellEventsFound;
        if (this.env === PROD_ENV) {
            var cellEvents = cell.querySelectorAll('[data-eventid]');
            cellEventsFound = cellEvents.length;
            var moreCellEvents = cell.querySelector('[data-opens-day-overview]');
            if (moreCellEvents) {
                cellEventsFound += parseInt(moreCellEvents.innerText.match(/(\d+) more/)[1]);
            }
        } else if (this.env === TEST_ENV) {
            var cellEvents = cell;
            cellEventsFound = cellEvents.length;
        }
        this.debug && console.log('cellEventsFound:', cellEventsFound);
        return cellEventsFound;
    }

    findTopCell(cells) {
        // Find first top-right most cell in current view containing a non-full number of events.
        this.debug && console.group('findTopCell');
        this.debug && console.log('cells:', cells);
        var topCell;

        // Check top to bottom.
        outer_loop:
        for (var rowIndex = 0; rowIndex < cells.length; rowIndex++) {
            this.debug && console.group('rowIndex:', rowIndex);

            var row = cells[rowIndex];
            this.debug && console.log('row:', row);

            var rowCells = this.findCellsInRow(row);
            // Check right to left.
            for (var cellIndex = rowCells.length - 1; cellIndex >= 0; cellIndex--) {
                this.debug && console.log('cellIndex:', cellIndex);
                var cell = rowCells[cellIndex];
                this.debug && console.log('cell:', cell);

                var cellEventsFound = this.countEventsInCell(cell);

                if (this.env === PROD_ENV) {
                    cell = cell;
                } else if (this.env === TEST_ENV) {
                    cell = [rowIndex, cellIndex];
                }

                // Determine if current top cell should be cleared now that it has the maximum number of events per
                // cell.
                if (this.topCellDate !== undefined &&
                    cellEventsFound === this.options.maxEventsPerCell) {
                    var cellDate = this.getCellDate(cell);
                    if (cellDate === this.topCellDate) {
                        this.topCellDate = undefined;
                    }
                }

                if (cellEventsFound < this.options.maxEventsPerCell) {
                    topCell = cell;
                    this.debug && console.groupEnd();
                    break outer_loop;
                } else {
                    this.debug && console.log('ELSE');
                }
            }

            this.debug && console.groupEnd();
        }

        this.debug && console.log('topCell:', topCell);
        this.debug && console.groupEnd();
        return topCell;
    }

    getCellDate(cell) {
        this.debug && console.info('getCellDate');
        this.debug && console.log('cell:', cell);
        var cellDate;
        if (this.env === PROD_ENV) {
            // "7 events, Thursday, October 17".
            var cellDescription = cell.querySelector('h2').innerText;

            // "October 17".
            var monthDate = cellDescription.match(/ events?, .*day, (.*?)$/)[1];
            this.debug && console.log('monthDate:', monthDate);

            // "Oct 17".
            monthDate = monthDate.substr(0, 3) + ' ' + monthDate.split(' ')[1];
            this.debug && console.log('monthDate:', monthDate);

            // "Oct 17, 2019".
            var monthDateYear = monthDate + ', ' + (new Date()).getFullYear();
            this.debug && console.log('monthDateYear:', monthDateYear);

            cellDate = monthDateYear;
        } else if (this.env === TEST_ENV) {
            var rowIndex = cell[0];
            var cellIndex = cell[1];
            cellDate = this.options.cellDates[rowIndex][cellIndex];
        }
        this.debug && console.log('cellDate:', cellDate);
        return cellDate;
    }

    getTopCellDate(calendarGridRows) {
        this.debug && console.info('getTopCellDate');

        // Calculate if cell date is older than the current top cell date only when a top cell is found.
        var topCell = this.findTopCell(calendarGridRows);
        if (topCell !== undefined) {
            var cellDate = this.getCellDate(topCell);
            if (this.topCellDate === undefined) {
                this.debug && console.log('using newly calculated cellDate:', cellDate);
                this.topCellDate = cellDate;
            } else {
                this.debug && console.log('comparing cellDate %s to current topCellDate %s', cellDate, this.topCellDate);
                if (this._getDateComparisonObject(cellDate) < this._getDateComparisonObject(this.topCellDate)) {
                    this.debug && console.log('updating current topCellDate');
                    this.topCellDate = cellDate;
                } else {
                    this.debug && console.log('keeping current topCellDate');
                }
            }
        }

        this.debug && console.log('topCellDate:', this.topCellDate);
        return this.topCellDate;
    }

    setOption(option, value) {
        this.options[option] = value;
    }

    _getDateComparisonObject(date) {
        return new Date(date).getTime();
    }
}

if (typeof(window) === 'undefined') {
    module.exports = GoogleCalendarMoveToDate
}
<commit_msg>Separate out variable<commit_after>const TEST_ENV = 'TEST';
const PROD_ENV = 'PROD';

class GoogleCalendarMoveToDate {
    // Maximum number of events to keep in a cell.
    #DEFAULT_MAX_EVENTS_PER_CELL = 14;

    // Oldest available cell date that has been found and should be used.
    topCellDate;

    constructor(options) {
        this.options = options;
        this.options.maxEventsPerCell = this.options.maxEventsPerCell || this.#DEFAULT_MAX_EVENTS_PER_CELL;
        this.env = options.env;
        this.debug = options.debug ? true : false;
    }

    findCellsInRow(row) {
        this.debug && console.info('findCellsInRow');
        this.debug && console.log('row:', row);
        var rowCells;
        if (this.env === PROD_ENV) {
            rowCells = row.querySelectorAll('[role="gridcell"]');
        } else if (this.env === TEST_ENV) {
            rowCells = row;
        }
        this.debug && console.log('rowCells:', rowCells);
        return rowCells;
    }

    clearTopCellDate() {
        this.debug && console.info('clearTopCellDate');
        this.topCellDate = undefined;
    }

    countEventsInCell(cell) {
        this.debug && console.info('countEventsInCell');
        this.debug && console.log('cell:', cell);
        var cellEventsFound;
        if (this.env === PROD_ENV) {
            var cellEvents = cell.querySelectorAll('[data-eventid]');
            cellEventsFound = cellEvents.length;
            var moreCellEvents = cell.querySelector('[data-opens-day-overview]');
            if (moreCellEvents) {
                cellEventsFound += parseInt(moreCellEvents.innerText.match(/(\d+) more/)[1]);
            }
        } else if (this.env === TEST_ENV) {
            var cellEvents = cell;
            cellEventsFound = cellEvents.length;
        }
        this.debug && console.log('cellEventsFound:', cellEventsFound);
        return cellEventsFound;
    }

    findTopCell(cells) {
        // Find first top-right most cell in current view containing a non-full number of events.
        this.debug && console.group('findTopCell');
        this.debug && console.log('cells:', cells);
        var topCell;

        // Check top to bottom.
        outer_loop:
        for (var rowIndex = 0; rowIndex < cells.length; rowIndex++) {
            this.debug && console.group('rowIndex:', rowIndex);

            var row = cells[rowIndex];
            this.debug && console.log('row:', row);

            var rowCells = this.findCellsInRow(row);
            // Check right to left.
            for (var cellIndex = rowCells.length - 1; cellIndex >= 0; cellIndex--) {
                this.debug && console.log('cellIndex:', cellIndex);
                var cell = rowCells[cellIndex];
                this.debug && console.log('cell:', cell);

                var cellEventsFound = this.countEventsInCell(cell);

                if (this.env === PROD_ENV) {
                    cell = cell;
                } else if (this.env === TEST_ENV) {
                    cell = [rowIndex, cellIndex];
                }

                // Determine if current top cell should be cleared now that it has the maximum number of events per
                // cell.
                if (this.topCellDate !== undefined &&
                    cellEventsFound === this.options.maxEventsPerCell) {
                    var cellDate = this.getCellDate(cell);
                    if (cellDate === this.topCellDate) {
                        this.topCellDate = undefined;
                    }
                }

                if (cellEventsFound < this.options.maxEventsPerCell) {
                    topCell = cell;
                    this.debug && console.groupEnd();
                    break outer_loop;
                } else {
                    this.debug && console.log('ELSE');
                }
            }

            this.debug && console.groupEnd();
        }

        this.debug && console.log('topCell:', topCell);
        this.debug && console.groupEnd();
        return topCell;
    }

    getCellDate(cell) {
        this.debug && console.info('getCellDate');
        this.debug && console.log('cell:', cell);
        var cellDate;
        if (this.env === PROD_ENV) {
            // "7 events, Thursday, October 17".
            var cellDescription = cell.querySelector('h2').innerText;

            // "October 17".
            var monthDate = cellDescription.match(/ events?, .*day, (.*?)$/)[1];
            this.debug && console.log('monthDate:', monthDate);

            // "Oct 17".
            monthDate = monthDate.substr(0, 3) + ' ' + monthDate.split(' ')[1];
            this.debug && console.log('monthDate:', monthDate);

            // "2019".
            var calendarYear = (new Date()).getFullYear();

            // "Oct 17, 2019".
            var monthDateYear = monthDate + ', ' + calendarYear;
            this.debug && console.log('monthDateYear:', monthDateYear);

            cellDate = monthDateYear;
        } else if (this.env === TEST_ENV) {
            var rowIndex = cell[0];
            var cellIndex = cell[1];
            cellDate = this.options.cellDates[rowIndex][cellIndex];
        }
        this.debug && console.log('cellDate:', cellDate);
        return cellDate;
    }

    getTopCellDate(calendarGridRows) {
        this.debug && console.info('getTopCellDate');

        // Calculate if cell date is older than the current top cell date only when a top cell is found.
        var topCell = this.findTopCell(calendarGridRows);
        if (topCell !== undefined) {
            var cellDate = this.getCellDate(topCell);
            if (this.topCellDate === undefined) {
                this.debug && console.log('using newly calculated cellDate:', cellDate);
                this.topCellDate = cellDate;
            } else {
                this.debug && console.log('comparing cellDate %s to current topCellDate %s', cellDate, this.topCellDate);
                if (this._getDateComparisonObject(cellDate) < this._getDateComparisonObject(this.topCellDate)) {
                    this.debug && console.log('updating current topCellDate');
                    this.topCellDate = cellDate;
                } else {
                    this.debug && console.log('keeping current topCellDate');
                }
            }
        }

        this.debug && console.log('topCellDate:', this.topCellDate);
        return this.topCellDate;
    }

    setOption(option, value) {
        this.options[option] = value;
    }

    _getDateComparisonObject(date) {
        return new Date(date).getTime();
    }
}

if (typeof(window) === 'undefined') {
    module.exports = GoogleCalendarMoveToDate
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

define([
    'jquery',
    'underscore',
    'find/app/model/document-model',
    'text!find/templates/app/page/colorbox-controls.html',
    'text!find/templates/app/page/view/document-content.html',
    'text!find/templates/app/page/view/audio-player.html',
    'text!find/templates/app/page/view/video-player.html',
    'text!find/templates/app/page/view/view-document.html',
    'i18n!find/nls/bundle'
], function ($, _, DocumentModel, colorboxControlsTemplate, documentContentTemplateString, audioPlayerTemplateString, videoPlayerTemplateString, viewDocumentTemplateString, i18n) {

    'use strict';

    var SIZE = '90%';
    var window = $(window);
    var isUrlRegex = /^https?:\/\//;

    var documentContentTemplate = _.template(documentContentTemplateString);
    var audioPlayerTemplate = _.template(audioPlayerTemplateString);
    var videoPlayerTemplate = _.template(videoPlayerTemplateString);
    var viewDocumentTemplate = _.template(viewDocumentTemplateString);

    function fancyButtonOverride() {
        $('#colorbox').append(_.template(colorboxControlsTemplate));
        $('.nextBtn').on('click', handleNextResult);
        $('.prevBtn').on('click', handlePrevResult);
    }

    function handlePrevResult() {
        $.colorbox.prev();
    }

    function handleNextResult() {
        $.colorbox.next();
    }

    function onResize() {
        $.colorbox.resize({width: SIZE, height: SIZE});
    }

    function colorboxArguments(options, isUrl) {
        var args = {
            current: '{current} of {total}',
            height: '70%',
            iframe: false,
            rel: options.grouping,
            width: '70%',
            onClosed: function () {
                window.off('resize', onResize);
            },
            onComplete: _.bind(function () {
                $('#cboxPrevious, #cboxNext').remove(); //removing default colorbox nav buttons

                var $iframe = $('.view-server-page');

                $iframe.on('load', function () {
                    $('.view-server-loading-indicator').addClass('hidden');
                    $('.view-server-page').removeClass('hidden');

                    // View server adds script tags to rendered HTML documents, which are blocked by the application
                    // This replicates their functionality
                    $iframe.contents().find('.InvisibleAbsolute').hide();
                });

                // Adding the source attribute after the colorbox has loaded prevents the iframe from loading
                // a very quick response (such as an error) before the listener is attached
                $iframe.attr("src", options.href);

                window.resize(onResize);
            }, this)
        };

        var contentType = options.model.get('contentType') || '';

        var identifyMedia = function (mediaType) {
            return contentType.indexOf(mediaType) === 0;
        };

        var url = options.model.get('url');

        var content;
        if (identifyMedia('audio') && url) {
            content = audioPlayerTemplate({
                url: url,
                offset: options.model.get('offset')
            });
        } else if (identifyMedia('video') && url) {
            content = videoPlayerTemplate({
                url: url,
                offset: options.model.get('offset')
            });
        } else {
            content = documentContentTemplate({
                i18n: i18n
            });
        }

        args.html = viewDocumentTemplate({
            src: isUrl ?  options.model.get('reference') : options.href,
            i18n: i18n,
            model: options.model,
            content: content
        });

        return args;
    }

    function isURL(reference) {
        return isUrlRegex.test(reference);
    }

    function nearNativeOrTab(options, reference, targetNode, triggerNode) {
        var isUrl = isURL(reference);
        var colorboxArgs = colorboxArguments(options, isUrl);

        if (triggerNode) {
            triggerNode.colorbox(colorboxArgs);
        }

        // web documents should open the original document in a new tab
        if (isUrl) {
            targetNode.attr({
                href: reference,
                target: "_blank"
            });
        } else if (triggerNode) {
            targetNode.click(function(e) {
                e.preventDefault();
                triggerNode.colorbox(_.extend({open: true}, colorboxArgs));
            });
        } else {
            targetNode.colorbox(colorboxArgs);
        }
    }

    return {
        fancyButtonOverride: fancyButtonOverride,
        nearNativeOrTab: nearNativeOrTab
    }
});<commit_msg>[CSA-1425] fixed view server iframe resizing [rev:matthew.gordon2]<commit_after>/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

define([
    'jquery',
    'underscore',
    'find/app/model/document-model',
    'text!find/templates/app/page/colorbox-controls.html',
    'text!find/templates/app/page/view/document-content.html',
    'text!find/templates/app/page/view/audio-player.html',
    'text!find/templates/app/page/view/video-player.html',
    'text!find/templates/app/page/view/view-document.html',
    'i18n!find/nls/bundle'
], function ($, _, DocumentModel, colorboxControlsTemplate, documentContentTemplateString, audioPlayerTemplateString, videoPlayerTemplateString, viewDocumentTemplateString, i18n) {

    'use strict';

    var SIZE = '90%';
    var $window = $(window);
    var isUrlRegex = /^https?:\/\//;

    var documentContentTemplate = _.template(documentContentTemplateString);
    var audioPlayerTemplate = _.template(audioPlayerTemplateString);
    var videoPlayerTemplate = _.template(videoPlayerTemplateString);
    var viewDocumentTemplate = _.template(viewDocumentTemplateString);

    function fancyButtonOverride() {
        $('#colorbox').append(_.template(colorboxControlsTemplate));
        $('.nextBtn').on('click', handleNextResult);
        $('.prevBtn').on('click', handlePrevResult);
    }

    function handlePrevResult() {
        $.colorbox.prev();
    }

    function handleNextResult() {
        $.colorbox.next();
    }

    function onResize() {
        $.colorbox.resize({width: SIZE, height: SIZE});
    }

    function colorboxArguments(options, isUrl) {
        var args = {
            current: '{current} of {total}',
            height: '70%',
            iframe: false,
            rel: options.grouping,
            width: '70%',
            onClosed: function () {
                $window.off('resize', onResize);
            },
            onComplete: _.bind(function () {
                $('#cboxPrevious, #cboxNext').remove(); //removing default colorbox nav buttons

                var $iframe = $('.view-server-page');

                $iframe.on('load', function () {
                    $('.view-server-loading-indicator').addClass('hidden');
                    $('.view-server-page').removeClass('hidden');

                    // View server adds script tags to rendered HTML documents, which are blocked by the application
                    // This replicates their functionality
                    $iframe.contents().find('.InvisibleAbsolute').hide();
                });

                // Adding the source attribute after the colorbox has loaded prevents the iframe from loading
                // a very quick response (such as an error) before the listener is attached
                $iframe.attr("src", options.href);

                $window.resize(onResize);
            }, this)
        };

        var contentType = options.model.get('contentType') || '';

        var identifyMedia = function (mediaType) {
            return contentType.indexOf(mediaType) === 0;
        };

        var url = options.model.get('url');

        var content;
        if (identifyMedia('audio') && url) {
            content = audioPlayerTemplate({
                url: url,
                offset: options.model.get('offset')
            });
        } else if (identifyMedia('video') && url) {
            content = videoPlayerTemplate({
                url: url,
                offset: options.model.get('offset')
            });
        } else {
            content = documentContentTemplate({
                i18n: i18n
            });
        }

        args.html = viewDocumentTemplate({
            src: isUrl ?  options.model.get('reference') : options.href,
            i18n: i18n,
            model: options.model,
            content: content
        });

        return args;
    }

    function isURL(reference) {
        return isUrlRegex.test(reference);
    }

    function nearNativeOrTab(options, reference, targetNode, triggerNode) {
        var isUrl = isURL(reference);
        var colorboxArgs = colorboxArguments(options, isUrl);

        if (triggerNode) {
            triggerNode.colorbox(colorboxArgs);
        }

        // web documents should open the original document in a new tab
        if (isUrl) {
            targetNode.attr({
                href: reference,
                target: "_blank"
            });
        } else if (triggerNode) {
            targetNode.click(function(e) {
                e.preventDefault();
                triggerNode.colorbox(_.extend({open: true}, colorboxArgs));
            });
        } else {
            targetNode.colorbox(colorboxArgs);
        }
    }

    return {
        fancyButtonOverride: fancyButtonOverride,
        nearNativeOrTab: nearNativeOrTab
    }
});<|endoftext|>


<commit_before>Ext.namespace('Gemma');

/**
 * need to set geneId as config
 */
Gemma.GeneAllenBrainAtlasImages =  Ext.extend(Ext.Panel, {
	geneId: null,
	padding:10,
					defaults:{
						border:false
					},
	initComponent: function(){

		Gemma.GeneAllenBrainAtlasImages.superclass.initComponent.call(this);
		this.on('render', function(){
			if (!this.loadMask) {
				this.loadMask = new Ext.LoadMask(this.getEl(), {
					msg: "Loading ...",
					msgCls: 'absolute-position-loading-mask ext-el-mask-msg x-mask-loading'
				});
			}
			this.loadMask.show();
			GeneController.loadAllenBrainImages(this.geneId, function(imageObjects){
			console.log(imageObjects[0]);

			this.loadMask.hide();
			if(!imageObjects || imageObjects.length === 0){
				this.add({html:'No images available'});

			}else{

				var img = imageObjects[0];
				var homologueText = (img.usingHomologue)? 'Images are for homologous mouse gene: '+
						''+
						img.abaHomologousMouseGene.officialSymbol+' ['+img.abaHomologousMouseGene.taxonCommonName+']':'';
				this.add({
					html:'
Allen Brain Atlas expression pattern'+
							''+
				' '+
				''+
				 ' '+
				'
'+'
'+homologueText+'
'
				});
				var i;
				for(i = 0; i< imageObjects.length; i++){
					img = imageObjects[i];
				this.add({
					html: '
'+
						''+
						' '+
						'
'
				});
				}
				this.doLayout();
			}

			}.createDelegate(this));
		});
	}
});
Ext.reg('geneallenbrainatlasimages',Gemma.GeneAllenBrainAtlasImages);

Gemma.geneLinkOutPopUp = function(abaImageUrl) {

	if (abaImageUrl == null)
		return;

	var abaWindowId = "geneDetailsAbaWindow";
	var win = Ext.getCmp(abaWindowId);
	if (win != null) {
		win.close();
	}

	win = new Ext.Window({
		html : "",
		id : abaWindowId,
		stateful : false,
		title : ""
			// ,
			// width : 500,
			// height : 400,
			// autoScroll : true
		});
	win.show(this);

};<commit_msg>removed console statement<commit_after>Ext.namespace('Gemma');

/**
 * need to set geneId as config
 */
Gemma.GeneAllenBrainAtlasImages =  Ext.extend(Ext.Panel, {
	geneId: null,
	padding:10,
					defaults:{
						border:false
					},
	initComponent: function(){

		Gemma.GeneAllenBrainAtlasImages.superclass.initComponent.call(this);
		this.on('render', function(){
			if (!this.loadMask) {
				this.loadMask = new Ext.LoadMask(this.getEl(), {
					msg: "Loading ...",
					msgCls: 'absolute-position-loading-mask ext-el-mask-msg x-mask-loading'
				});
			}
			this.loadMask.show();
			GeneController.loadAllenBrainImages(this.geneId, function(imageObjects){

			this.loadMask.hide();
			if(!imageObjects || imageObjects.length === 0){
				this.add({html:'No images available'});

			}else{

				var img = imageObjects[0];
				var homologueText = (img.usingHomologue)? 'Images are for homologous mouse gene: '+
						''+
						img.abaHomologousMouseGene.officialSymbol+' ['+img.abaHomologousMouseGene.taxonCommonName+']':'';
				this.add({
					html:'
Allen Brain Atlas expression pattern'+
							''+
				' '+
				''+
				 ' '+
				'
'+'
'+homologueText+'
'
				});
				var i;
				for(i = 0; i< imageObjects.length; i++){
					img = imageObjects[i];
				this.add({
					html: '
'+
						''+
						' '+
						'
'
				});
				}
				this.doLayout();
			}

			}.createDelegate(this));
		});
	}
});
Ext.reg('geneallenbrainatlasimages',Gemma.GeneAllenBrainAtlasImages);

Gemma.geneLinkOutPopUp = function(abaImageUrl) {

	if (abaImageUrl == null)
		return;

	var abaWindowId = "geneDetailsAbaWindow";
	var win = Ext.getCmp(abaWindowId);
	if (win != null) {
		win.close();
	}

	win = new Ext.Window({
		html : "",
		id : abaWindowId,
		stateful : false,
		title : ""
			// ,
			// width : 500,
			// height : 400,
			// autoScroll : true
		});
	win.show(this);

};<|endoftext|>


<commit_before>if (typeof(com) == 'undefined') com = {};
if (typeof(com.atlassian) == 'undefined') com.atlassian = {};
if (typeof(com.atlassian.jira) == 'undefined') com.atlassian.jira = {};
if (typeof(com.atlassian.jira.dvcs) == 'undefined') com.atlassian.jira.dvcs = {};

com.atlassian.jira.dvcs.showChangesetByFork = function(node, repoId, repoName, repoUrl) {

    // hide all changesets CommitPanels
    AJS.$('#' + node + ' .CommitPanel').each(function(n, el) {
        $(el).hide();
    });

    // show only that which is from given repository
    AJS.$('#' + node + '-' + repoId).show();

    registerForksTooltip(node, repoName, repoUrl);
}

com.atlassian.jira.dvcs.registerForksTooltip = function(node, repoName, repoUrl) {
    com.atlassian.jira.dvcs.registerInlineDialogTooltip(AJS.$('#fork-drop-down-' + node), "This changeset is present in multiple repositories (forks). Currently showing " + repoName + ".");
}

com.atlassian.jira.dvcs.registerInlineDialogTooltip = function (element, body) {
    AJS.InlineDialog(AJS.$(element), 'tooltip_' + AJS.$(element).attr('id'),
            function(content, trigger, showPopup) {
                content.css({'padding' : '10px'}).html(body);
                showPopup();
                return false;
            },
            {onHover : true, hideDelay : 200, showDelay : 1000, arrowOffsetX : -8, offsetX : -80, addActiveClass : false}
        );
}
<commit_msg>BBC-565 Adding semicolons to be compatible with IE<commit_after>if (typeof(com) == 'undefined') com = {};
if (typeof(com.atlassian) == 'undefined') com.atlassian = {};
if (typeof(com.atlassian.jira) == 'undefined') com.atlassian.jira = {};
if (typeof(com.atlassian.jira.dvcs) == 'undefined') com.atlassian.jira.dvcs = {};

com.atlassian.jira.dvcs.showChangesetByFork = function(node, repoId, repoName, repoUrl) {

    // hide all changesets CommitPanels
    AJS.$('#' + node + ' .CommitPanel').each(function(n, el) {
        $(el).hide();
    });

    // show only that which is from given repository
    AJS.$('#' + node + '-' + repoId).show();

    registerForksTooltip(node, repoName, repoUrl);
};

com.atlassian.jira.dvcs.registerForksTooltip = function(node, repoName, repoUrl) {
    com.atlassian.jira.dvcs.registerInlineDialogTooltip(AJS.$('#fork-drop-down-' + node), "This changeset is present in multiple repositories (forks). Currently showing " + repoName + ".");
};

com.atlassian.jira.dvcs.registerInlineDialogTooltip = function (element, body) {
    AJS.InlineDialog(AJS.$(element), 'tooltip_' + AJS.$(element).attr('id'),
            function(content, trigger, showPopup) {
                content.css({'padding' : '10px'}).html(body);
                showPopup();
                return false;
            },
            {onHover : true, hideDelay : 200, showDelay : 1000, arrowOffsetX : -8, offsetX : -80, addActiveClass : false}
        );
};
<|endoftext|>